repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
bonitasoft-labs/bpmn-js
|
src/component/mxgraph/initializer.ts
|
<filename>src/component/mxgraph/initializer.ts
/**
* Copyright 2021 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import factory, { type mxGraphExportObject } from 'mxgraph';
export const mxgraph = initialize();
declare global {
interface Window {
mxForceIncludes: boolean;
mxLoadResources: boolean;
mxLoadStylesheets: boolean;
mxResourceExtension: string;
}
}
function initialize(): mxGraphExportObject {
// set options globally, as it is not working when passing options to the factory (https://github.com/jgraph/mxgraph/issues/479)
// Required otherwise 'Uncaught ReferenceError: assignment to undeclared variable mx...'
window.mxForceIncludes = false;
window.mxLoadResources = false;
// Required otherwise we got 'Uncaught ReferenceError: assignment to undeclared variable mx...'
window.mxLoadStylesheets = false;
window.mxResourceExtension = '.txt';
return factory({});
}
|
bonitasoft-labs/bpmn-js
|
dev/ts/utils/internal-helpers.ts
|
/**
* Copyright 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { log } from './shared-helpers';
export function stringify(value: unknown): string {
return JSON.stringify(value, undefined, 2);
}
export function _log(header: string, message: unknown, ...optionalParams: unknown[]): void {
// eslint-disable-next-line no-console
console.info(header + ' ' + message, ...optionalParams);
}
export function logStartup(message?: string, ...optionalParams: unknown[]): void {
_log('[DEMO STARTUP]', message, ...optionalParams);
}
export function logErrorAndOpenAlert(error: unknown, alertMsg?: string): void {
console.error(`[DEMO]`, error);
window.alert(alertMsg ?? error);
}
export function logDownload(message?: unknown, ...optionalParams: unknown[]): void {
_log('[DEMO DOWNLOAD]', message, ...optionalParams);
}
export function fetchBpmnContent(url: string): Promise<string> {
log(`Fetching BPMN content from url ${url}`);
return fetch(url).then(response => {
if (!response.ok) {
throw Error(String(response.status));
}
return response.text();
});
}
|
bonitasoft-labs/bpmn-js
|
dev/ts/component/ThemedBpmnVisualization.ts
|
/**
* Copyright 2022 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { BpmnVisualization, FlowKind, ShapeBpmnElementKind, ShapeUtil, StyleConfigurator } from '../../../src/bpmn-visualization';
import { logStartup } from '../utils/internal-helpers';
import { mxgraph } from '../../../src/component/mxgraph/initializer';
interface Theme {
defaultStrokeColor: string;
defaultFontColor: string;
defaultFillColor: string;
endEventFillColor: string;
endEventStrokeColor: string;
startEventFillColor: string;
startEventStrokeColor: string;
taskFillColor: string;
laneFillColor: string;
poolFillColor: string;
catchAndThrowEventStrokeColor?: string;
flowColor?: string;
}
const themes = new Map<string, Theme>([
[
'dark',
{
defaultStrokeColor: '#c0ddeb',
defaultFontColor: 'white',
defaultFillColor: '#334352',
endEventFillColor: 'pink',
endEventStrokeColor: 'FireBrick',
startEventFillColor: 'DarkSeaGreen',
startEventStrokeColor: 'DarkGreen',
taskFillColor: '#5c8599',
laneFillColor: '#2b3742',
poolFillColor: '#232b33',
},
],
[
'brown',
{
defaultStrokeColor: '#414666',
defaultFillColor: '#ede7e1',
defaultFontColor: '#414666',
flowColor: '#666666',
endEventFillColor: 'pink',
endEventStrokeColor: 'FireBrick',
startEventFillColor: 'DarkSeaGreen',
startEventStrokeColor: 'DarkGreen',
taskFillColor: '#dadce8',
laneFillColor: '#d4c3b2',
poolFillColor: '#d1b9a1',
catchAndThrowEventStrokeColor: '#377f87',
},
],
]);
export class ThemedBpmnVisualization extends BpmnVisualization {
configureTheme(name: string): boolean {
if (name == 'default') {
new StyleConfigurator(this.graph).configureStyles();
return true;
}
const theme = themes.get(name);
if (!theme) {
return false;
}
// we are not using mxgraph constants here to show another way to configure the style
const styleSheet = this.graph.getStylesheet();
// EVENTS
ShapeUtil.eventKinds().forEach(kind => {
let fillColor;
let strokeColor;
switch (kind) {
case 'endEvent':
fillColor = theme.endEventFillColor;
strokeColor = theme.endEventStrokeColor;
break;
case 'startEvent':
fillColor = theme.startEventFillColor;
strokeColor = theme.startEventStrokeColor;
break;
case 'intermediateCatchEvent':
case 'intermediateThrowEvent':
case 'boundaryEvent':
fillColor = theme.defaultFillColor;
strokeColor = theme.catchAndThrowEventStrokeColor ?? theme.defaultStrokeColor;
break;
default:
fillColor = theme.defaultFillColor;
strokeColor = theme.defaultStrokeColor;
break;
}
const style = styleSheet.styles[kind];
style['fillColor'] = fillColor;
style['strokeColor'] = strokeColor;
});
// TASKS
ShapeUtil.taskKinds().forEach(kind => {
const style = styleSheet.styles[kind];
style['fillColor'] = theme.taskFillColor;
style['fontColor'] = theme.defaultFontColor; // TODO extra config
});
// CALL ACTIVITIES
const callActivityStyle = styleSheet.styles[ShapeBpmnElementKind.CALL_ACTIVITY];
callActivityStyle['fillColor'] = theme.taskFillColor;
callActivityStyle['fontColor'] = theme.defaultFontColor;
// POOL
const poolStyle = styleSheet.styles[ShapeBpmnElementKind.POOL];
poolStyle['fillColor'] = theme.poolFillColor;
poolStyle['swimlaneFillColor'] = theme.defaultFillColor;
// LANE
const laneStyle = styleSheet.styles[ShapeBpmnElementKind.LANE];
laneStyle['fillColor'] = theme.laneFillColor;
// DEFAULTS
const defaultVertexStyle = styleSheet.getDefaultVertexStyle();
defaultVertexStyle['fontColor'] = theme.defaultFontColor;
defaultVertexStyle['fillColor'] = theme.defaultFillColor;
defaultVertexStyle['strokeColor'] = theme.defaultStrokeColor;
const defaultEdgeStyle = styleSheet.getDefaultEdgeStyle();
defaultEdgeStyle['fontColor'] = theme.defaultFontColor;
defaultEdgeStyle['fillColor'] = theme.defaultFillColor;
defaultEdgeStyle['strokeColor'] = theme.flowColor ?? theme.defaultStrokeColor;
// theme configuration completed
return true;
}
configureSequenceFlowColor(color: string): void {
logStartup(`Use dedicated ${color} color for sequence flows`);
const stylesheet = this.graph.getStylesheet();
// directly access the 'styles' map to update values. Using stylesheet.getCellStyle returns a copy of the style
const seqFlowStyle = stylesheet.styles[FlowKind.SEQUENCE_FLOW];
seqFlowStyle[mxgraph.mxConstants.STYLE_STROKECOLOR] = color;
seqFlowStyle[mxgraph.mxConstants.STYLE_FILLCOLOR] = color;
logStartup('Sequence flows style updated');
}
}
|
bonitasoft-labs/bpmn-js
|
src/component/mxgraph/shape/flow-shapes.ts
|
<gh_stars>1-10
/**
* Copyright 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { IconPainterProvider } from './render';
import { buildPaintParameter } from './render/icon-painter';
import { StyleUtils } from '../style';
import { MessageVisibleKind } from '../../../model/bpmn/internal/edge/kinds';
import { mxgraph } from '../initializer';
import type { mxAbstractCanvas2D, mxRectangle } from 'mxgraph';
/**
* @internal
*/
export class MessageFlowIconShape extends mxgraph.mxRectangleShape {
protected iconPainter = IconPainterProvider.get();
constructor(bounds: mxRectangle, fill: string, stroke: string, strokewidth: number) {
super(bounds, fill, stroke, strokewidth);
}
override paintVertexShape(c: mxAbstractCanvas2D, x: number, y: number, w: number, h: number): void {
const withFilledIcon = StyleUtils.getBpmnIsInitiating(this.style) === MessageVisibleKind.NON_INITIATING;
const paintParameter = buildPaintParameter({ canvas: c, x, y, width: w, height: h, shape: this, ratioFromParent: 1, isFilled: withFilledIcon });
this.iconPainter.paintEnvelopeIcon(paintParameter);
}
}
|
bonitasoft-labs/bpmn-js
|
test/integration/dom.overlays.test.ts
|
<filename>test/integration/dom.overlays.test.ts
/**
* Copyright 2021 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { OverlayEdgePosition, OverlayShapePosition } from '../../src/bpmn-visualization';
import { readFileSync } from '../helpers/file-helper';
import { overlayEdgePositionValues, overlayShapePositionValues } from '../helpers/overlays';
import { initializeBpmnVisualization } from './helpers/bpmn-visualization-initialization';
import { HtmlElementLookup } from './helpers/html-utils';
describe('Bpmn Elements registry - Overlay management', () => {
const bpmnVisualization = initializeBpmnVisualization();
const htmlElementLookup = new HtmlElementLookup(bpmnVisualization);
describe('BPMN Shape', () => {
it('Add one overlay to a BPMN shape', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/1-pool-3-lanes-message-start-end-intermediate-events.bpmn'));
htmlElementLookup.expectServiceTask('serviceTask_1_2');
// add a single overlay
const overlayLabel = '123';
bpmnVisualization.bpmnElementsRegistry.addOverlays('serviceTask_1_2', { label: overlayLabel, position: 'top-left' });
htmlElementLookup.expectServiceTask('serviceTask_1_2', { overlayLabel });
});
it.each(overlayShapePositionValues)("Ensure no issue when adding one overlay at position '%s' to a BPMN Shape", (position: OverlayShapePosition) => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/overlays/overlays.start.flow.task.gateway.bpmn'));
htmlElementLookup.expectExclusiveGateway('Gateway_1');
bpmnVisualization.bpmnElementsRegistry.addOverlays('Gateway_1', { label: 'Yes', position: position });
htmlElementLookup.expectExclusiveGateway('Gateway_1', { overlayLabel: 'Yes' });
});
it('Remove all overlays from a BPMN shape', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/1-pool-3-lanes-message-start-end-intermediate-events.bpmn'));
htmlElementLookup.expectServiceTask('serviceTask_1_2');
// remove all overlays
bpmnVisualization.bpmnElementsRegistry.addOverlays('serviceTask_1_2', { label: '8789', position: 'top-left' });
bpmnVisualization.bpmnElementsRegistry.removeAllOverlays('serviceTask_1_2');
htmlElementLookup.expectServiceTask('serviceTask_1_2');
});
});
describe('BPMN Edge', () => {
it.each(overlayEdgePositionValues)("Ensure no issue when adding one overlay at position '%s' to a BPMN Edge without waypoints", (position: OverlayEdgePosition) => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/overlays/overlays.start.flow.task.gateway.no.waypoints.bpmn'));
htmlElementLookup.expectSequenceFlow('Flow_1');
bpmnVisualization.bpmnElementsRegistry.addOverlays('Flow_1', { label: 'important', position: position });
htmlElementLookup.expectSequenceFlow('Flow_1', { overlayLabel: 'important' });
});
it.each(overlayEdgePositionValues)("Ensure no issue when adding one overlay at position '%s' to a BPMN Edge with waypoints", (position: OverlayEdgePosition) => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/overlays/overlays.edges.associations.complex.paths.bpmn'));
htmlElementLookup.expectAssociation('Association_3_waypoints');
bpmnVisualization.bpmnElementsRegistry.addOverlays('Association_3_waypoints', { label: 'warning', position: position });
htmlElementLookup.expectAssociation('Association_3_waypoints', { overlayLabel: 'warning' });
});
});
});
|
bonitasoft-labs/bpmn-js
|
src/component/parser/xml/BpmnXmlParser.ts
|
<filename>src/component/parser/xml/BpmnXmlParser.ts
/**
* Copyright 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { XMLParser, type X2jOptions } from 'fast-xml-parser';
import { decodeXML } from 'entities';
import type { BpmnJsonModel } from '../../../model/bpmn/json/BPMN20';
/**
* Parse bpmn xml source
* @internal
*/
export default class BpmnXmlParser {
private x2jOptions: Partial<X2jOptions> = {
attributeNamePrefix: '', // default to '@_'
removeNSPrefix: true,
ignoreAttributes: false,
parseAttributeValue: true, // ensure numbers are parsed as number, not as string
// entities management
processEntities: false, // If you don't have entities in your XML document then it is recommended to disable it for better performance.
attributeValueProcessor: (_name: string, val: string) => {
return decodeXML(val);
},
};
private xmlParser: XMLParser = new XMLParser(this.x2jOptions);
parse(xml: string): BpmnJsonModel {
let model: BpmnJsonModel;
try {
model = this.xmlParser.parse(xml);
} catch {
throw new Error('XML parsing failed. Invalid BPMN source.');
}
if (!model.definitions) {
// We currently don't validate the xml, so we don't detect xml validation error
// if 'definitions' is undefined, there is an Error later in the parsing code without explicit information
// So for now, throw a generic error that better explains the problem.
// See https://github.com/process-analytics/bpmn-visualization-js/issues/21 for improvement
throw new Error(`XML parsing failed. Unable to retrieve 'definitions' from the BPMN source.`);
}
return model;
}
}
|
bonitasoft-labs/bpmn-js
|
src/component/helpers/validators.ts
|
/**
* Copyright 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { ZoomConfiguration } from '../options';
/**
* @internal
*/
export function ensureInRange(value: number, min: number, max: number, defaultValue: number): number {
let inRangeValue = value == undefined ? defaultValue : value;
inRangeValue = Math.min(Math.max(inRangeValue, min), max);
return inRangeValue;
}
/**
* @internal
*/
export function ensurePositiveValue(input: number | undefined | null): number {
return Math.max(input || 0, 0);
}
/**
* Make sure the configuration parameters are defined and in range
* @param config the {@link ZoomConfiguration} to make valid
* @internal
*/
export function ensureValidZoomConfiguration(config: ZoomConfiguration): ZoomConfiguration {
const validatedConfig = config ?? {};
validatedConfig.debounceDelay = ensureInRange(validatedConfig.debounceDelay, 0, 100, 50);
validatedConfig.throttleDelay = ensureInRange(validatedConfig.throttleDelay, 0, 100, 50);
return validatedConfig;
}
|
bonitasoft-labs/bpmn-js
|
test/config/playwright.browser.logs.ts
|
/**
* Copyright 2021 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import debugLogger from 'debug';
import 'jest-playwright-preset';
// Allow getting browser console logs
// this is from https://playwright.dev/docs/api/class-page#page-event-console
const browserLog = debugLogger('bv:test:browser');
page.on('console', msg => browserLog('<%s> %s', msg.type(), msg.text()));
|
bonitasoft-labs/bpmn-js
|
src/component/mxgraph/shape/render/utils.ts
|
<gh_stars>10-100
/**
* Copyright 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ShapeBpmnMarkerKind } from '../../../../model/bpmn/internal';
const referenceOrderedMarkers = [
ShapeBpmnMarkerKind.LOOP,
ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL,
ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL,
ShapeBpmnMarkerKind.COMPENSATION,
ShapeBpmnMarkerKind.EXPAND,
ShapeBpmnMarkerKind.ADHOC,
];
/**
* @internal
*/
export function orderActivityMarkers(markers: string[]): string[] {
const orderedMarkers: string[] = referenceOrderedMarkers.filter(marker => markers.includes(marker));
// Put extra remaining at the end of the ordered markers, in the order they appear in the original array
markers.filter(marker => !orderedMarkers.includes(marker)).forEach(marker => orderedMarkers.push(marker));
return orderedMarkers;
}
|
bonitasoft-labs/bpmn-js
|
test/unit/component/parser/json/TestUtils.ts
|
<reponame>bonitasoft-labs/bpmn-js
/**
* Copyright 2021 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ShapeBpmnElementKind, ShapeUtil } from '../../../../../src/model/bpmn/internal';
import type BpmnModel from '../../../../../src/model/bpmn/internal/BpmnModel';
import type Shape from '../../../../../src/model/bpmn/internal/shape/Shape';
export const shapeBpmnElementKindForLabelTests = Object.values(ShapeBpmnElementKind)
.filter(kind => !ShapeUtil.isPoolOrLane(kind))
// group as label is managed by category
.filter(kind => kind != ShapeBpmnElementKind.GROUP)
// intermediate catch and boundary events require extra property no managed here
.filter(kind => ![ShapeBpmnElementKind.EVENT_BOUNDARY, ShapeBpmnElementKind.EVENT_INTERMEDIATE_CATCH].includes(kind))
.map(kind => [kind]);
export function getEventShapes(model: BpmnModel): Shape[] {
return model.flowNodes.filter(shape => ShapeUtil.isEvent(shape.bpmnElement.kind));
}
|
bonitasoft-labs/bpmn-js
|
src/bpmn-visualization.ts
|
<filename>src/bpmn-visualization.ts
/**
* Copyright 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// export types first, otherwise typedoc doesn't generate the subsequent doc correctly (no category and uses the file header instead of the actual TSDoc)
export * from './component/options';
export { BpmnVisualization } from './component/BpmnVisualization';
export * from './component/registry';
export type { Version } from './component/version';
export type { Navigation } from './component/navigation';
export * from './model/bpmn/internal';
// not part of the public API but needed for the custom theme examples
export { IconPainter } from './component/mxgraph/shape/render/icon-painter';
export { StyleConfigurator } from './component/mxgraph/config/StyleConfigurator';
export * from './component/mxgraph/style';
export * from './component/mxgraph/shape/render';
|
bonitasoft-labs/bpmn-js
|
src/model/bpmn/json/baseElement/flowNode/gateway.ts
|
/**
* Copyright 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { TExpression } from '../expression';
import type { TFlowNode } from '../flowElement';
// abstract="true"
export interface TGateway extends TFlowNode {
gatewayDirection?: tGatewayDirection; // default="Unspecified"
}
export interface TComplexGateway extends TGateway {
activationCondition?: TExpression;
default?: string;
}
export interface TEventBasedGateway extends TGateway {
instantiate?: boolean; // default="false"
eventGatewayType?: tEventBasedGatewayType; // default="Exclusive"
}
export interface TExclusiveGateway extends TGateway {
default?: string;
}
export interface TInclusiveGateway extends TGateway {
default?: string;
}
export type TParallelGateway = TGateway;
enum tEventBasedGatewayType {
Exclusive = 'Exclusive',
Parallel = 'Parallel',
}
enum tGatewayDirection {
Unspecified = 'Unspecified',
Converging = 'Converging',
Diverging = 'Diverging',
Mixed = 'Mixed',
}
|
bonitasoft-labs/bpmn-js
|
src/component/mxgraph/config/MarkerConfigurator.ts
|
<gh_stars>1-10
/**
* Copyright 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { MarkerIdentifier } from '../style';
import { mxgraph } from '../initializer';
import type { mxAbstractCanvas2D, mxCell, mxPoint, mxShape } from 'mxgraph';
/**
* @internal
*/
export default class MarkerConfigurator {
configureMarkers(): void {
this.registerArrowDashMarker();
}
private registerArrowDashMarker(): void {
// This implementation is adapted from the draw.io BPMN 'dash' marker
// https://github.com/jgraph/drawio/blob/f539f1ff362e76127dcc7e68b5a9d83dd7d4965c/src/main/webapp/js/mxgraph/Shapes.js#L2796
// prefix parameter name - common practice to acknowledge the fact that some parameter is unused (e.g. in TypeScript compiler)
const createMarker = (
c: mxAbstractCanvas2D,
_shape: mxShape,
_type: string,
pe: mxPoint,
unitX: number,
unitY: number,
size: number,
_source: mxCell,
strokewidth: number,
): (() => void) => {
const nx = unitX * (size + strokewidth + 4);
const ny = unitY * (size + strokewidth + 4);
return function () {
c.begin();
c.moveTo(pe.x - nx / 2 - ny / 2, pe.y - ny / 2 + nx / 2);
c.lineTo(pe.x + ny / 2 - (3 * nx) / 2, pe.y - (3 * ny) / 2 - nx / 2);
c.stroke();
};
};
mxgraph.mxMarker.addMarker(MarkerIdentifier.ARROW_DASH, createMarker);
}
}
|
bonitasoft-labs/bpmn-js
|
src/component/mxgraph/config/ShapeConfigurator.ts
|
/**
* Copyright 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { mxgraph } from '../initializer';
import type { mxCellState, mxImageShape, mxShape } from 'mxgraph';
import { ShapeBpmnElementKind } from '../../../model/bpmn/internal';
import { EndEventShape, EventShape, IntermediateEventShape, ThrowIntermediateEventShape } from '../shape/event-shapes';
import { EventBasedGatewayShape, ExclusiveGatewayShape, InclusiveGatewayShape, ParallelGatewayShape } from '../shape/gateway-shapes';
import {
BusinessRuleTaskShape,
CallActivityShape,
ManualTaskShape,
ReceiveTaskShape,
ScriptTaskShape,
SendTaskShape,
ServiceTaskShape,
SubProcessShape,
TaskShape,
UserTaskShape,
} from '../shape/activity-shapes';
import { TextAnnotationShape } from '../shape/text-annotation-shapes';
import { MessageFlowIconShape } from '../shape/flow-shapes';
import { BpmnStyleIdentifier } from '../style';
import { computeAllBpmnClassNamesOfCell } from '../renderer/style-utils';
import { MxGraphCustomOverlay } from '../overlay/custom-overlay';
import { OverlayBadgeShape } from '../overlay/shapes';
import { BpmnConnector } from '../shape/edges';
/**
* @internal
*/
export default class ShapeConfigurator {
configureShapes(): void {
this.initMxSvgCanvasPrototype();
this.initMxShapePrototype();
this.registerShapes();
this.initMxCellRendererCreateCellOverlays();
}
private registerShapes(): void {
// events
mxgraph.mxCellRenderer.registerShape(ShapeBpmnElementKind.EVENT_END, EndEventShape);
mxgraph.mxCellRenderer.registerShape(ShapeBpmnElementKind.EVENT_START, EventShape);
mxgraph.mxCellRenderer.registerShape(ShapeBpmnElementKind.EVENT_INTERMEDIATE_THROW, ThrowIntermediateEventShape);
mxgraph.mxCellRenderer.registerShape(ShapeBpmnElementKind.EVENT_INTERMEDIATE_CATCH, IntermediateEventShape);
mxgraph.mxCellRenderer.registerShape(ShapeBpmnElementKind.EVENT_BOUNDARY, IntermediateEventShape);
// gateways
mxgraph.mxCellRenderer.registerShape(ShapeBpmnElementKind.GATEWAY_EVENT_BASED, EventBasedGatewayShape);
mxgraph.mxCellRenderer.registerShape(ShapeBpmnElementKind.GATEWAY_EXCLUSIVE, ExclusiveGatewayShape);
mxgraph.mxCellRenderer.registerShape(ShapeBpmnElementKind.GATEWAY_INCLUSIVE, InclusiveGatewayShape);
mxgraph.mxCellRenderer.registerShape(ShapeBpmnElementKind.GATEWAY_PARALLEL, ParallelGatewayShape);
// activities
mxgraph.mxCellRenderer.registerShape(ShapeBpmnElementKind.SUB_PROCESS, SubProcessShape);
mxgraph.mxCellRenderer.registerShape(ShapeBpmnElementKind.CALL_ACTIVITY, CallActivityShape);
// tasks
mxgraph.mxCellRenderer.registerShape(ShapeBpmnElementKind.TASK, TaskShape);
mxgraph.mxCellRenderer.registerShape(ShapeBpmnElementKind.TASK_SERVICE, ServiceTaskShape);
mxgraph.mxCellRenderer.registerShape(ShapeBpmnElementKind.TASK_USER, UserTaskShape);
mxgraph.mxCellRenderer.registerShape(ShapeBpmnElementKind.TASK_RECEIVE, ReceiveTaskShape);
mxgraph.mxCellRenderer.registerShape(ShapeBpmnElementKind.TASK_SEND, SendTaskShape);
mxgraph.mxCellRenderer.registerShape(ShapeBpmnElementKind.TASK_MANUAL, ManualTaskShape);
mxgraph.mxCellRenderer.registerShape(ShapeBpmnElementKind.TASK_SCRIPT, ScriptTaskShape);
mxgraph.mxCellRenderer.registerShape(ShapeBpmnElementKind.TASK_BUSINESS_RULE, BusinessRuleTaskShape);
// artifacts
mxgraph.mxCellRenderer.registerShape(ShapeBpmnElementKind.TEXT_ANNOTATION, TextAnnotationShape);
// shapes for flows
mxgraph.mxCellRenderer.registerShape(BpmnStyleIdentifier.EDGE, BpmnConnector);
mxgraph.mxCellRenderer.registerShape(BpmnStyleIdentifier.MESSAGE_FLOW_ICON, MessageFlowIconShape);
}
private initMxSvgCanvasPrototype(): void {
// getTextCss is only used when creating foreignObject for label, so there is no impact on svg text that we use for Overlays.
// Analysis done for mxgraph@4.1.1, still apply to mxgraph@4.2.2
mxgraph.mxSvgCanvas2D.prototype.getTextCss = function () {
const s = this.state;
const lh = mxgraph.mxConstants.ABSOLUTE_LINE_HEIGHT ? s.fontSize * mxgraph.mxConstants.LINE_HEIGHT + 'px' : mxgraph.mxConstants.LINE_HEIGHT * this.lineHeightCorrection;
let css =
'display: inline-block; font-size: ' +
s.fontSize +
'px; ' +
'font-family: ' +
s.fontFamily +
'; color: ' +
s.fontColor +
'; line-height: ' +
lh +
// START Fix for issue #920 (https://github.com/process-analytics/bpmn-visualization-js/issues/920)
// This cannot be generalized for all mxgraph use cases. For instance, in an editor mode, we should be able to edit the text by clicking on it.
// Setting to 'none' prevent to capture click.
'; pointer-events: none' +
// (this.pointerEvents ? this.pointerEventsValue : 'none') +
// END OF Fix for issue #920
'; ';
if ((s.fontStyle & mxgraph.mxConstants.FONT_BOLD) == mxgraph.mxConstants.FONT_BOLD) {
css += 'font-weight: bold; ';
}
if ((s.fontStyle & mxgraph.mxConstants.FONT_ITALIC) == mxgraph.mxConstants.FONT_ITALIC) {
css += 'font-style: italic; ';
}
const deco = [];
if ((s.fontStyle & mxgraph.mxConstants.FONT_UNDERLINE) == mxgraph.mxConstants.FONT_UNDERLINE) {
deco.push('underline');
}
if ((s.fontStyle & mxgraph.mxConstants.FONT_STRIKETHROUGH) == mxgraph.mxConstants.FONT_STRIKETHROUGH) {
deco.push('line-through');
}
if (deco.length > 0) {
css += 'text-decoration: ' + deco.join(' ') + '; ';
}
return css;
};
}
private initMxShapePrototype(): void {
// The following is copied from the mxgraph mxShape implementation then converted to TypeScript and enriched for bpmn-visualization
// It is needed for adding the custom attributes that permits identification of the BPMN elements in the DOM
mxgraph.mxShape.prototype.createSvgCanvas = function () {
const canvas = new mxgraph.mxSvgCanvas2D(this.node, false);
canvas.strokeTolerance = this.pointerEvents ? this.svgStrokeTolerance : 0;
canvas.pointerEventsValue = this.svgPointerEvents;
const off = this.getSvgScreenOffset();
if (off != 0) {
this.node.setAttribute('transform', 'translate(' + off + ',' + off + ')');
} else {
this.node.removeAttribute('transform');
}
// START bpmn-visualization CUSTOMIZATION
// add attributes to be able to identify elements in DOM
if (this.state && this.state.cell) {
// 'this.state.style' = the style definition associated with the cell
// 'this.state.cell.style' = the style applied to the cell: 1st element: style name = bpmn shape name
const cell = this.state.cell;
// dialect = strictHtml is set means that current node holds an html label
let allBpmnClassNames = computeAllBpmnClassNamesOfCell(cell, this.dialect === mxgraph.mxConstants.DIALECT_STRICTHTML);
const extraCssClasses = this.state.style[BpmnStyleIdentifier.EXTRA_CSS_CLASSES];
if (extraCssClasses) {
allBpmnClassNames = allBpmnClassNames.concat(extraCssClasses);
}
this.node.setAttribute('class', allBpmnClassNames.join(' '));
this.node.setAttribute('data-bpmn-id', this.state.cell.id);
}
// END bpmn-visualization CUSTOMIZATION
canvas.minStrokeWidth = this.minSvgStrokeWidth;
if (!this.antiAlias) {
// Rounds all numbers in the SVG output to integers
canvas.format = function (value: string) {
return Math.round(parseFloat(value));
};
}
return canvas;
};
}
initMxCellRendererCreateCellOverlays(): void {
mxgraph.mxCellRenderer.prototype.createCellOverlays = function (state: mxCellState) {
const graph = state.view.graph;
const overlays = graph.getCellOverlays(state.cell);
let dict = null;
if (overlays != null) {
dict = new mxgraph.mxDictionary<mxShape>();
for (const currentOverlay of overlays) {
const shape = state.overlays != null ? state.overlays.remove(currentOverlay) : null;
if (shape != null) {
dict.put(currentOverlay, shape);
continue;
}
let overlayShape: mxShape;
// START bpmn-visualization CUSTOMIZATION
if (currentOverlay instanceof MxGraphCustomOverlay) {
overlayShape = new OverlayBadgeShape(currentOverlay.label, new mxgraph.mxRectangle(0, 0, 0, 0), currentOverlay.style);
} else {
overlayShape = new mxgraph.mxImageShape(new mxgraph.mxRectangle(0, 0, 0, 0), currentOverlay.image.src);
(<mxImageShape>overlayShape).preserveImageAspect = false;
}
// END bpmn-visualization CUSTOMIZATION
overlayShape.dialect = state.view.graph.dialect;
overlayShape.overlay = currentOverlay;
// The 'initializeOverlay' signature forces us to hardly cast the overlayShape
this.initializeOverlay(state, <mxImageShape>overlayShape);
this.installCellOverlayListeners(state, currentOverlay, overlayShape);
if (currentOverlay.cursor != null) {
overlayShape.node.style.cursor = currentOverlay.cursor;
}
// START bpmn-visualization CUSTOMIZATION
if (overlayShape instanceof OverlayBadgeShape) {
overlayShape.node.classList.add('overlay-badge');
overlayShape.node.setAttribute('data-bpmn-id', state.cell.id);
}
// END bpmn-visualization CUSTOMIZATION
dict.put(currentOverlay, overlayShape);
}
}
// Removes unused
if (state.overlays != null) {
// prefix parameter name - common practice to acknowledge the fact that some parameter is unused (e.g. in TypeScript compiler)
state.overlays.visit(function (_id: string, shape: mxShape) {
shape.destroy();
});
}
state.overlays = dict;
};
}
}
|
bonitasoft-labs/bpmn-js
|
scripts/utils/parseBpmn.ts
|
<filename>scripts/utils/parseBpmn.ts
/**
* Copyright 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as path from 'path';
import clipboardy from 'clipboardy';
import parseArgs from 'minimist';
import type BpmnModel from '../../src/model/bpmn/internal/BpmnModel';
import type { BpmnJsonModel } from '../../src/model/bpmn/json/BPMN20';
import BpmnXmlParser from '../../src/component/parser/xml/BpmnXmlParser';
import { newBpmnJsonParser } from '../../src/component/parser/json/BpmnJsonParser';
import { ParsingMessageCollector } from '../../src/component/parser/parsing-messages';
import { readFileSync } from '../../test/helpers/file-helper';
const __dirname = path.resolve();
const argv = parseArgs(process.argv.slice(2));
const bpmnFilePath = argv._[0];
const outputType = argv['output'] || 'json';
// eslint-disable-next-line no-console
console.info('Generating BPMN in the "%s" output type', outputType);
if (!bpmnFilePath) {
throw new Error('You must provide file path as 1st parameter for example: test/fixtures/bpmn/simple-start-task-end.bpmn ');
}
if (['json', 'model'].indexOf(outputType) == -1) {
throw new Error('--output parameter must be one of: json | model');
}
// eslint-disable-next-line no-console
console.info('Use BPMN diagram located at "%s"', bpmnFilePath);
const xmlParser = new BpmnXmlParser();
const json = xmlParser.parse(readFileSync(bpmnFilePath, 'utf-8', __dirname));
const prettyString = (object: BpmnJsonModel | BpmnModel): string => JSON.stringify(object, null, 2);
let result = '';
if (outputType === 'json') {
result = prettyString(json);
} else {
result = prettyString(newBpmnJsonParser(new ParsingMessageCollector()).parse(json));
}
// copy to clipboard
// disabling the copy is not officially supported, it currently fails on GitHub actions when running on Ubuntu 20.04. So disabling it only in this case.
// file:///home/runner/work/bpmn-visualization-js/bpmn-visualization-js/node_modules/clipboardy/lib/linux.js:16
// error = new Error('Couldn\'t find the `xsel` binary and fallback didn\'t work. On Debian/Ubuntu you can install xsel with: sudo apt install xsel');
// Error: Couldn't find the `xsel` binary and fallback didn't work. On Debian/Ubuntu you can install xsel with: sudo apt install xsel
// CI env variable when running on GitHub Actions: https://docs.github.com/en/actions/learn-github-actions/environment-variables#default-environment-variables
const isRunningOnCIWithLinuxOS = process.env.CI === 'true' && process.platform.startsWith('linux');
if (!isRunningOnCIWithLinuxOS) {
clipboardy.writeSync(result);
} else {
console.warn('No clipboard copy, as it is not supported in this environment');
}
/* eslint-disable no-console */
console.info('Output generated');
console.info(result);
|
bonitasoft-labs/bpmn-js
|
src/component/parser/json/converter/DiagramConverter.ts
|
<reponame>bonitasoft-labs/bpmn-js<gh_stars>1-10
/**
* Copyright 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Shape from '../../../../model/bpmn/internal/shape/Shape';
import Bounds from '../../../../model/bpmn/internal/Bounds';
import type ShapeBpmnElement from '../../../../model/bpmn/internal/shape/ShapeBpmnElement';
import { ShapeBpmnCallActivity, ShapeBpmnSubProcess } from '../../../../model/bpmn/internal/shape/ShapeBpmnElement';
import { Edge, Waypoint } from '../../../../model/bpmn/internal/edge/edge';
import type { Shapes } from '../../../../model/bpmn/internal/BpmnModel';
import type BpmnModel from '../../../../model/bpmn/internal/BpmnModel';
import Label, { Font } from '../../../../model/bpmn/internal/Label';
import { MessageVisibleKind } from '../../../../model/bpmn/internal/edge/kinds';
import type { BPMNDiagram, BPMNEdge, BPMNLabel, BPMNLabelStyle, BPMNShape } from '../../../../model/bpmn/json/BPMNDI';
import type { Point } from '../../../../model/bpmn/json/DC';
import type { ConvertedElements } from './utils';
import { ShapeBpmnCallActivityKind, ShapeBpmnMarkerKind, ShapeUtil } from '../../../../model/bpmn/internal';
import { ensureIsArray } from '../../../helpers/array-utils';
import type { ParsingMessageCollector } from '../../parsing-messages';
import { EdgeUnknownBpmnElementWarning, LabelStyleMissingFontWarning, ShapeUnknownBpmnElementWarning } from '../warnings';
/**
* @internal
*/
export default class DiagramConverter {
constructor(private convertedElements: ConvertedElements, private parsingMessageCollector: ParsingMessageCollector) {}
private convertedFonts: Map<string, Font> = new Map();
deserialize(bpmnDiagrams: Array<BPMNDiagram> | BPMNDiagram): BpmnModel {
const flowNodes: Shape[] = [];
const lanes: Shape[] = [];
const pools: Shape[] = [];
const edges: Edge[] = [];
const bpmnDiagram = ensureIsArray(bpmnDiagrams)[0];
if (bpmnDiagram) {
// Need to be done before deserialization of Shape and Edge, to link the converted fonts to them
this.deserializeFonts(bpmnDiagram.BPMNLabelStyle);
const plane = bpmnDiagram.BPMNPlane;
const convertedEdges = this.deserializeEdges(plane.BPMNEdge);
const convertedShapes = this.deserializeShapes(plane.BPMNShape);
flowNodes.push(...convertedShapes.flowNodes);
lanes.push(...convertedShapes.lanes);
pools.push(...convertedShapes.pools);
edges.push(...convertedEdges);
}
return { flowNodes, lanes, pools, edges };
}
private deserializeFonts(bpmnLabelStyle: Array<BPMNLabelStyle> | BPMNLabelStyle): void {
this.convertedFonts = new Map();
ensureIsArray(bpmnLabelStyle).forEach(labelStyle =>
ensureIsArray(labelStyle.Font).forEach(font =>
this.convertedFonts.set(labelStyle.id, new Font(font.name, font.size, font.isBold, font.isItalic, font.isUnderline, font.isStrikeThrough)),
),
);
}
private deserializeShapes(shapes: Array<BPMNShape> | BPMNShape): Shapes {
const convertedShapes: Shapes = { flowNodes: [], lanes: [], pools: [] };
ensureIsArray(shapes).forEach(shape => {
// flow nodes
if (this.deserializeShapeAndStoreIfFound(shape, convertedShapes.flowNodes, (bpmnElement: string) => this.convertedElements.findFlowNode(bpmnElement))) {
return;
}
// lane
if (this.deserializeShapeAndStoreIfFound(shape, convertedShapes.lanes, (bpmnElement: string) => this.convertedElements.findLane(bpmnElement))) {
return;
}
// pool
if (this.deserializeShapeAndStoreIfFound(shape, convertedShapes.pools, (bpmnElement: string) => this.convertedElements.findProcess(bpmnElement))) {
return;
}
// not found
this.parsingMessageCollector.warning(new ShapeUnknownBpmnElementWarning(shape.bpmnElement));
});
return convertedShapes;
}
private deserializeShapeAndStoreIfFound(shape: BPMNShape, storage: Array<Shape>, findShapeElement: (bpmnElement: string) => ShapeBpmnElement): boolean {
const element = this.deserializeShape(shape, findShapeElement);
if (element) {
storage.push(element);
return true;
}
return false;
}
private deserializeShape(shape: BPMNShape, findShapeElement: (bpmnElement: string) => ShapeBpmnElement): Shape | undefined {
const bpmnElement = findShapeElement(shape.bpmnElement);
if (bpmnElement) {
const bounds = DiagramConverter.deserializeBounds(shape);
if (bpmnElement.parentId) {
const participant = this.convertedElements.findParticipantByProcessRef(bpmnElement.parentId);
if (participant) {
bpmnElement.parentId = participant.id;
}
}
if (
(bpmnElement instanceof ShapeBpmnSubProcess ||
(bpmnElement instanceof ShapeBpmnCallActivity && bpmnElement.callActivityKind === ShapeBpmnCallActivityKind.CALLING_PROCESS)) &&
!shape.isExpanded
) {
bpmnElement.markers.push(ShapeBpmnMarkerKind.EXPAND);
}
let isHorizontal;
if (ShapeUtil.isPoolOrLane(bpmnElement.kind)) {
isHorizontal = shape.isHorizontal !== undefined ? shape.isHorizontal : true;
}
const label = this.deserializeLabel(shape.BPMNLabel, shape.id);
return new Shape(shape.id, bpmnElement, bounds, label, isHorizontal);
}
}
private static deserializeBounds(boundedElement: BPMNShape | BPMNLabel): Bounds {
const bounds = boundedElement.Bounds;
if (bounds) {
return new Bounds(bounds.x, bounds.y, bounds.width, bounds.height);
}
}
private deserializeEdges(edges: BPMNEdge | BPMNEdge[]): Edge[] {
return ensureIsArray(edges)
.map(edge => {
const flow =
this.convertedElements.findSequenceFlow(edge.bpmnElement) ||
this.convertedElements.findMessageFlow(edge.bpmnElement) ||
this.convertedElements.findAssociationFlow(edge.bpmnElement);
if (!flow) {
this.parsingMessageCollector.warning(new EdgeUnknownBpmnElementWarning(edge.bpmnElement));
return;
}
const waypoints = this.deserializeWaypoints(edge.waypoint);
const label = this.deserializeLabel(edge.BPMNLabel, edge.id);
const messageVisibleKind = edge.messageVisibleKind ? (edge.messageVisibleKind as unknown as MessageVisibleKind) : MessageVisibleKind.NONE;
return new Edge(edge.id, flow, waypoints, label, messageVisibleKind);
})
.filter(Boolean);
}
private deserializeWaypoints(waypoints: Point[]): Waypoint[] {
return ensureIsArray(waypoints).map(waypoint => new Waypoint(waypoint.x, waypoint.y));
}
private deserializeLabel(bpmnLabel: string | BPMNLabel, id: string): Label {
if (bpmnLabel && typeof bpmnLabel === 'object') {
const font = this.findFont(bpmnLabel.labelStyle, id);
const bounds = DiagramConverter.deserializeBounds(bpmnLabel);
if (font || bounds) {
return new Label(font, bounds);
}
}
}
private findFont(labelStyle: string, id: string): Font {
let font;
if (labelStyle) {
font = this.convertedFonts.get(labelStyle);
if (!font) {
this.parsingMessageCollector.warning(new LabelStyleMissingFontWarning(id, labelStyle));
}
}
return font;
}
}
|
bonitasoft-labs/bpmn-js
|
test/unit/component/mxgraph/renderer/style-utils.test.ts
|
/**
* Copyright 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { FlowKind, ShapeBpmnElementKind } from '../../../../../src/model/bpmn/internal';
import { computeBpmnBaseClassName, computeAllBpmnClassNames } from '../../../../../src/component/mxgraph/renderer/style-utils';
describe('compute base css class names of BPMN elements', () => {
it.each`
kind | expectedClassName
${undefined} | ${''}
${null} | ${''}
${''} | ${''}
${FlowKind.ASSOCIATION_FLOW} | ${'bpmn-association'}
${FlowKind.MESSAGE_FLOW} | ${'bpmn-message-flow'}
${FlowKind.SEQUENCE_FLOW} | ${'bpmn-sequence-flow'}
${ShapeBpmnElementKind.CALL_ACTIVITY} | ${'bpmn-call-activity'}
${ShapeBpmnElementKind.EVENT_INTERMEDIATE_CATCH} | ${'bpmn-intermediate-catch-event'}
${ShapeBpmnElementKind.EVENT_START} | ${'bpmn-start-event'}
${ShapeBpmnElementKind.GATEWAY_EVENT_BASED} | ${'bpmn-event-based-gateway'}
${ShapeBpmnElementKind.GATEWAY_PARALLEL} | ${'bpmn-parallel-gateway'}
${ShapeBpmnElementKind.SUB_PROCESS} | ${'bpmn-sub-process'}
${ShapeBpmnElementKind.TASK} | ${'bpmn-task'}
${ShapeBpmnElementKind.TASK_BUSINESS_RULE} | ${'bpmn-business-rule-task'}
${ShapeBpmnElementKind.TASK_SERVICE} | ${'bpmn-service-task'}
${ShapeBpmnElementKind.GROUP} | ${'bpmn-group'}
${ShapeBpmnElementKind.TEXT_ANNOTATION} | ${'bpmn-text-annotation'}
`('$kind Bpmn base classname', ({ kind, expectedClassName }) => {
expect(computeBpmnBaseClassName(kind)).toEqual(expectedClassName);
});
});
describe('compute all css class names based on style input', () => {
it.each`
style | isLabel | expectedClassNames
${ShapeBpmnElementKind.LANE} | ${true} | ${['bpmn-type-container', 'bpmn-lane', 'bpmn-label']}
${ShapeBpmnElementKind.POOL} | ${false} | ${['bpmn-type-container', 'bpmn-pool']}
${ShapeBpmnElementKind.CALL_ACTIVITY} | ${false} | ${['bpmn-type-activity', 'bpmn-call-activity']}
${'callActivity;bpmn.globalTaskKind=globalTask'} | ${false} | ${['bpmn-type-activity', 'bpmn-call-activity', 'bpmn-global-task']}
${'callActivity;bpmn.globalTaskKind=globalManualTask'} | ${true} | ${['bpmn-type-activity', 'bpmn-call-activity', 'bpmn-global-manual-task', 'bpmn-label']}
${ShapeBpmnElementKind.EVENT_BOUNDARY} | ${true} | ${['bpmn-type-event', 'bpmn-boundary-event', 'bpmn-label']}
${'boundaryEvent;bpmn.eventDefinitionKind=cancel;bpmn.isInterrupting=true'} | ${true} | ${['bpmn-type-event', 'bpmn-boundary-event', 'bpmn-event-def-cancel', 'bpmn-label']}
${ShapeBpmnElementKind.EVENT_INTERMEDIATE_THROW} | ${false} | ${['bpmn-type-event', 'bpmn-intermediate-throw-event']}
${'startEvent;bpmn.eventDefinitionKind=timer;bpmn.isInterrupting=false;fontStyle=2'} | ${false} | ${['bpmn-type-event', 'bpmn-start-event', 'bpmn-event-def-timer']}
${ShapeBpmnElementKind.GATEWAY_EVENT_BASED} | ${true} | ${['bpmn-type-gateway', 'bpmn-event-based-gateway', 'bpmn-label']}
${'eventBasedGateway;bpmn.isInstantiating=true;bpmn.gatewayKind=Parallel'} | ${false} | ${['bpmn-type-gateway', 'bpmn-event-based-gateway', 'bpmn-gateway-kind-parallel']}
${ShapeBpmnElementKind.GATEWAY_EXCLUSIVE} | ${true} | ${['bpmn-type-gateway', 'bpmn-exclusive-gateway', 'bpmn-label']}
${ShapeBpmnElementKind.TASK} | ${true} | ${['bpmn-type-activity', 'bpmn-type-task', 'bpmn-task', 'bpmn-label']}
${ShapeBpmnElementKind.TASK_BUSINESS_RULE} | ${false} | ${['bpmn-type-activity', 'bpmn-type-task', 'bpmn-business-rule-task']}
${ShapeBpmnElementKind.SUB_PROCESS} | ${false} | ${['bpmn-type-activity', 'bpmn-sub-process']}
${'subProcess;bpmn.subProcessKind=embedded'} | ${false} | ${['bpmn-type-activity', 'bpmn-sub-process', 'bpmn-sub-process-embedded']}
${'subProcess;bpmn.subProcessKind=event'} | ${true} | ${['bpmn-type-activity', 'bpmn-sub-process', 'bpmn-sub-process-event', 'bpmn-label']}
${FlowKind.ASSOCIATION_FLOW} | ${true} | ${['bpmn-type-flow', 'bpmn-association', 'bpmn-label']}
${FlowKind.MESSAGE_FLOW} | ${false} | ${['bpmn-type-flow', 'bpmn-message-flow']}
${'sequenceFlow;default;fontStyle=4'} | ${false} | ${['bpmn-type-flow', 'bpmn-sequence-flow']}
${'shape=bpmn.message-flow-icon'} | ${false} | ${['bpmn-message-flow-icon']}
${'shape=bpmn.message-flow-icon;bpmn.isInitiating=non_initiating'} | ${false} | ${['bpmn-message-flow-icon', 'bpmn-icon-non-initiating']}
${'shape=bpmn.message-flow-icon;bpmn.isInitiating=initiating'} | ${true} | ${['bpmn-message-flow-icon', 'bpmn-icon-initiating', 'bpmn-label']}
`('style="$style" / isLabel=$isLabel', ({ style, isLabel, expectedClassNames }: { style: string; isLabel: boolean; expectedClassNames: string[] }) => {
expect(computeAllBpmnClassNames(style, isLabel)).toEqual(expectedClassNames);
});
});
|
bonitasoft-labs/bpmn-js
|
test/e2e/bpmn.elements.collapsed.test.ts
|
<filename>test/e2e/bpmn.elements.collapsed.test.ts<gh_stars>1-10
/**
* Copyright 2022 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { MatchImageSnapshotOptions } from 'jest-image-snapshot';
import { ImageSnapshotConfigurator, MultiBrowserImageSnapshotThresholds } from './helpers/visu/image-snapshot-config';
import { AvailableTestPages, PageTester } from './helpers/visu/bpmn-page-utils';
import type { Page } from 'playwright';
import { getBpmnDiagramNames } from './helpers/test-utils';
// key: diagram name
// values: the ids of the elements to collapse. The elements are collapsed one by one, in dedicated tests
const elementsToCollapsePerDiagram = new Map<string, Array<string>>([
['pools', ['Participant_1', 'Participant_2', 'Participant_3', 'Participant_4']],
['subprocess', ['SubProcess_1']],
]);
class CollapsedElementImageSnapshotConfigurator extends ImageSnapshotConfigurator {
override getConfig(param: { fileName: string; collapsedElement: string }): MatchImageSnapshotOptions {
const config = super.getConfig(param);
config.customSnapshotIdentifier = `${param.fileName}-collapse-${param.collapsedElement}`;
return config;
}
}
const getElementsToCollapse = (bpmnDiagramName: string): Array<string> => {
const elementsToCollapse = elementsToCollapsePerDiagram.get(bpmnDiagramName);
// add 'none' to test the diagram rendering without collapsing any element. There is no element in diagrams with the 'none' id (in this case, the value is ignored and there is no collapsing).
return ['none', ...elementsToCollapse];
};
describe('Collapse BPMN elements', () => {
const diagramSubfolder = 'collapse-expand';
const imageSnapshotConfigurator = new CollapsedElementImageSnapshotConfigurator(
// chromium: max 0.00019290318850062604%
// firefox: max 0.10839637777485533%
// webkit: max 0.14363687914162873%
new MultiBrowserImageSnapshotThresholds({ chromium: 0.0002 / 100, firefox: 0.11 / 100, webkit: 0.15 / 100 }),
diagramSubfolder,
);
const pageTester = new PageTester({ targetedPage: AvailableTestPages.BPMN_RENDERING, diagramSubfolder }, <Page>page);
const bpmnDiagramNames = getBpmnDiagramNames(diagramSubfolder);
describe.each(bpmnDiagramNames)(`%s`, (bpmnDiagramName: string) => {
it.each(getElementsToCollapse(bpmnDiagramName))(`collapse %s`, async (bpmnElementIdToCollapse: string) => {
await pageTester.gotoPageAndLoadBpmnDiagram(bpmnDiagramName, {
bpmnElementIdToCollapse: bpmnElementIdToCollapse,
});
const image = await page.screenshot({ fullPage: true });
const config = imageSnapshotConfigurator.getConfig({ fileName: bpmnDiagramName, collapsedElement: bpmnElementIdToCollapse });
expect(image).toMatchImageSnapshot(config);
});
});
});
|
bonitasoft-labs/bpmn-js
|
test/unit/component/parser/parsing-messages.test.ts
|
<reponame>bonitasoft-labs/bpmn-js<gh_stars>10-100
/**
* Copyright 2021 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ParsingMessageCollector } from '../../../../src/component/parser/parsing-messages';
import { ShapeBpmnElementKind } from '../../../../src/model/bpmn/internal/shape';
import {
EdgeUnknownBpmnElementWarning,
GroupUnknownCategoryValueWarning,
LaneUnknownFlowNodeRefWarning,
LabelStyleMissingFontWarning,
ShapeUnknownBpmnElementWarning,
BoundaryEventNotAttachedToActivityWarning,
} from '../../../../src/component/parser/json/warnings';
describe('parsing message collector', () => {
jest.spyOn(console, 'warn').mockImplementation(() => {
// do not display actual console outputs during tests
});
afterEach(() => {
jest.clearAllMocks();
});
const parsingMessageCollector = new ParsingMessageCollector();
describe('console.warn when warning is registered', () => {
it('unknown edge bpmn element', () => {
parsingMessageCollector.warning(new EdgeUnknownBpmnElementWarning('edge-bpmnElement-unknown'));
expect(console.warn).toHaveBeenCalledWith('Edge json deserialization: unable to find bpmn element with id %s', 'edge-bpmnElement-unknown');
});
it('unknown shape bpmn element', () => {
parsingMessageCollector.warning(new ShapeUnknownBpmnElementWarning('shape-bpmnElement-unknown'));
expect(console.warn).toHaveBeenCalledWith('Shape json deserialization: unable to find bpmn element with id %s', 'shape-bpmnElement-unknown');
});
it('missing font in label style', () => {
parsingMessageCollector.warning(new LabelStyleMissingFontWarning('BPMNEdge_id_0', 'non-existing_style_id'));
expect(console.warn).toHaveBeenCalledWith('Unable to assign font from style %s to shape/edge %s', 'non-existing_style_id', 'BPMNEdge_id_0');
});
it('unknown flow node ref in lane', () => {
parsingMessageCollector.warning(new LaneUnknownFlowNodeRefWarning('lane_id', 'non-existing_flow_node_ref'));
expect(console.warn).toHaveBeenCalledWith('Unable to assign lane %s as parent: flow node %s is not found', 'non-existing_flow_node_ref', 'lane_id');
});
it('unknown category value ref in group', () => {
parsingMessageCollector.warning(new GroupUnknownCategoryValueWarning('Group_0', 'non-existing_category_value_ref'));
expect(console.warn).toHaveBeenCalledWith(
'Group json deserialization: unable to find category value ref %s for bpmn element %s',
'non-existing_category_value_ref',
'Group_0',
);
});
it('boundary event not attached to activity', () => {
parsingMessageCollector.warning(new BoundaryEventNotAttachedToActivityWarning('boundary_event_0', 'lane_id_ref', ShapeBpmnElementKind.LANE));
expect(console.warn).toHaveBeenCalledWith('The boundary event %s must be attached to an activity, and not to %s of kind %s', 'boundary_event_0', 'lane_id_ref', 'lane');
});
});
});
|
bonitasoft-labs/bpmn-js
|
src/model/bpmn/internal/shape/kinds.ts
|
<gh_stars>10-100
/**
* Copyright 2021 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* The real name of the field in the BPMN XSD.
* @category BPMN
*/
export enum ShapeBpmnElementKind {
LANE = 'lane',
POOL = 'pool',
CALL_ACTIVITY = 'callActivity',
SUB_PROCESS = 'subProcess',
// When adding support, uncomment related content in tests
// test/unit/component/mxgraph/renderer/StyleComputer.test.ts
// test/unit/component/parser/json/BpmnJsonParser.marker.test.ts (adhoc requires special checks as an additional marker should be present)
// Generalize test/unit/component/parser/json/BpmnJsonParser.sub.process.test.ts
// See also, ShapeBpmnSubProcessKind
// SUB_PROCESS_AD_HOC = 'adHocSubProcess',
// SUB_PROCESS_TRANSACTION = 'transaction',
TASK = 'task',
TASK_USER = 'userTask',
TASK_SERVICE = 'serviceTask',
TASK_RECEIVE = 'receiveTask',
TASK_SEND = 'sendTask',
TASK_MANUAL = 'manualTask',
TASK_SCRIPT = 'scriptTask',
TASK_BUSINESS_RULE = 'businessRuleTask',
GLOBAL_TASK = 'globalTask',
GLOBAL_TASK_USER = 'globalUserTask',
GLOBAL_TASK_MANUAL = 'globalManualTask',
GLOBAL_TASK_SCRIPT = 'globalScriptTask',
GLOBAL_TASK_BUSINESS_RULE = 'globalBusinessRuleTask',
GROUP = 'group',
TEXT_ANNOTATION = 'textAnnotation',
GATEWAY_PARALLEL = 'parallelGateway',
GATEWAY_EXCLUSIVE = 'exclusiveGateway',
GATEWAY_INCLUSIVE = 'inclusiveGateway',
GATEWAY_EVENT_BASED = 'eventBasedGateway',
// When adding support for GATEWAY_COMPLEX, uncomment corresponding test in the following files
// test/unit/component/parser/json/BpmnJsonParser.sequenceFlow.default.test.ts
// test/unit/component/parser/json/BpmnJsonParser.sequenceFlow.conditional.test.ts
// test/unit/component/parser/json/BpmnJsonParser.flowNode.test.ts
// test/unit/component/parser/json/BpmnJsonParser.label.bounds.test.ts
// test/unit/component/parser/json/BpmnJsonParser.label.font.test.ts
// test/unit/component/parser/json/BpmnJsonParser.label.test.ts
// Uncomment corresponding line in src/model/bpmn/shape/utils.ts FLOW_NODE_WITH_DEFAULT_SEQUENCE_FLOW_KINDS
// GATEWAY_COMPLEX = 'complexGateway',
EVENT_START = 'startEvent',
EVENT_END = 'endEvent',
EVENT_INTERMEDIATE_CATCH = 'intermediateCatchEvent',
EVENT_INTERMEDIATE_THROW = 'intermediateThrowEvent',
EVENT_BOUNDARY = 'boundaryEvent',
}
/**
* {@link ShapeBpmnElementKind} related to BPMN Events.
* @category BPMN
*/
export type BpmnEventKind =
| ShapeBpmnElementKind.EVENT_BOUNDARY
| ShapeBpmnElementKind.EVENT_START
| ShapeBpmnElementKind.EVENT_END
| ShapeBpmnElementKind.EVENT_INTERMEDIATE_THROW
| ShapeBpmnElementKind.EVENT_INTERMEDIATE_CATCH;
/**
* {@link ShapeBpmnElementKind} related to BPMN Global Tasks.
* @category BPMN
*/
export type GlobalTaskKind =
| ShapeBpmnElementKind.GLOBAL_TASK
| ShapeBpmnElementKind.GLOBAL_TASK_MANUAL
| ShapeBpmnElementKind.GLOBAL_TASK_SCRIPT
| ShapeBpmnElementKind.GLOBAL_TASK_USER
| ShapeBpmnElementKind.GLOBAL_TASK_BUSINESS_RULE;
/**
* @category BPMN
*/
export enum ShapeBpmnCallActivityKind {
CALLING_PROCESS = 'process',
CALLING_GLOBAL_TASK = 'global task',
}
/**
* Values available for the `eventGatewayType` property in the BPMN specification.
* @category BPMN
*/
export enum ShapeBpmnEventBasedGatewayKind {
Exclusive = 'Exclusive',
/** When no type is provided in the BPMN source. */
None = 'None',
Parallel = 'Parallel',
}
/**
* Base name of the EventDefinition fields in the BPMN XSD for event kinds. In the xsd, the value is <enum_value>EventDefinition.
*
* For instance, TERMINATE --> terminateEventDefinition
* @category BPMN
*/
export enum ShapeBpmnEventDefinitionKind {
NONE = 'none',
TERMINATE = 'terminate',
CANCEL = 'cancel',
COMPENSATION = 'compensate',
CONDITIONAL = 'conditional',
ERROR = 'error',
ESCALATION = 'escalation',
LINK = 'link',
MESSAGE = 'message',
SIGNAL = 'signal',
TIMER = 'timer',
}
/**
* @category BPMN
*/
export enum ShapeBpmnMarkerKind {
ADHOC = 'adhoc',
COMPENSATION = 'compensation',
EXPAND = 'expand',
LOOP = 'loop',
MULTI_INSTANCE_PARALLEL = 'parallel multi instance',
MULTI_INSTANCE_SEQUENTIAL = 'sequential multi instance',
}
/**
* Base name of the BPMN specification for sub-process kinds.
* @category BPMN
*/
export enum ShapeBpmnSubProcessKind {
EMBEDDED = 'embedded',
EVENT = 'event',
// The following may be only needed for rendering, as we have special types for adHoc and transaction subprocess in ShapeBpmnElementKind
// TRANSACTION = 'transaction',
// AD_HOC = 'ad_hoc',
}
|
bonitasoft-labs/bpmn-js
|
test/unit/helpers/bpmn-semantic-utils.ts
|
<filename>test/unit/helpers/bpmn-semantic-utils.ts
/**
* Copyright 2021 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { BpmnSemantic } from '../../../src/component/registry';
import { FlowKind, ShapeBpmnElementKind } from '../../../src/model/bpmn/internal';
export interface ExpectedBaseBpmnElement {
id: string;
name?: string;
}
export function expectSequenceFlow(bpmnSemantic: BpmnSemantic, expected: ExpectedBaseBpmnElement): void {
expect(bpmnSemantic.id).toEqual(expected.id);
expect(bpmnSemantic.name).toEqual(expected.name);
expect(bpmnSemantic.isShape).toBeFalsy();
expect(bpmnSemantic.kind).toEqual(FlowKind.SEQUENCE_FLOW);
}
function expectShape(bpmnSemantic: BpmnSemantic, expected: ExpectedBaseBpmnElement): void {
expect(bpmnSemantic.id).toEqual(expected.id);
expect(bpmnSemantic.name).toEqual(expected.name);
expect(bpmnSemantic.isShape).toBeTruthy();
}
export function expectStartEvent(bpmnSemantic: BpmnSemantic, expected: ExpectedBaseBpmnElement): void {
expectShape(bpmnSemantic, expected);
expect(bpmnSemantic.kind).toEqual(ShapeBpmnElementKind.EVENT_START);
}
export function expectEndEvent(bpmnSemantic: BpmnSemantic, expected: ExpectedBaseBpmnElement): void {
expectShape(bpmnSemantic, expected);
expect(bpmnSemantic.kind).toEqual(ShapeBpmnElementKind.EVENT_END);
}
export function expectLane(bpmnSemantic: BpmnSemantic, expected: ExpectedBaseBpmnElement): void {
expectShape(bpmnSemantic, expected);
expect(bpmnSemantic.kind).toEqual(ShapeBpmnElementKind.LANE);
}
export function expectPool(bpmnSemantic: BpmnSemantic, expected: ExpectedBaseBpmnElement): void {
expectShape(bpmnSemantic, expected);
expect(bpmnSemantic.kind).toEqual(ShapeBpmnElementKind.POOL);
}
export function expectTask(bpmnSemantic: BpmnSemantic, expected: ExpectedBaseBpmnElement): void {
expectShape(bpmnSemantic, expected);
expect(bpmnSemantic.kind).toEqual(ShapeBpmnElementKind.TASK);
}
export function expectServiceTask(bpmnSemantic: BpmnSemantic, expected: ExpectedBaseBpmnElement): void {
expectShape(bpmnSemantic, expected);
expect(bpmnSemantic.kind).toEqual(ShapeBpmnElementKind.TASK_SERVICE);
}
|
bonitasoft-labs/bpmn-js
|
test/integration/helpers/semantic-with-svg-utils.ts
|
<reponame>bonitasoft-labs/bpmn-js<filename>test/integration/helpers/semantic-with-svg-utils.ts
/**
* Copyright 2021 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { BpmnElement } from '../../../src/component/registry';
import type { ExpectedBaseBpmnElement } from '../../unit/helpers/bpmn-semantic-utils';
import { expectEndEvent, expectPool, expectSequenceFlow, expectServiceTask, expectStartEvent, expectTask } from '../../unit/helpers/bpmn-semantic-utils';
import { expectSvgEvent, expectSvgPool, expectSvgSequenceFlow, expectSvgTask } from './html-utils';
export function expectStartEventBpmnElement(bpmnElement: BpmnElement, expected: ExpectedBaseBpmnElement): void {
expectStartEvent(bpmnElement.bpmnSemantic, expected);
expectSvgEvent(bpmnElement.htmlElement);
}
export function expectEndEventBpmnElement(bpmnElement: BpmnElement, expected: ExpectedBaseBpmnElement): void {
expectEndEvent(bpmnElement.bpmnSemantic, expected);
expectSvgEvent(bpmnElement.htmlElement);
}
export function expectSequenceFlowBpmnElement(bpmnElement: BpmnElement, expected: ExpectedBaseBpmnElement): void {
expectSequenceFlow(bpmnElement.bpmnSemantic, expected);
expectSvgSequenceFlow(bpmnElement.htmlElement);
}
export function expectTaskBpmnElement(bpmnElement: BpmnElement, expected: ExpectedBaseBpmnElement): void {
expectTask(bpmnElement.bpmnSemantic, expected);
expectSvgTask(bpmnElement.htmlElement);
}
export function expectServiceTaskBpmnElement(bpmnElement: BpmnElement, expected: ExpectedBaseBpmnElement): void {
expectServiceTask(bpmnElement.bpmnSemantic, expected);
expectSvgTask(bpmnElement.htmlElement);
}
export function expectPoolBpmnElement(bpmnElement: BpmnElement, expected: ExpectedBaseBpmnElement): void {
expectPool(bpmnElement.bpmnSemantic, expected);
expectSvgPool(bpmnElement.htmlElement);
}
|
bonitasoft-labs/bpmn-js
|
src/model/bpmn/internal/edge/edge.ts
|
/**
* Copyright 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type Label from '../Label';
import type { Flow } from './flows';
import { MessageVisibleKind } from './kinds';
/**
* @internal
*/
export class Edge {
constructor(
readonly id: string,
readonly bpmnElement: Flow,
readonly waypoints?: Waypoint[],
readonly label?: Label,
readonly messageVisibleKind: MessageVisibleKind = MessageVisibleKind.NONE,
) {}
}
/**
* @internal
*/
export class Waypoint {
constructor(readonly x: number, readonly y: number) {}
}
|
bonitasoft-labs/bpmn-js
|
test/unit/component/helpers/validators.test.ts
|
/**
* Copyright 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ensureInRange, ensurePositiveValue, ensureValidZoomConfiguration } from '../../../../src/component/helpers/validators';
describe('helper functions', () => {
it.each`
input | min | max | expected
${undefined} | ${-12} | ${45} | ${20}
${30} | ${-12} | ${45} | ${30}
${-30} | ${0} | ${45} | ${0}
${130} | ${0} | ${72} | ${72}
${0} | ${-100} | ${100} | ${0}
`('Range number restriction: input ($input) min ($min) max ($max)', ({ input, min, max, expected }) => {
expect(ensureInRange(input, min, max, 20)).toEqual(expected);
});
it.each`
input | expected
${undefined} | ${0}
${null} | ${0}
${-30} | ${0}
${130} | ${130}
${0} | ${0}
`('Ensure positive values: input ($input)', ({ input, expected }) => {
expect(ensurePositiveValue(input)).toEqual(expected);
});
});
describe('validate configuration', () => {
it.each`
input | expected
${undefined} | ${{ debounceDelay: 50, throttleDelay: 50 }}
${{ throttleDelay: 12 }} | ${{ debounceDelay: 50, throttleDelay: 12 }}
${{ debounceDelay: 72 }} | ${{ debounceDelay: 72, throttleDelay: 50 }}
${{ debounceDelay: 172, throttleDelay: -50 }} | ${{ debounceDelay: 100, throttleDelay: 0 }}
`('zoom configuration: input ($input)', ({ input, expected }) => {
expect(ensureValidZoomConfiguration(input)).toEqual(expected);
});
});
|
bonitasoft-labs/bpmn-js
|
src/model/bpmn/json/baseElement/flowNode/choreographyActivity.ts
|
<reponame>bonitasoft-labs/bpmn-js
/**
* Copyright 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { TCorrelationKey } from '../correlation';
import type { TParticipantAssociation } from '../participant';
import type { TArtifact, TAssociation, TGroup, TTextAnnotation } from '../artifact';
import type { TFlowElement, TFlowNode, TSequenceFlow } from '../flowElement';
import type { TAdHocSubProcess, TCallActivity, TSubProcess, TTransaction } from './activity/activity';
import type { TDataObject, TDataObjectReference, TDataStoreReference } from '../data';
import type { TBoundaryEvent, TEndEvent, TEvent, TImplicitThrowEvent, TIntermediateCatchEvent, TIntermediateThrowEvent, TStartEvent } from './event';
import type { TComplexGateway, TEventBasedGateway, TExclusiveGateway, TInclusiveGateway, TParallelGateway } from './gateway';
import type { TBusinessRuleTask, TManualTask, TReceiveTask, TScriptTask, TSendTask, TServiceTask, TTask, TUserTask } from './activity/task';
// abstract="true"
export interface TChoreographyActivity extends TFlowNode {
correlationKey?: TCorrelationKey | TCorrelationKey[];
participantRef: string | string[];
initiatingParticipantRef: string;
loopType?: tChoreographyLoopType; // default="None"
}
export interface TCallChoreography extends TChoreographyActivity {
participantAssociation?: TParticipantAssociation | TParticipantAssociation[];
calledChoreographyRef?: string;
}
export interface TChoreographyTask extends TChoreographyActivity {
messageFlowRef: string | string[];
}
export interface TSubChoreography extends TChoreographyActivity {
// flowElement
flowElement?: TFlowElement | TFlowElement[];
sequenceFlow?: TSequenceFlow | TSequenceFlow[];
callChoreography?: TCallChoreography | TCallChoreography[];
choreographyTask?: TChoreographyTask | TChoreographyTask[];
subChoreography?: TSubChoreography | TSubChoreography[];
callActivity?: TCallActivity | TCallActivity[];
// dataObject
dataObject?: TDataObject | TDataObject[];
dataObjectReference?: TDataObjectReference | TDataObjectReference[];
dataStoreReference?: TDataStoreReference | TDataStoreReference[];
// event
event?: TEvent | TEvent[];
intermediateCatchEvent?: TIntermediateCatchEvent | TIntermediateCatchEvent[];
boundaryEvent?: TBoundaryEvent | TBoundaryEvent[];
startEvent?: TStartEvent | TStartEvent[];
implicitThrowEvent?: TImplicitThrowEvent | TImplicitThrowEvent[];
intermediateThrowEvent?: TIntermediateThrowEvent | TIntermediateThrowEvent[];
endEvent?: TEndEvent | TEndEvent[];
// sub process
subProcess?: TSubProcess | TSubProcess[];
adHocSubProcess?: TAdHocSubProcess | TAdHocSubProcess[];
transaction?: TTransaction | TTransaction[];
// gateway
complexGateway?: TComplexGateway | TComplexGateway[];
eventBasedGateway?: TEventBasedGateway | TEventBasedGateway[];
exclusiveGateway?: TExclusiveGateway | TExclusiveGateway[];
inclusiveGateway?: TInclusiveGateway | TInclusiveGateway[];
parallelGateway?: TParallelGateway | TParallelGateway[];
// task
task?: TTask | TTask[];
businessRuleTask?: TBusinessRuleTask | TBusinessRuleTask[];
manualTask?: TManualTask | TManualTask[];
receiveTask?: TReceiveTask | TReceiveTask[];
sendTask?: TSendTask | TSendTask[];
serviceTask?: TServiceTask | TServiceTask[];
scriptTask?: TScriptTask | TScriptTask[];
userTask?: TUserTask | TUserTask[];
// artifact
artifact?: TArtifact | TArtifact[];
association?: TAssociation | TAssociation[];
group?: TGroup | TGroup[];
textAnnotation?: TTextAnnotation | TTextAnnotation[];
}
enum tChoreographyLoopType {
None = 'None',
Standard = 'Standard',
MultiInstanceSequential = 'MultiInstanceSequential',
MultiInstanceParallel = 'MultiInstanceParallel',
}
|
bonitasoft-labs/bpmn-js
|
test/unit/component/helpers/array-utils.test.ts
|
/**
* Copyright 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { filter } from '../../../../src/component/helpers/array-utils';
import { ShapeBpmnElementKind } from '../../../../src/model/bpmn/internal';
describe('array helper functions', () => {
describe('filter an array of string', () => {
it('filter an array of string with a case insensitive regex', () => {
expect(filter(['lane', 'pool', 'callActivity', 'subProcess', 'task', 'userTask', 'serviceTask'], 'Task', { ignoreCase: true })).toEqual(['task', 'userTask', 'serviceTask']);
});
it('filter an array of string with a case sensitive regex', () => {
expect(filter(['lane', 'pool', 'callActivity', 'subProcess', 'task', 'userTask', 'serviceTask'], 'Task', { ignoreCase: false })).toEqual(['userTask', 'serviceTask']);
});
it('filter an array of string with no case sensitive parameter', () => {
expect(filter(['lane', 'pool', 'callActivity', 'subProcess', 'task', 'userTask', 'serviceTask'], 'Task')).toEqual(['userTask', 'serviceTask']);
});
it('filter an array of string starting with', () => {
expect(filter(['subProcess', 'task', 'userTask', 'globalTask', 'globalUserTask', 'globalManualTask'], 'Task', { startingWith: 'global' })).toEqual([
'globalTask',
'globalUserTask',
'globalManualTask',
]);
});
it('filter an array of string not starting with', () => {
expect(filter(['subProcess', 'task', 'userTask', 'globalTask', 'globalUserTask', 'globalManualTask'], 'Task', { notStartingWith: 'global' })).toEqual(['userTask']);
});
});
describe('filter an array of string enum', () => {
it('filter an array of string enum with a case insensitive regex', () => {
expect(filter(Object.values(ShapeBpmnElementKind), 'Task', { ignoreCase: true })).toEqual([
'task',
'userTask',
'serviceTask',
'receiveTask',
'sendTask',
'manualTask',
'scriptTask',
'businessRuleTask',
'globalTask',
'globalUserTask',
'globalManualTask',
'globalScriptTask',
'globalBusinessRuleTask',
]);
});
it('filter an array of string enum with a case sensitive regex', () => {
expect(filter(Object.values(ShapeBpmnElementKind), 'Task', { ignoreCase: false })).toEqual([
'userTask',
'serviceTask',
'receiveTask',
'sendTask',
'manualTask',
'scriptTask',
'businessRuleTask',
'globalTask',
'globalUserTask',
'globalManualTask',
'globalScriptTask',
'globalBusinessRuleTask',
]);
});
it('filter an array of string enum with no case sensitive parameter', () => {
expect(filter(Object.values(ShapeBpmnElementKind), 'Task')).toEqual([
'userTask',
'serviceTask',
'receiveTask',
'sendTask',
'manualTask',
'scriptTask',
'businessRuleTask',
'globalTask',
'globalUserTask',
'globalManualTask',
'globalScriptTask',
'globalBusinessRuleTask',
]);
});
it('filter an array of string starting with', () => {
expect(filter(Object.values(ShapeBpmnElementKind), 'Task', { startingWith: 'global' })).toEqual([
'globalTask',
'globalUserTask',
'globalManualTask',
'globalScriptTask',
'globalBusinessRuleTask',
]);
});
it('filter an array of string not starting with', () => {
expect(filter(Object.values(ShapeBpmnElementKind), 'Task', { notStartingWith: 'global' })).toEqual([
'userTask',
'serviceTask',
'receiveTask',
'sendTask',
'manualTask',
'scriptTask',
'businessRuleTask',
]);
});
});
});
|
bonitasoft-labs/bpmn-js
|
test/unit/component/parser/json/JsonBuilder.test.ts
|
<filename>test/unit/component/parser/json/JsonBuilder.test.ts
/**
* Copyright 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { BuildEventDefinitionParameter } from './JsonBuilder';
import { addEvent, buildDefinitionsAndProcessWithTask, EventDefinitionOn } from './JsonBuilder';
describe('build json', () => {
it(
'build json with definitions, process, task, interrupting boundary event with attachedToRef & empty messageEventDefinition, ' +
"when bpmnKind='boundaryEvent', eventDefinitionKind='message', eventDefinitionOn=EVENT, isInterrupting=true, attachedToRef is defined",
() => {
const buildEventDefinitionParameter: BuildEventDefinitionParameter = { eventDefinitionKind: 'message', eventDefinitionOn: EventDefinitionOn.EVENT };
const json = buildDefinitionsAndProcessWithTask();
addEvent(json, 'boundaryEvent', buildEventDefinitionParameter, {
isInterrupting: true,
attachedToRef: 'task_id_0',
});
expect(json).toEqual({
definitions: {
targetNamespace: '',
process: {
task: {
id: 'task_id_0',
name: 'task name',
},
boundaryEvent: {
id: 'event_id_0',
cancelActivity: true,
attachedToRef: 'task_id_0',
messageEventDefinition: '',
name: undefined,
},
},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: [
{
id: 'shape_task_id_0',
bpmnElement: 'task_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
{
id: 'shape_event_id_0',
bpmnElement: 'event_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
],
},
},
},
});
},
);
it(
'build json with definitions, process, task, boundary event with attachedToRef & empty messageEventDefinition & name, without cancelActivity, ' +
"when bpmnKind='boundaryEvent', eventDefinitionKind='message', eventDefinitionOn=EVENT, isInterrupting is not defined, attachedToRef & name are defined",
() => {
const buildEventDefinitionParameter: BuildEventDefinitionParameter = { eventDefinitionKind: 'message', eventDefinitionOn: EventDefinitionOn.EVENT };
const json = buildDefinitionsAndProcessWithTask();
addEvent(json, 'boundaryEvent', buildEventDefinitionParameter, {
attachedToRef: 'task_id_0',
name: 'name',
});
expect(json).toEqual({
definitions: {
targetNamespace: '',
process: {
task: {
id: 'task_id_0',
name: 'task name',
},
boundaryEvent: {
id: 'event_id_0',
attachedToRef: 'task_id_0',
messageEventDefinition: '',
name: 'name',
},
},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: [
{
id: 'shape_task_id_0',
bpmnElement: 'task_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
{
id: 'shape_event_id_0',
bpmnElement: 'event_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
],
},
},
},
});
},
);
it(
'build json with definitions with messageEventDefinition with id, process, task, interrupting boundary event with eventDefinitionRef, ' +
"when bpmnKind='boundaryEvent', eventDefinitionKind='message', eventDefinitionOn=DEFINITIONS, isInterrupting=true, attachedToRef is not defined",
() => {
const buildEventDefinitionParameter: BuildEventDefinitionParameter = { eventDefinitionKind: 'message', eventDefinitionOn: EventDefinitionOn.DEFINITIONS };
const json = buildDefinitionsAndProcessWithTask();
addEvent(json, 'boundaryEvent', buildEventDefinitionParameter, {
isInterrupting: true,
});
expect(json).toEqual({
definitions: {
targetNamespace: '',
messageEventDefinition: {
id: 'event_definition_id',
},
process: {
task: {
id: 'task_id_0',
name: 'task name',
},
boundaryEvent: {
id: 'event_id_0',
cancelActivity: true,
eventDefinitionRef: 'event_definition_id',
attachedToRef: undefined,
name: undefined,
},
},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: [
{
id: 'shape_task_id_0',
bpmnElement: 'task_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
{
id: 'shape_event_id_0',
bpmnElement: 'event_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
],
},
},
},
});
},
);
it(
'build json with definitions, process, task, non-interrupting boundary event with empty signalEventDefinition, ' +
"when bpmnKind='boundaryEvent', eventDefinitionKind='signal', eventDefinitionOn=EVENT, isInterrupting=false, attachedToRef is NOT defined",
() => {
const buildEventDefinitionParameter: BuildEventDefinitionParameter = { eventDefinitionKind: 'signal', eventDefinitionOn: EventDefinitionOn.EVENT };
const json = buildDefinitionsAndProcessWithTask();
addEvent(json, 'boundaryEvent', buildEventDefinitionParameter, {
isInterrupting: false,
});
expect(json).toEqual({
definitions: {
targetNamespace: '',
process: {
task: {
id: 'task_id_0',
name: '<NAME>',
},
boundaryEvent: {
id: 'event_id_0',
cancelActivity: false,
attachedToRef: undefined,
signalEventDefinition: '',
name: undefined,
},
},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: [
{
id: 'shape_task_id_0',
bpmnElement: 'task_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
{
id: 'shape_event_id_0',
bpmnElement: 'event_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
],
},
},
},
});
},
);
it(
'build json with definitions, process, task, non-interrupting boundary event with empty signalEventDefinition and increased id, ' +
"when bpmnKind='boundaryEvent', eventDefinitionKind='signal', eventDefinitionOn=EVENT, isInterrupting=false, attachedToRef is not defined, index=1",
() => {
const buildEventDefinitionParameter: BuildEventDefinitionParameter = { eventDefinitionKind: 'signal', eventDefinitionOn: EventDefinitionOn.EVENT };
const json = buildDefinitionsAndProcessWithTask();
addEvent(json, 'boundaryEvent', buildEventDefinitionParameter, {
isInterrupting: false,
index: 1,
});
expect(json).toEqual({
definitions: {
targetNamespace: '',
process: {
task: {
id: 'task_id_0',
name: 'task name',
},
boundaryEvent: {
id: 'event_id_1',
cancelActivity: false,
attachedToRef: undefined,
signalEventDefinition: '',
name: undefined,
},
},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: [
{
id: 'shape_task_id_0',
bpmnElement: 'task_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
{
id: 'shape_event_id_1',
bpmnElement: 'event_id_1',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
],
},
},
},
});
},
);
it(
'build json with definitions with signalEventDefinition with id, process, task, non-interrupting boundary event with attachedToRef & eventDefinitionRef, ' +
"when bpmnKind='boundaryEvent', eventDefinitionKind='signal', eventDefinitionOn=DEFINITIONS, isInterrupting=false, attachedToRef is defined",
() => {
const buildEventDefinitionParameter: BuildEventDefinitionParameter = { eventDefinitionKind: 'signal', eventDefinitionOn: EventDefinitionOn.DEFINITIONS };
const json = buildDefinitionsAndProcessWithTask();
addEvent(json, 'boundaryEvent', buildEventDefinitionParameter, {
isInterrupting: false,
attachedToRef: 'task_id_0',
});
expect(json).toEqual({
definitions: {
targetNamespace: '',
signalEventDefinition: {
id: 'event_definition_id',
},
process: {
task: {
id: 'task_id_0',
name: 'task name',
},
boundaryEvent: {
id: 'event_id_0',
cancelActivity: false,
eventDefinitionRef: 'event_definition_id',
attachedToRef: 'task_id_0',
name: undefined,
},
},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: [
{
id: 'shape_task_id_0',
bpmnElement: 'task_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
{
id: 'shape_event_id_0',
bpmnElement: 'event_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
],
},
},
},
});
},
);
it(
'build json with definitions, process, task, start event with messageEventDefinition & name, ' +
"when bpmnKind='startEvent', eventDefinitionKind='message', eventDefinitionOn=EVENT, name is defined, attachedToRef & isInterrupting is not defined",
() => {
const buildEventDefinitionParameter: BuildEventDefinitionParameter = { eventDefinitionKind: 'message', eventDefinitionOn: EventDefinitionOn.EVENT };
const json = buildDefinitionsAndProcessWithTask();
addEvent(json, 'startEvent', buildEventDefinitionParameter, {
name: 'name',
});
expect(json).toEqual({
definitions: {
targetNamespace: '',
process: {
task: {
id: 'task_id_0',
name: 'task name',
},
startEvent: {
id: 'event_id_0',
messageEventDefinition: '',
name: 'name',
},
},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: [
{
id: 'shape_task_id_0',
bpmnElement: 'task_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
{
id: 'shape_event_id_0',
bpmnElement: 'event_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
],
},
},
},
});
},
);
it(
'build json with definitions with messageEventDefinition with id, process, task, start event with name, ' +
"when bpmnKind='endEvent', eventDefinitionKind='message', eventDefinitionOn=DEFINITIONS, name is defined, attachedToRef & isInterrupting is not defined",
() => {
const buildEventDefinitionParameter: BuildEventDefinitionParameter = { eventDefinitionKind: 'message', eventDefinitionOn: EventDefinitionOn.DEFINITIONS };
const json = buildDefinitionsAndProcessWithTask();
addEvent(json, 'endEvent', buildEventDefinitionParameter, {
name: 'name',
});
expect(json).toEqual({
definitions: {
targetNamespace: '',
messageEventDefinition: {
id: 'event_definition_id',
},
process: {
task: {
id: 'task_id_0',
name: '<NAME>',
},
endEvent: {
id: 'event_id_0',
eventDefinitionRef: 'event_definition_id',
name: 'name',
},
},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: [
{
id: 'shape_task_id_0',
bpmnElement: 'task_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
{
id: 'shape_event_id_0',
bpmnElement: 'event_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
],
},
},
},
});
},
);
it(
'build json with definitions with messageEventDefinition with id, process, task, intermediate catch event with messageEventDefinition & eventDefinitionRef & name, ' +
"when bpmnKind='intermediateCatchEvent', eventDefinitionKind='message', eventDefinitionOn=BOTH, name is defined, attachedToRef & isInterrupting is not defined",
() => {
const buildEventDefinitionParameter: BuildEventDefinitionParameter = { eventDefinitionKind: 'message', eventDefinitionOn: EventDefinitionOn.BOTH };
const json = buildDefinitionsAndProcessWithTask();
addEvent(json, 'intermediateCatchEvent', buildEventDefinitionParameter, {
name: 'name',
});
expect(json).toEqual({
definitions: {
targetNamespace: '',
messageEventDefinition: {
id: 'event_definition_id',
},
process: {
task: {
id: 'task_id_0',
name: '<NAME>',
},
intermediateCatchEvent: {
id: 'event_id_0',
messageEventDefinition: '',
eventDefinitionRef: 'event_definition_id',
name: 'name',
},
},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: [
{
id: 'shape_task_id_0',
bpmnElement: 'task_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
{
id: 'shape_event_id_0',
bpmnElement: 'event_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
],
},
},
},
});
},
);
it(
'build json with definitions, process, task, start event with messageEventDefinitions (empty string & empty object) & name, ' +
"when bpmnKind='startEvent', eventDefinitionKind='message', eventDefinitionOn=EVENT, withMultipleDefinitions=true, name is defined, attachedToRef & isInterrupting is not defined",
() => {
const buildEventDefinitionParameter: BuildEventDefinitionParameter = {
eventDefinitionKind: 'message',
eventDefinitionOn: EventDefinitionOn.EVENT,
withMultipleDefinitions: true,
};
const json = buildDefinitionsAndProcessWithTask();
addEvent(json, 'startEvent', buildEventDefinitionParameter, {
name: 'name',
});
expect(json).toEqual({
definitions: {
targetNamespace: '',
process: {
task: {
id: 'task_id_0',
name: 'task name',
},
startEvent: {
id: 'event_id_0',
messageEventDefinition: ['', {}],
name: 'name',
},
},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: [
{
id: 'shape_task_id_0',
bpmnElement: 'task_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
{
id: 'shape_event_id_0',
bpmnElement: 'event_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
],
},
},
},
});
},
);
it(
'build json with definitions with messageEventDefinitions with id, process, task, start event with name, ' +
"when bpmnKind='endEvent', eventDefinitionKind='message', eventDefinitionOn=DEFINITIONS, withMultipleDefinitions=true, name is defined, attachedToRef & isInterrupting is not defined",
() => {
const buildEventDefinitionParameter: BuildEventDefinitionParameter = {
eventDefinitionKind: 'message',
eventDefinitionOn: EventDefinitionOn.DEFINITIONS,
withMultipleDefinitions: true,
};
const json = buildDefinitionsAndProcessWithTask();
addEvent(json, 'endEvent', buildEventDefinitionParameter, {
name: 'name',
});
expect(json).toEqual({
definitions: {
targetNamespace: '',
messageEventDefinition: [
{
id: 'event_definition_1_id',
},
{
id: 'event_definition_2_id',
},
],
process: {
task: {
id: 'task_id_0',
name: 'task name',
},
endEvent: {
id: 'event_id_0',
eventDefinitionRef: ['event_definition_1_id', 'event_definition_2_id'],
name: 'name',
},
},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: [
{
id: 'shape_task_id_0',
bpmnElement: 'task_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
{
id: 'shape_event_id_0',
bpmnElement: 'event_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
],
},
},
},
});
},
);
it(
'build json with definitions with messageEventDefinitions with id, process, task, intermediate catch event with messageEventDefinitions (empty string & empty object) & eventDefinitionRef & name, ' +
"when bpmnKind='intermediateCatchEvent', eventDefinitionKind='message', eventDefinitionOn=BOTH, withMultipleDefinitions=true, name is defined, attachedToRef & isInterrupting is not defined",
() => {
const buildEventDefinitionParameter: BuildEventDefinitionParameter = {
eventDefinitionKind: 'message',
eventDefinitionOn: EventDefinitionOn.BOTH,
withMultipleDefinitions: true,
};
const json = buildDefinitionsAndProcessWithTask();
addEvent(json, 'intermediateCatchEvent', buildEventDefinitionParameter, {
name: 'name',
});
expect(json).toEqual({
definitions: {
targetNamespace: '',
messageEventDefinition: [
{
id: 'event_definition_1_id',
},
{
id: 'event_definition_2_id',
},
],
process: {
task: {
id: 'task_id_0',
name: 'task name',
},
intermediateCatchEvent: {
id: 'event_id_0',
messageEventDefinition: ['', {}],
eventDefinitionRef: ['event_definition_1_id', 'event_definition_2_id'],
name: 'name',
},
},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: [
{
id: 'shape_task_id_0',
bpmnElement: 'task_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
{
id: 'shape_event_id_0',
bpmnElement: 'event_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
],
},
},
},
});
},
);
it(
'build json with definitions, process, task, intermediate throw event, ' +
"when bpmnKind='intermediateThrowEvent', eventDefinitionKind='message', eventDefinitionOn=NONE, eventDefinition is defined, name & attachedToRef & isInterrupting is not defined",
() => {
const buildEventDefinitionParameter: BuildEventDefinitionParameter = {
eventDefinitionKind: 'message',
eventDefinitionOn: EventDefinitionOn.NONE,
eventDefinition: { id: '9' },
};
const json = buildDefinitionsAndProcessWithTask();
addEvent(json, 'intermediateThrowEvent', buildEventDefinitionParameter, {});
expect(json).toEqual({
definitions: {
targetNamespace: '',
process: {
task: {
id: 'task_id_0',
name: 'task name',
},
intermediateThrowEvent: {
id: 'event_id_0',
name: undefined,
},
},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: [
{
id: 'shape_task_id_0',
bpmnElement: 'task_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
{
id: 'shape_event_id_0',
bpmnElement: 'event_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
],
},
},
},
});
},
);
it(
'build json with definitions, process, task, intermediate throw event with defined messageEventDefinition, ' +
"when bpmnKind='intermediateThrowEvent', eventDefinitionKind='message', eventDefinitionOn=EVENT, eventDefinition is defined, name & attachedToRef & isInterrupting is not defined",
() => {
const buildEventDefinitionParameter: BuildEventDefinitionParameter = {
eventDefinitionKind: 'message',
eventDefinitionOn: EventDefinitionOn.EVENT,
eventDefinition: { id: '9' },
};
const json = buildDefinitionsAndProcessWithTask();
addEvent(json, 'intermediateThrowEvent', buildEventDefinitionParameter, {});
expect(json).toEqual({
definitions: {
targetNamespace: '',
process: {
task: {
id: 'task_id_0',
name: 'task name',
},
intermediateThrowEvent: {
id: 'event_id_0',
messageEventDefinition: { id: '9' },
name: undefined,
},
},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: [
{
id: 'shape_task_id_0',
bpmnElement: 'task_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
{
id: 'shape_event_id_0',
bpmnElement: 'event_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
],
},
},
},
});
},
);
it(
'build json with definitions with defined messageEventDefinition, process, task, intermediate throw event with eventDefinitionRef, ' +
"when bpmnKind='intermediateThrowEvent', eventDefinitionKind='message', eventDefinitionOn=DEFINITIONS, eventDefinition is defined, name & attachedToRef & isInterrupting is not defined",
() => {
const buildEventDefinitionParameter: BuildEventDefinitionParameter = {
eventDefinitionKind: 'message',
eventDefinitionOn: EventDefinitionOn.DEFINITIONS,
eventDefinition: { id: '9' },
};
const json = buildDefinitionsAndProcessWithTask();
addEvent(json, 'intermediateThrowEvent', buildEventDefinitionParameter, {});
expect(json).toEqual({
definitions: {
targetNamespace: '',
messageEventDefinition: { id: '9' },
process: {
task: {
id: 'task_id_0',
name: 'task name',
},
intermediateThrowEvent: {
id: 'event_id_0',
eventDefinitionRef: '9',
name: undefined,
},
},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: [
{
id: 'shape_task_id_0',
bpmnElement: 'task_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
{
id: 'shape_event_id_0',
bpmnElement: 'event_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
],
},
},
},
});
},
);
it(
'build json with definitions, process, task, intermediate throw event with messageEventDefinition & signalEventDefinition, ' +
"when bpmnKind='intermediateThrowEvent', eventDefinitionKind='message', eventDefinitionOn=EVENT, withDifferentDefinition=true, name & attachedToRef & isInterrupting is not defined",
() => {
const buildEventDefinitionParameter: BuildEventDefinitionParameter = {
eventDefinitionKind: 'message',
eventDefinitionOn: EventDefinitionOn.EVENT,
withDifferentDefinition: true,
};
const json = buildDefinitionsAndProcessWithTask();
addEvent(json, 'intermediateThrowEvent', buildEventDefinitionParameter, {});
expect(json).toEqual({
definitions: {
targetNamespace: '',
process: {
task: {
id: 'task_id_0',
name: 'task name',
},
intermediateThrowEvent: {
id: 'event_id_0',
messageEventDefinition: '',
signalEventDefinition: '',
name: undefined,
},
},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: [
{
id: 'shape_task_id_0',
bpmnElement: 'task_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
{
id: 'shape_event_id_0',
bpmnElement: 'event_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
],
},
},
},
});
},
);
it(
'build json with definitions, process, task, intermediate throw event with messageEventDefinition & signalEventDefinition, ' +
"when bpmnKind='intermediateThrowEvent', eventDefinitionKind='signal', eventDefinitionOn=EVENT, withDifferentDefinition=true, name & attachedToRef & isInterrupting is not defined",
() => {
const buildEventDefinitionParameter: BuildEventDefinitionParameter = {
eventDefinitionKind: 'signal',
eventDefinitionOn: EventDefinitionOn.EVENT,
withDifferentDefinition: true,
};
const json = buildDefinitionsAndProcessWithTask();
addEvent(json, 'intermediateThrowEvent', buildEventDefinitionParameter, {});
expect(json).toEqual({
definitions: {
targetNamespace: '',
process: {
task: {
id: 'task_id_0',
name: 'task name',
},
intermediateThrowEvent: {
id: 'event_id_0',
messageEventDefinition: '',
signalEventDefinition: '',
name: undefined,
},
},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: [
{
id: 'shape_task_id_0',
bpmnElement: 'task_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
{
id: 'shape_event_id_0',
bpmnElement: 'event_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
],
},
},
},
});
},
);
it(
'build json with definitions with messageEventDefinition & signalEventDefinition with ids, process, task, intermediate throw event with messageEventDefinition & signalEventDefinition & eventDefinitionRefs, ' +
"when bpmnKind='intermediateThrowEvent', eventDefinitionKind='signal', eventDefinitionOn=BOTH, withDifferentDefinition=true, name & attachedToRef & isInterrupting is not defined",
() => {
const buildEventDefinitionParameter: BuildEventDefinitionParameter = {
eventDefinitionKind: 'signal',
eventDefinitionOn: EventDefinitionOn.BOTH,
withDifferentDefinition: true,
};
const json = buildDefinitionsAndProcessWithTask();
addEvent(json, 'intermediateThrowEvent', buildEventDefinitionParameter, {});
expect(json).toEqual({
definitions: {
targetNamespace: '',
messageEventDefinition: {
id: 'other_event_definition_id',
},
signalEventDefinition: {
id: 'event_definition_id',
},
process: {
task: {
id: 'task_id_0',
name: 'task name',
},
intermediateThrowEvent: {
id: 'event_id_0',
messageEventDefinition: '',
signalEventDefinition: '',
eventDefinitionRef: ['event_definition_id', 'other_event_definition_id'],
name: undefined,
},
},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: [
{
id: 'shape_task_id_0',
bpmnElement: 'task_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
{
id: 'shape_event_id_0',
bpmnElement: 'event_id_0',
Bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
},
],
},
},
},
});
},
);
});
|
bonitasoft-labs/bpmn-js
|
test/e2e/bpmn.rendering.test.ts
|
/**
* Copyright 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import 'jest-playwright-preset';
import type { Page } from 'playwright';
import { getBpmnDiagramNames } from './helpers/test-utils';
import type { StyleOptions } from './helpers/visu/bpmn-page-utils';
import { AvailableTestPages, PageTester } from './helpers/visu/bpmn-page-utils';
import type { ImageSnapshotThresholdConfig } from './helpers/visu/image-snapshot-config';
import { ImageSnapshotConfigurator, MultiBrowserImageSnapshotThresholds } from './helpers/visu/image-snapshot-config';
class ImageSnapshotThresholds extends MultiBrowserImageSnapshotThresholds {
constructor() {
// chromium: max on macOS - the local diff was 0.00516920660650344%
// threshold for webkit is taken from macOS only
super({ chromium: 0.006 / 100, firefox: 0.02 / 100, webkit: 0.12 / 100 });
}
protected override getChromiumThresholds(): Map<string, ImageSnapshotThresholdConfig> {
// if no dedicated information, set minimal threshold to make test pass on GitHub Workflow
// linux threshold are set for Ubuntu
return new Map<string, ImageSnapshotThresholdConfig>([
[
'flows.message.02.labels.and.complex.paths',
{
macos: 0.05 / 100, // 0.04335117590119619%
windows: 0.13 / 100, // 0.12203782032372823%
},
],
[
'group.01.in.process.with.label',
{
macos: 0.02 / 100, // 0.01749142091445055%
windows: 0.03 / 100, // 0.028794961672506947%
},
],
[
'group.02.in.collaboration.with.label',
{
macos: 0.02 / 100, // 0.01128137033959975%
windows: 0.04 / 100, // 0.03137680045437463%
},
],
[
'labels.01.general',
{
macos: 0.59 / 100, // 0.58878433419145%
windows: 0.423 / 100, // 0.41473463002763555%
},
],
[
'labels.02.position.and.line.breaks',
{
linux: 0.009 / 100, // 0.008114783064627762%
macos: 0.92 / 100, // 0.9143424811214107%
windows: 0.59 / 100, // 0.5844660139573077%
},
],
[
'labels.03.default.position',
{
linux: 0.002 / 100, // 0.0013799735258945844%
macos: 0.36 / 100, // 0.35527645122680473%
windows: 0.32 / 100, // 0.3125578154609565%
},
],
[
'labels.04.fonts',
{
macos: 0.18 / 100, // 0.17224316335068268%
windows: 0.21 / 100, // 0.2083830906789208%
},
],
[
'pools.01.labels.and.lanes',
{
macos: 0.09 / 100, // 0.08291308761130267%
windows: 0.23 / 100, // 0.21990738071808735%
},
],
[
'pools.02.vertical.with.lanes',
{
macos: 0.13 / 100, // 0.12482014769641389%
windows: 0.14 / 100, // 0.13308164928160784%
},
],
[
'pools.03.black.box',
{
macos: 0.095 / 100, // 0.0935782032063015%
windows: 0.12 / 100, // 0.1184446265753869%
},
],
// tests without labels
[
'gateways',
{
macos: 0.000006, // 0.0005804554357724534%
},
],
[
'events',
{
macos: 0.00001, // 0.000988153090064614%
},
],
[
'call.activities',
{
macos: 0.000005, // 0.0004123713869708112%
},
],
]);
}
protected override getFirefoxThresholds(): Map<string, ImageSnapshotThresholdConfig> {
return new Map<string, ImageSnapshotThresholdConfig>([
[
'flows.message.02.labels.and.complex.paths',
{
linux: 0.09 / 100, // 0.08377044926310973%
macos: 0.13 / 100, // 0.12624011437493143%
windows: 0.73 / 100, // 0.7275118149390969%
},
],
[
'group.01.in.process.with.label',
{
windows: 0.2 / 100, // 0.19944779635067134%
},
],
[
'group.02.in.collaboration.with.label',
{
windows: 0.24 / 100, // 0.23009823201961543%
},
],
[
'labels.01.general',
{
linux: 0.23 / 100, // 0.22239085167347072%
macos: 0.82 / 100, // 0.818150021840347%
// very high value due to font rendering discrepancies with chromium rendering
windows: 11.55 / 10, // 11.549215850525563%
},
],
[
'labels.02.position.and.line.breaks',
{
// TODO possible rendering issue so high threshold value
linux: 2.54 / 100, // 2.5316594800931735%
macos: 3.22 / 100, // 3.213605890318172%
// very high threshold
windows: 15.75 / 100, // 15.741601399131824%
},
],
[
'labels.03.default.position',
{
linux: 0.64 / 100, // 0.6356854597329709%
macos: 0.9 / 100, // 0.8910384426042195%
// TODO possible rendering issue so high threshold value
windows: 2.35 / 100, // 2.3456231064214905%
},
],
[
'labels.04.fonts',
{
// high values due to font rendering discrepancies with chromium rendering
linux: 1.43 / 100, // 1.4296226221777508%
macos: 0.88 / 100, // 0.8747774724672697%
windows: 1.68 / 100, // 1.6735128438225666%
},
],
[
'pools.01.labels.and.lanes',
{
macos: 0.09 / 100, // 0.08552532456441721%
windows: 0.56 / 100, // 0.5571042176931162%
},
],
[
'pools.02.vertical.with.lanes',
{
macos: 0.13 / 100, // 0.1257657147324509%
windows: 0.75 / 100, // 0.7432204108300144%
},
],
[
'pools.03.black.box',
{
linux: 0.08 / 100, // 0.07283646777227482%
macos: 0.14 / 100, // 0.13474247576623632%
windows: 0.66 / 100, // 0.6566433292574891%
},
],
// tests without labels
[
'associations.and.annotations.01.general',
{
linux: 0.074 / 100, // 0.07377888682271738%
macos: 0.074 / 100, // 0.07377888682271738%
windows: 0.074 / 100, // 0.07377888682271738%
},
],
[
'markers.01.positioning',
{
linux: 0.00022, // 0.02063400006822036%
macos: 0.00021, // 0.02063400006822036%
windows: 0.00021, // 0.02063400006822036%
},
],
[
'markers.02.different.tasks.sizes',
{
linux: 0.00026, // 0.02578305330844799%
macos: 0.00026, // 0.02578305330844799%
windows: 0.00026, // 0.02578305330844799%
},
],
]);
}
protected override getWebkitThresholds(): Map<string, ImageSnapshotThresholdConfig> {
return new Map<string, ImageSnapshotThresholdConfig>([
[
'flows.message.02.labels.and.complex.paths',
{
macos: 0.41 / 100, // 0.40487233108913445%
},
],
[
'labels.01.general',
{
// TODO possible rendering issue so high threshold value
macos: 1.25 / 100, // 1.2428419116196077%
},
],
[
'labels.02.position.and.line.breaks',
{
// TODO possible rendering issue so high threshold value
macos: 6.11 / 100, // 6.105183205727094%
},
],
[
'labels.03.default.position',
{
macos: 0.64 / 100, // 0.6346061558805904%
},
],
[
'labels.04.fonts',
{
macos: 0.61 / 100, // 0.6044319789370367%
},
],
[
'pools.01.labels.and.lanes',
{
macos: 0.21 / 100, // 0.20749068678074245%
},
],
[
'pools.02.vertical.with.lanes',
{
macos: 0.24 / 100, // 0.23336351480325318%
},
],
[
'pools.03.black.box',
{
macos: 0.36 / 100, // 0.3576987596416892%
},
],
// tests without labels
[
'events',
{
macos: 0.0014, // 0.1397832014147449%
},
],
]);
}
}
const styleOptionsPerDiagram = new Map<string, StyleOptions>([
[
'associations.and.annotations.04.target.edges',
{
sequenceFlow: { useLightColors: true },
},
],
]);
describe('BPMN rendering', () => {
const imageSnapshotConfigurator = new ImageSnapshotConfigurator(new ImageSnapshotThresholds(), 'bpmn-rendering');
const diagramSubfolder = 'bpmn-rendering';
const pageTester = new PageTester({ targetedPage: AvailableTestPages.BPMN_RENDERING, diagramSubfolder }, <Page>page);
const bpmnDiagramNames = getBpmnDiagramNames(diagramSubfolder);
describe('BPMN diagram files are present', () => {
// non exhaustive list
it.each(['gateways', 'events'])('%s', (bpmnDiagramName: string) => {
expect(bpmnDiagramNames).toContain(bpmnDiagramName);
});
});
it.each(bpmnDiagramNames)(`%s`, async (bpmnDiagramName: string) => {
await pageTester.gotoPageAndLoadBpmnDiagram(bpmnDiagramName, {
styleOptions: styleOptionsPerDiagram.get(bpmnDiagramName),
});
const image = await page.screenshot({ fullPage: true });
const config = imageSnapshotConfigurator.getConfig(bpmnDiagramName);
expect(image).toMatchImageSnapshot(config);
});
});
|
MauroDataMapper/mdm-ui
|
src/app/shared/path-name/path-name.service.spec.ts
|
<gh_stars>1-10
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { setupTestModuleForService } from '@mdm/testing/testing.helpers';
import { PathElement, PathElementType } from './path-name.model';
import { PathNameService } from './path-name.service';
describe('PathNameService', () => {
let service: PathNameService;
beforeEach(() => {
service = setupTestModuleForService(PathNameService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
describe('parsing path name', () => {
it.each([undefined, null, ''])('should return nothing when no path is provided', (path) => {
const actual = service.parse(path);
expect(actual).toBeNull();
});
const pathCases: Array<[string, PathElement[]]> = [
[
'dm:Test Data Model',
[
{ type: PathElementType.DataModel, typeName: 'Data model', label: 'Test Data Model' }
]
],
[
'dm:Test Data Model$another-branch',
[
{ type: PathElementType.DataModel, typeName: 'Data model', version: 'another-branch', label: 'Test Data Model' }
]
],
[
'dm:Test Data Model$2.0.0',
[
{ type: PathElementType.DataModel, typeName: 'Data model', version: '2.0.0', label: 'Test Data Model' }
]
],
[
'te:Test Terminology',
[
{ type: PathElementType.Terminology, typeName: 'Terminology', label: 'Test Terminology' }
]
],
[
'cs:Test Code Set',
[
{ type: PathElementType.CodeSet, typeName: 'Code set', label: 'Test Code Set' }
]
],
[
'dm:Test Data Model|dc:Test Data Class',
[
{ type: PathElementType.DataModel, typeName: 'Data model', label: 'Test Data Model' },
{ type: PathElementType.DataClass, typeName: 'Data class', label: 'Test Data Class' }
]
],
[
'dm:Test Data Model|dc:Test Data Class|de:Test Data Element',
[
{ type: PathElementType.DataModel, typeName: 'Data model', label: 'Test Data Model' },
{ type: PathElementType.DataClass, typeName: 'Data class', label: 'Test Data Class' },
{ type: PathElementType.DataElement, typeName: 'Data element', label: 'Test Data Element' }
]
],
[
'dm:Test Data Model@description',
[
{
type: PathElementType.DataModel,
typeName: 'Data model',
label: 'Test Data Model',
property: {
name: 'description',
qualifiedName: ['description']
}
}
]
],
[
'dm:Test Data Model$2.0.0@description',
[
{
type: PathElementType.DataModel,
typeName: 'Data model',
label: 'Test Data Model',
version: '2.0.0',
property: {
name: 'description',
qualifiedName: ['description']
}
}
]
],
[
'dm:Test Data Model@rule:rule-representation',
[
{
type: PathElementType.DataModel,
typeName: 'Data model',
label: 'Test Data Model',
property: {
name: 'rule-representation',
qualifiedName: ['rule', 'rule-representation']
}
}
]
],
[
'dm:Test Data Model|dc:Test Data Class@description',
[
{
type: PathElementType.DataModel,
typeName: 'Data model',
label: 'Test Data Model'
},
{
type: PathElementType.DataClass,
typeName: 'Data class',
label: 'Test Data Class',
property: {
name: 'description',
qualifiedName: ['description']
}
}
]
],
[
'dm:Test Data Model$test-branch|dc:Test Data Class@description',
[
{
type: PathElementType.DataModel,
typeName: 'Data model',
label: 'Test Data Model',
version: 'test-branch'
},
{
type: PathElementType.DataClass,
typeName: 'Data class',
label: 'Test Data Class',
property: {
name: 'description',
qualifiedName: ['description']
}
}
]
]
];
it.each(pathCases)(
'when parsing %p then the correct parsed output is returned',
(path: string, expected: PathElement[]) => {
const actual = service.parse(path);
expect(actual).toMatchObject(expected);
});
const badPathCases = [
'dm',
'dm:',
':label',
'dm:label|dm',
'dm:label|dm:',
'dm:label|:label'
];
it.each(badPathCases)(
'when parsing %p then an error is thrown',
(path: string) => {
expect(() => {
service.parse(path);
}).toThrow();
});
});
});
|
MauroDataMapper/mdm-ui
|
src/app/utility/model-path/model-path.component.ts
|
<gh_stars>1-10
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, OnInit, Input } from '@angular/core';
import { ElementTypesService } from '@mdm/services/element-types.service';
@
Component({
selector: 'mdm-model-path',
templateUrl: './model-path.component.html',
})
export class ModelPathComponent implements OnInit {
@Input() path: any[];
@Input() newWindow: boolean;
@Input() doNotDisplayStatus: boolean;
@Input() showHref = true;
@Input() doNotShowParentDataModel: boolean;
updatedPath: any[];
targetWindow;
showAsSimpleText;
constructor(private elementTypes: ElementTypesService) { }
ngOnInit() {
this.updatedPath = [];
if (this.path) {
this.path.forEach((p, index) => {
if(p.domainType === 'ReferenceDataModel') {
p.link = this.elementTypes.getLinkUrl({ id: p.id, domainType: 'ReferenceDataModel' });
}
else if(p.domainType === 'Terminology'){
p.link = this.elementTypes.getLinkUrl({ id: p.id, domainType: 'Terminology' });
}
else {
if (index === 0) {
p.link = this.elementTypes.getLinkUrl({ id: p.id, domainType: 'DataModel' });
} else if (index === 1) {
p.link = this.elementTypes.getLinkUrl({ id: p.id, model: this.path[0].id, domainType: 'DataClass' });
} else {
p.link = this.elementTypes.getLinkUrl({ id: p.id, model: this.path[0].id, parentDataClass: this.path[index - 1].id, domainType: 'DataClass' });
}
}
this.updatedPath.push(p);
});
}
this.targetWindow = '';
if (this.newWindow) {
this.targetWindow = '_blank';
}
}
}
|
MauroDataMapper/mdm-ui
|
src/app/app-routing.module.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Injector, NgModule } from '@angular/core';
import { AboutComponent } from './about/about.component';
import { FolderComponent } from './folder/folder.component';
import { NotFoundComponent } from './errors/not-found/not-found.component';
import { DataModelDefaultComponent } from './utility/data-model-default.component';
import { NotImplementedComponent } from './errors/not-implemented/not-implemented.component';
import { NotAuthorizedComponent } from './errors/not-authorized/not-authorized.component';
import { ServerErrorComponent } from './errors/server-error/server-error.component';
import { DataModelMainComponent } from './wizards/dataModel/data-model-main/data-model-main.component';
import { DataClassMainComponent } from './wizards/dataClass/data-class-main/data-class-main.component';
import { DataTypeMainComponent } from './wizards/dataType/data-type-main/data-type-main.component';
import { HomeComponent } from './home/home.component';
import { ImportModelsComponent } from './import-models/import-models.component';
import { SearchComponent } from './search/search.component';
import { TerminologyComponent } from './terminology/terminology.component';
import { TwoSidePanelComponent } from './two-side-panel/two-side-panel.component';
import { Ng2StateDeclaration, UIRouterModule } from '@uirouter/angular';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
import { UiViewComponent } from './shared/ui-view/ui-view.component';
import { ModelsComponent } from './shared/models/models.component';
import { DataModelComponent } from './dataModel/data-model.component';
import { ReferenceDataComponent } from './referenceData/reference-data.component';
import { DataClassComponent } from './dataClass/data-class/data-class.component';
import { DataElementComponent } from './dataElement/data-element/data-element.component';
import { ClassificationComponent } from './classification/classification.component';
import { AppContainerComponent } from './app-container/app-container.component';
import { AppComponent } from './app.component';
import { ExportModelsComponent } from './export-models/export-models.component';
import { DataElementMainComponent } from './wizards/dataElement/data-element-main/data-element-main.component';
import { DataTypeComponent } from './data-type/data-type.component';
import { ResetPasswordComponent } from './reset-password/reset-password.component';
import { TermComponent } from './term/term/term.component';
import { LinkSuggestionComponent } from './link-suggestion/link-suggestion.component';
import { ModelComparisonComponent } from './model-comparison/model-comparison.component';
import { CodeSetMainComponent } from './wizards/codeSet/code-set-main/code-set-main.component';
import { CodeSetComponent } from './code-set/code-set/code-set.component';
import { ModelMergingComponent } from './model-merging/model-merging.component';
import { ModelsMergingGraphComponent } from './models-merging-graph/models-merging-graph.component';
import { EnumerationValuesComponent } from '@mdm/enumerationValues/enumeration-values/enumeration-values.component';
import { HookResult, StateObject, Transition, TransitionService, UIRouter } from '@uirouter/core';
import { EditingService } from '@mdm/services/editing.service';
import { SubscribedCatalogueMainComponent } from './subscribed-catalogues/subscribed-catalogue-main/subscribed-catalogue-main.component';
import { FederatedDataModelMainComponent } from './subscribed-catalogues/federated-data-model-main/federated-data-model-main.component';
import { ServerTimeoutComponent } from './errors/server-timeout/server-timeout.component';
import { NewVersionComponent } from './shared/new-version/new-version.component';
import { VersionedFolderComponent } from './versioned-folder/versioned-folder/versioned-folder.component';
import { MergeDiffContainerComponent } from './merge-diff/merge-diff-container/merge-diff-container.component';
import { OpenIdConnectAuthorizeComponent } from './security/open-id-connect-authorize/open-id-connect-authorize.component';
import { DoiRedirectComponent } from './doi-redirect/doi-redirect.component';
import { SecurityHandlerService, SharedService } from './services';
/**
* Collection of all page state routes.
*
* To allow anonymous access to a route, add `allowAnonymous: true` to the `data` of a state:
*
* @example
*
* ```ts
* states: [
* {
* name: 'appContainer.mainApp.public',
* component: PublicComponent,
* url: '/public',
* data: {
* allowAnonymous: true
* }
* }
* ]
* ```
*/
export const pageRoutes: { states: Ng2StateDeclaration[] } = {
states: [
{
name: 'appContainer',
component: AppComponent
},
{
name: 'appContainer.mainApp',
component: AppContainerComponent
},
{
name: 'appContainer.mainApp.about',
url: '/about',
component: AboutComponent,
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.twoSidePanel',
component: TwoSidePanelComponent
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue',
url: '/catalogue',
data: {
allowAnonymous: true
},
views: {
left: {
component: ModelsComponent
},
'': {
component: UiViewComponent
}
}
},
{
url: '/folder/:id/{tabView:string}?edit',
name: 'appContainer.mainApp.twoSidePanel.catalogue.folder',
component: FolderComponent,
params: { tabView: { value: null, squash: true, dynamic: true } },
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.allDataModel',
url: '/dataModel/all',
component: DataModelDefaultComponent,
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.notImplemented',
url: '/notImplemented',
component: NotImplementedComponent,
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.notAuthorized',
url: '/notAuthorized',
component: NotAuthorizedComponent,
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.serverError',
url: '/serverError',
component: ServerErrorComponent,
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.serverTimeout',
url: '/serverTimeout',
component: ServerTimeoutComponent,
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.notFound',
url: '/notFound',
component: NotFoundComponent,
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.newVersionModel',
url: '/:domainType/newVersion/:id',
component: NewVersionComponent
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.dataModel',
url: '/dataModel/:id/{tabView:string}',
component: DataModelComponent,
params: { tabView: { dynamic: true, value: null, squash: true } },
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.NewDataModel',
url: '/dataModelNew/new?parentFolderId&parentDomainType',
component: DataModelMainComponent
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.ReferenceDataModel',
url: '/referenceDataModel/:id/{tabView:string}',
component: ReferenceDataComponent,
params: { tabView: { dynamic: true, value: null, squash: true } },
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.NewDataClass',
url:
'/dataClassNew/new?parentDataModelId&grandParentDataClassId&parentDataClassId',
component: DataClassMainComponent
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.NewDataType',
url: '/dataTypeNew/new?parentDataModelId',
component: DataTypeMainComponent
},
{
name: 'appContainer.mainApp.home',
url: '/home',
component: HomeComponent,
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.default',
url: '',
component: HomeComponent,
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.openIdConnectAuthorizing',
url: '/open-id-connect/authorize',
component: OpenIdConnectAuthorizeComponent,
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.doiRedirect',
url: '/doi/:id',
component: DoiRedirectComponent,
params: {
id: {
type: 'string',
raw: true
}
},
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.search',
url: '/search',
component: SearchComponent,
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.terminology',
url: '/terminology/:id/{tabView:string}',
component: TerminologyComponent,
params: { tabView: { dynamic: true, value: null, squash: true } },
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.dataClass',
url: '/dataClass/:dataModelId/:dataClassId/:id/{tabView:string}',
component: DataClassComponent,
params: { tabView: { dynamic: true, value: null, squash: true } },
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.dataElement',
url:
'/dataElement/:dataModelId/:dataClassId/:id/{tabView:string}?parentId',
params: { tabView: { dynamic: true, value: null, squash: true } },
component: DataElementComponent,
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.classification',
url: '/classification/:id/{tabView:string}',
component: ClassificationComponent,
params: { tabView: { dynamic: true, value: null, squash: true } },
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.import',
url: '/import/:importType',
component: ImportModelsComponent
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.export',
url: '/export/:exportType',
component: ExportModelsComponent
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.NewDataElement',
url: '/dataElement/new?parentDataModelId&grandParentDataClassId&parentDataClassId',
component: DataElementMainComponent
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.dataType',
url: '/dataType/:dataModelId/:id/{tabView:string}',
component: DataTypeComponent,
params: {
tabView: { dynamic: true, value: null, squash: true },
data: {
allowAnonymous: true
}
}
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.enumerationValues',
url: '/enumerationType/:dataModelId/:dataTypeId/:id/{tabView:string}',
component: EnumerationValuesComponent,
params: { tabView: { dynamic: true, value: null, squash: true } }
},
{
name: 'appContainer.mainApp.resetPassword',
url: '/resetpassword?uid&token',
component: ResetPasswordComponent,
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.term',
url: '/term/:terminologyId/:id/{tabView:string}',
component: TermComponent,
params: { tabView: { dynamic: true, value: null, squash: true } },
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.linkSuggestion',
url: '/linkSuggestion/:sourceDMId?&targetDMId&sourceDCId&sourceDEId',
component: LinkSuggestionComponent
},
{
name: 'appContainer.mainApp.modelsComparison',
url: '/modelsComparison/:sourceId/:targetId',
component: ModelComparisonComponent
},
{
name: 'appContainer.mainApp.modelsMerging',
url: '/modelsMerging/:catalogueDomainType/:sourceId/:targetId',
component: ModelMergingComponent
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.modelsMergingGraph',
url: '/modelsMergingGraph/:modelType/:modelId',
component: ModelsMergingGraphComponent
},
{
name: 'appContainer.mainApp.mergeDiff',
url: '/mergeDiff/:catalogueDomainType/:sourceId/:targetId',
component: MergeDiffContainerComponent,
params: {
targetId: null
}
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.NewCodeSet',
url: '/codeSet/new?parentFolderId&parentDomainType',
component: CodeSetMainComponent
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.codeSet',
url: '/codeSet/:id/{tabView:string}',
component: CodeSetComponent,
params: { tabView: { dynamic: true, value: null, squash: true } },
data: {
allowAnonymous: true
}
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.subscribedCatalogue',
url: '/subscribedCatalogue/:id/{tabView:string}',
component: SubscribedCatalogueMainComponent,
params: { tabView: { dynamic: true, value: null, squash: true } }
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.federatedDataModel',
url: '/subscribedCatalogue/:parentId/federatedDataModel/:id/{tabView:string}',
component: FederatedDataModelMainComponent,
params: {
tabView: { dynamic: true, value: null, squash: true },
dataModel: null
}
},
{
name: 'appContainer.mainApp.twoSidePanel.catalogue.versionedFolder',
url: '/versionedFolder/:id/{tabView:string}',
component: VersionedFolderComponent,
params: { tabView: { dynamic: true, value: null, squash: true } },
data: {
allowAnonymous: true
}
}
]
};
/**
* Router transition hook to check editing state of app before switching views
*/
const editingViewTransitionHooks = (transitions: TransitionService, editing: EditingService) => {
/**
* Check each state transition where the "from" view state is marked as editable.
*/
const canLeaveStateCriteria = {
from: (state: StateObject) => state.name && editing.isRouteEditable(state.name)
};
/**
* Check a state transition by checking if any unsaved edits still exist. If so, confirm with the user whether to continue.
*/
const canLeaveStateAction = () => editing.confirmLeaveAsync().toPromise();
/**
* When entering each view, ensure that the global editing state of the app is reset.
*/
const onEnteringViewAction = () => editing.stop();
transitions.onBefore(canLeaveStateCriteria, canLeaveStateAction);
transitions.onEnter({}, onEnteringViewAction);
};
/**
* Router transition hooks for checking role access before switching views.
*
* @see {@link StateRoleAccessService}
*/
const roleTransitionHooks = (transitions: TransitionService) => {
/**
* Before starting a transition, check if the user/role has access to this route.
*/
const canAccessRoute = (transition: Transition): HookResult => {
const securityHandler = transition.injector().get<SecurityHandlerService>(SecurityHandlerService);
const shared = transition.injector().get<SharedService>(SharedService);
const state = transition.$to();
shared.current = state.name;
if (state.data?.allowAnonymous) {
return true;
}
return securityHandler.isLoggedIn();
};
transitions.onStart({}, canAccessRoute);
};
/**
* Configuration of the `UIRouter`.
*/
const routerConfigFn = (router: UIRouter, injector: Injector) => {
const transitions = router.transitionService;
const editing = injector.get<EditingService>(EditingService);
editingViewTransitionHooks(transitions, editing);
roleTransitionHooks(transitions);
};
@NgModule({
imports: [UIRouterModule.forChild({
states: pageRoutes.states,
config: routerConfigFn
})],
providers: [
{
provide: LocationStrategy,
useClass: HashLocationStrategy
}
]
})
export class AppRoutingModule {
constructor() { }
}
|
MauroDataMapper/mdm-ui
|
src/app/utility/editable-form-buttons/editable-form-buttons.component.ts
|
<gh_stars>1-10
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { EditingService } from '@mdm/services/editing.service';
@Component({
selector: 'mdm-editable-form-buttons',
templateUrl: './editable-form-buttons.component.html',
styleUrls: ['./editable-form-buttons.component.scss']
})
export class EditableFormButtonsComponent implements OnInit {
@Input() deleteIcon = null;
@Input() deleteTitle = '';
@Input() editTitle = '';
@Input() processing: any;
@Input() editable: any;
@Input() onEditClicked: any;
@Input() onDeleteClicked: any;
@Input() onConfirmDelete: any;
@Input() onCancelDelete: any;
@Input() onCancelEdit: any;
@Input() onSave: any;
@Input() hasSeparateEditForm: any;
@Input() textLocation: any;
@Input() hideDelete: any;
@Input() hideEdit: any;
@Input() hideCancel: any;
@Output() delete = new EventEmitter<any>();
public displayDeleteTitle: string = this.deleteTitle;
public displayDeleteIcon: any = this.deleteIcon;
public displayEditTitle: string = this.editTitle;
get isEditorVisible(): boolean {
return this.editable && (this.editable.visible || this.editable.isEditing);
}
constructor(private editingService: EditingService) {}
ngOnInit() {
if (!this.displayDeleteTitle) {
this.displayDeleteTitle = 'Delete';
}
if (!this.displayDeleteIcon) {
this.displayDeleteIcon = 'fa-trash-alt';
}
if (!this.displayEditTitle) {
this.displayEditTitle = 'Edit';
}
if (this.onConfirmDelete) {
this.onConfirmDelete = this.onConfirmDelete();
}
if (this.onEditClicked) {
this.onEditClicked = this.onEditClicked();
}
if (this.onCancelEdit) {
this.onCancelEdit = this.onCancelEdit();
}
if (this.editable) {
this.editable.deletePending = false;
}
}
editClicked() {
if (this.onEditClicked) {
this.onEditClicked();
}
// if it does not have 'hasSeparateEditForm' && has 'editable'
if (!this.hasSeparateEditForm && this.editable) {
this.editable.show();
}
}
/// Delete ----------------------------------------
deleteClicked() {
this.editable.deletePending = true;
}
cancelDeleteClicked() {
if (this.editable) {
this.editable.deletePending = false;
}
if (this.onCancelDelete) {
this.onCancelDelete();
}
if (!this.hideDelete) {
this.editable.deletePending = false;
}
}
confirmDeleteClicked() {
if (this.editable) {
this.editable.deletePending = false;
}
if (this.onConfirmDelete) {
this.onConfirmDelete();
}
if (this.delete) {
this.delete.emit();
}
}
/// ----------------------------------------
cancelEditClicked() {
this.editingService.confirmCancelAsync().subscribe(confirm => {
if (!confirm) {
return;
}
if (this.editable && this.editable.cancel) {
this.editable.cancel();
}
if (this.onCancelEdit) {
this.onCancelEdit();
}
});
}
saveClicked(): any {
if (this.onSave) {
this.onSave();
}
return true; // as it is submit
}
}
|
MauroDataMapper/mdm-ui
|
src/app/directives/show-if-roles-writable.directive.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import {Directive, ElementRef, Input, OnInit} from '@angular/core';
import { Securable, Finalisable } from '@maurodatamapper/mdm-resources';
import {SecurityHandlerService} from '../services/handlers/security-handler.service';
@Directive({
selector: '[mdmShowIfRolesWritable]'
})
export class ShowIfRolesWritableDirective implements OnInit {
@Input() result: Securable & Finalisable;
constructor(private securityHandler: SecurityHandlerService, private elementRef: ElementRef) {
}
ngOnInit(): void {
this.watchRole(this.result);
}
watchRole(newValue : Securable & Finalisable) {
const show = this.securityHandler.showIfRoleIsWritable(newValue);
if (!show) {
this.elementRef.nativeElement.style.display = 'none';
return;
}
}
}
|
MauroDataMapper/mdm-ui
|
src/app/diagram/services/umlclass-diagram.service.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { BasicDiagramService } from './basic-diagram.service';
import { Observable } from 'rxjs';
import * as joint from 'jointjs';
import { MdmResourcesService } from '@mdm/modules/resources';
import { MessageHandlerService } from '@mdm/services/utility/message-handler.service';
export class UmlClassDiagramService extends BasicDiagramService {
private modelId: string;
private allDataClasses: Array<any> = [];
private subClassLinks: Array<any> = [];
private referenceLinks: Array<any> = [];
constructor(protected resourcesService: MdmResourcesService,
protected messageHandler: MessageHandlerService) {
super(resourcesService, messageHandler);
}
getDiagramContent(params: any): Observable<any> {
this.modelId = params.parent.id;
return this.resourcesService.dataModel.hierarchy(this.modelId);
}
render(data: any): void {
this.graph.clear();
this.allDataClasses = [];
this.subClassLinks = [];
this.referenceLinks = [];
this.addAllChildDataClasses(data.body);
this.allDataClasses.forEach(dataClass => {
this.addRectangleCell(dataClass.id, '', 300, dataClass.attributes.length * 25 + 31);
});
this.addLinks();
super.layoutNodes('TB');
this.allDataClasses.forEach(dataClass => {
const oldCell = this.graph.getCell(dataClass.id) as joint.shapes.standard.Rectangle;
this.addUmlClassCell(dataClass.id, dataClass.label, dataClass.attributes, null, oldCell);
});
}
addLinks(): void {
const filledDiamond = 'M 40 0 L 20 10 L 0 0 L 20 -10 z';
this.subClassLinks.forEach(subClassLink => {
const link = new joint.shapes.standard.Link({
id: `${subClassLink.source}-${subClassLink.target}`,
source: { id: subClassLink.source },
target: { id: subClassLink.target },
attrs: {
line: {
sourceMarker: { d: filledDiamond },
targetMarker: { d: '' }
}
}
});
// link.id = flow.id as string;
// link.attr('.marker-target', { d: 'M 40 0 L 20 10 L 0 0 L 20 -10 z', fill: 'black' });
link.connector('rounded', { radius: 40 });
link.toBack();
this.graph.addCell(link);
});
this.referenceLinks.forEach(subClassLink => {
const link = new joint.shapes.standard.Link({
id: `${subClassLink.source}-${subClassLink.name}`,
source: { id: subClassLink.source },
target: { id: subClassLink.target },
attrs: {
line: {
sourceMarker: { d: '' },
targetMarker: { d: '' }
}
}
});
// link.id = flow.id as string;
link.connector('rounded', { radius: 40 });
link.toBack();
this.graph.addCell(link);
});
}
addAllChildDataClasses(container: any): void {
if (container.dataClasses) {
container.dataClasses.forEach(childDataClass => {
this.allDataClasses.push({
id: childDataClass.id,
label: childDataClass.label,
attributes: childDataClass.dataElements.filter(attribute => {
return attribute.dataType.domainType !== 'ReferenceType';
})
});
if (container.domainType !== 'DataModel') {
this.subClassLinks.push({
source: container.id,
target: childDataClass.id
});
}
this.addAllChildDataClasses(childDataClass);
childDataClass.dataElements.filter(attribute => {
return attribute.dataType.domainType === 'ReferenceType';
}).forEach(attribute => {
this.referenceLinks.push({
source: childDataClass.id,
target: attribute.dataType.referenceClass.id,
name: attribute.label
});
});
});
} else if (container.childDataClasses) {
container.childDataClasses.forEach(childDataClass => {
this.allDataClasses.push({
id: childDataClass.id,
label: childDataClass.label,
attributes: childDataClass.dataElements.filter(attribute => {
return attribute.dataType.domainType !== 'ReferenceType';
})
});
if (container.domainType !== 'DataModel') {
this.subClassLinks.push({
source: container.id,
target: childDataClass.id
});
}
this.addAllChildDataClasses(childDataClass);
childDataClass.dataElements.filter(attribute => {
return attribute.dataType.domainType === 'ReferenceType';
}).forEach(attribute => {
this.referenceLinks.push({
source: childDataClass.id,
target: attribute.dataType.referenceClass.id,
name: attribute.label
});
});
});
}
}
layoutNodes(): void {
// console.log('not calling super');
}
configurePaper(): void {
}
canGoUp(): boolean {
return false;
}
goUp(): void {
}
}
|
MauroDataMapper/mdm-ui
|
src/app/model/userDetailsModel.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
export class UserDetailsResult {
id: string;
firstName: string;
lastName: string;
organisation: string;
jobTitle: string;
userRole: string;
groups: any[];
emailAddress: string;
}
|
MauroDataMapper/mdm-ui
|
src/app/diagram/diagram-popup/diagram-popup.component.ts
|
<reponame>MauroDataMapper/mdm-ui
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import {
Component,
Inject,
OnInit,
Optional,
ViewChild,
} from '@angular/core';
import { MdmResourcesService } from '@mdm/modules/resources';
import { MessageHandlerService } from '@mdm/services/utility/message-handler.service';
import {
MatDialog,
MatDialogRef,
MAT_DIALOG_DATA
} from '@angular/material/dialog';
import { DiagramComponent } from '../diagram/diagram.component';
import { DiagramToolbarComponent } from '../diagram-toolbar/diagram-toolbar.component';
import { MatSidenav } from '@angular/material/sidenav';
@Component({
selector: 'mdm-diagram-popup',
templateUrl: './diagram-popup.component.html',
})
export class DiagramPopupComponent implements OnInit {
@ViewChild(DiagramComponent) diagramComponent: DiagramComponent;
@ViewChild(DiagramToolbarComponent) toolbarComponent: DiagramToolbarComponent;
@ViewChild(MatSidenav) drawer: MatSidenav;
node: any;
filterList: Array<any> = [];
constructor(
protected resourcesService: MdmResourcesService,
protected messageHandler: MessageHandlerService,
protected matDialog: MatDialog,
protected dialogRef: MatDialogRef<DiagramPopupComponent>,
@Optional() @Inject(MAT_DIALOG_DATA) public data: any
) {}
ngOnInit(): void {
this.loadTree();
}
popDown(): void {
this.clearFilterClick();
this.dialogRef.close({ diagramComponent: this.diagramComponent });
}
showFilterTree(): void {
this.drawer.toggle();
// this.diagramComponent.filter(this.data.diagramComponent.parent)
}
onNodeChecked(node, parent, checkedList): void {
this.filterList = Object.keys(checkedList);
}
filterClick(): void {
this.diagramComponent.filter(this.data.diagramComponent.parent, this.filterList, this.data.diagramComponent.mode);
}
clearFilterClick(): void {
this.loadTree();
this.diagramComponent.filter(this.data.diagramComponent.parent, [], this.data.diagramComponent.mode);
}
toolbarClick(buttonName: string) {
switch (buttonName) {
case 'popDown':
this.popDown();
break;
case 'showTreeFilter':
this.showFilterTree();
break;
default:
this.diagramComponent.toolbarClick(buttonName);
}
}
private loadTree() {
this.node = null;
this.resourcesService.tree.get('folders', this.data.diagramComponent.parent.domainType, this.data.diagramComponent.parent.id)
.subscribe((result) => {
this.node = {
children: result.body,
isRoot: true,
};
});
}
}
|
MauroDataMapper/mdm-ui
|
src/app/services/element-selector-dialogue.service.spec.ts
|
<gh_stars>1-10
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { TestBed } from '@angular/core/testing';
import { ElementSelectorDialogueService } from './element-selector-dialogue.service';
import { NgxSkeletonLoaderModule } from 'ngx-skeleton-loader';
import { ProfilePictureComponent } from '@mdm/shared/profile-picture/profile-picture.component';
import { ByteArrayToBase64Pipe } from '@mdm/pipes/byte-array-to-base64.pipe';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatDialogModule } from '@angular/material/dialog';
describe('ElementSelectorDialogueService', () => {
beforeEach(() => TestBed.configureTestingModule({
imports: [
NgxSkeletonLoaderModule,
MatTooltipModule,
MatDialogModule
],
declarations: [
ProfilePictureComponent,
ByteArrayToBase64Pipe
]
}));
it('should be created', () => {
const service: ElementSelectorDialogueService = TestBed.inject(ElementSelectorDialogueService);
expect(service).toBeTruthy();
});
});
|
MauroDataMapper/mdm-ui
|
src/app/model/federated-data-model.ts
|
<gh_stars>1-10
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { AvailableDataModel, CatalogueItemDomainType, SubscribedDataModel } from '@maurodatamapper/mdm-resources';
export class FederatedDataModel {
catalogueId: string;
modelId?: string;
label: string;
description?: string;
modelType?: CatalogueItemDomainType;
subscriptionId?: string;
folderId?: string;
folderLabel?: string;
version? : string;
constructor(
catalogueId: string,
available?: AvailableDataModel,
subscription?: SubscribedDataModel) {
this.catalogueId = catalogueId;
this.modelId = available?.modelId;
this.label = available?.label;
this.description = available?.description;
this.version = available?.version;
this.modelType = available?.modelType;
this.subscriptionId = subscription?.id;
this.folderId = subscription?.folderId;
}
get isSubscribed(): boolean {
return this.subscriptionId !== undefined;
}
}
|
MauroDataMapper/mdm-ui
|
src/app/modals/finalise-modal/finalise-modal.component.ts
|
<reponame>MauroDataMapper/mdm-ui<gh_stars>1-10
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, OnInit, Inject, ChangeDetectorRef } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { FinalisePayload } from '@maurodatamapper/mdm-resources';
import { ModalDialogStatus } from '@mdm/constants/modal-dialog-status';
export interface FinaliseModalResponse {
status: ModalDialogStatus;
request?: FinalisePayload;
}
@Component({
selector: 'mdm-finalise-modal',
templateUrl: './finalise-modal.component.html',
styleUrls: ['./finalise-modal.component.scss']
})
export class FinaliseModalComponent implements OnInit {
title: string;
message: string;
username: string;
password: string;
okTitle: string;
cancelTitle: string;
cancelShown: boolean;
btnType: string;
defaultVersion = 'Major';
showCustomVersion = false;
version = '';
versionMajor = '';
versionMinor = '';
versionPatch = '';
currentVersion = '0.0.0';
modelVersion = '0.0.0';
versionTag: string;
constructor(
public dialogRef: MatDialogRef<FinaliseModalComponent, FinaliseModalResponse>,
@Inject(MAT_DIALOG_DATA) public data: any,
private changeRef: ChangeDetectorRef) {
}
ngOnInit() {
this.okTitle = this.data.okBtnTitle ? this.data.okBtnTitle : 'OK';
this.btnType = this.data.btnType ? this.data.btnType : 'primary';
this.cancelTitle = this.data.cancelBtnTitle ? this.data.cancelBtnTitle : 'Cancel';
this.modelVersion = this.data.modelVersion ? this.data.modelVersion : '0.0.0';
this.title = this.data.title;
this.message = this.data.message;
this.password = '';
this.cancelShown = this.data.cancelShown != null ? this.data.cancelShown : true;
this.changeRef.detectChanges();
this.currentVersion = this.data.modelVersion;
const nameSplit = this.modelVersion.split('.');
if (nameSplit.length === 3) {
this.data.versionList = this.defaultVersion;
this.versionMajor = `The 'Major' option will finalise the model with version <strong>${parseInt(nameSplit[0], 10) + 1}</strong>.0.0`;
this.versionMinor = `The 'Minor' option will finalise the model with version ${parseInt(nameSplit[0], 10)}.<strong>${parseInt(nameSplit[1], 10) + 1}</strong>.0`;
this.versionPatch = `The 'Patch' option will finalise the model with version ${parseInt(nameSplit[0], 10)}.${parseInt(nameSplit[1], 10)}.<strong>${parseInt(nameSplit[2], 10) + 1}</strong>`;
} else {
this.data.versionList = 'Custom';
this.showCustomVersion = true;
this.versionMajor = 'Example: 1.0.0 <i class="fas fa-long-arrow-alt-right"></i> <strong> 2</strong>.0.0';
this.versionMinor = 'Example: 1.0.0 <i class="fas fa-long-arrow-alt-right"></i> 1.<strong>1</strong>.0';
this.versionPatch = 'Example: 1.0.0 <i class="fas fa-long-arrow-alt-right"></i> 1.0.<strong>1</strong>';
}
}
onVersionChange() {
if (this.data.versionList === 'Custom') {
this.showCustomVersion = !this.showCustomVersion;
} else {
this.showCustomVersion = false;
}
}
ok() {
const useCustomVersion = this.data.versionList === 'Custom';
const request: FinalisePayload = {
version: useCustomVersion ? this.version : undefined,
versionChangeType: !useCustomVersion ? this.data.versionList : undefined,
versionTag: this.versionTag
};
this.dialogRef.close({
status: ModalDialogStatus.Ok,
request
});
}
cancel() {
this.dialogRef.close({ status: ModalDialogStatus.Cancel });
}
close() {
this.dialogRef.close({ status: ModalDialogStatus.Close });
}
}
|
MauroDataMapper/mdm-ui
|
src/app/term/codeset-list/term-codeset-list.component.ts
|
<reponame>MauroDataMapper/mdm-ui
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { AfterViewInit, Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges, ViewChild } from '@angular/core';
import { MatSort } from '@angular/material/sort';
import { MdmResourcesService } from '@mdm/modules/resources';
import { CodeSet, TermDetail } from '@maurodatamapper/mdm-resources';
import { MdmTableDataSource } from '@mdm/utility/table-data-source';
import { merge } from 'rxjs';
import { MdmPaginatorComponent } from '@mdm/shared/mdm-paginator/mdm-paginator';
@Component({
selector: 'mdm-term-codeset-list',
templateUrl: './term-codeset-list.component.html',
styleUrls: ['./term-codeset-list.component.scss']
})
export class TermCodeSetListComponent implements OnInit, AfterViewInit, OnChanges {
@Input() term: TermDetail;
@Input() pageSize = 10;
@Input() canEdit = false;
@Input() canDelete = false;
@Output() totalCount = new EventEmitter<number>();
@Output() selectedCodeSet = new EventEmitter<CodeSet>();
@ViewChild(MatSort, { static: true }) sort: MatSort;
@ViewChild(MdmPaginatorComponent, { static: true }) paginator: MdmPaginatorComponent;
displayedColumns: string[] = ['label', 'author'];
codesets: MdmTableDataSource<CodeSet> = new MdmTableDataSource();
isLoadingResults = false;
reloadEvent = new EventEmitter<string>();
totalItemCount = 0;
constructor(private resources: MdmResourcesService) {}
ngOnChanges(changes: SimpleChanges): void {
if (!this.term) {
return;
}
if (changes.term) {
// Update action functions when term changed
this.codesets.fetchFunction = options => {
return this.resources.terms.codesetsForTerm(this.term.model, this.term.id, options);
};
this.codesets.fetchData();
}
}
ngOnInit() {
// Keep track of item count
this.codesets.count.subscribe(c => {
this.totalItemCount = c;
this.totalCount.emit(this.totalItemCount);
});
}
ngAfterViewInit() {
// Reset pageIndex on reload
this.reloadEvent.subscribe(() => this.paginator.pageIndex = 0);
// Reset pageIndex on re-order
this.sort?.sortChange.subscribe(() => this.paginator.pageIndex = 0);
// Update table data source on sorting, paging, or reload events
merge(this.sort?.sortChange, this.paginator?.page, this.reloadEvent).subscribe(() => {
this.refreshFetchOptions();
this.codesets.fetchData();
});
// Initial paging and sorting configuration
this.refreshFetchOptions();
// First data fetch
this.codesets.fetchData();
}
refreshFetchOptions() {
this.codesets.pageable = {
max: this.paginator?.pageSize || this.pageSize,
offset: (this.paginator?.pageOffset) || 0
};
this.codesets.sortable = {
sort: this.sort?.active,
order: this.sort?.direction
};
}
}
|
MauroDataMapper/mdm-ui
|
src/app/modules/admin/admin.module.ts
|
<filename>src/app/modules/admin/admin.module.ts
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AdminAppContainerComponent } from '@mdm/admin/app-container/app-container.component';
import { AdminRoutesModule } from '../admin-routes/admin-routes.module';
import { SharedModule } from '../shared/shared.module';
import { EmailsComponent } from '@mdm/admin/emails/emails.component';
import { GroupMemberTableComponent } from '@mdm/admin/group-member-table/group-member-table.component';
import { UserComponent } from '@mdm/admin/user/user.component';
import { ProfilesDashboardComponent } from '@mdm/profiles-dashboard/profiles-dashboard.component';
import { OpenidConnectProviderTableComponent } from '@mdm/admin/openid-connect-provider-table/openid-connect-provider-table.component';
import { OpenidConnectProviderComponent } from '@mdm/admin/openid-connect-provider/openid-connect-provider.component';
import { DoiRedirectComponent } from '@mdm/doi-redirect/doi-redirect.component';
@NgModule({
declarations: [
AdminAppContainerComponent,
EmailsComponent,
GroupMemberTableComponent,
UserComponent,
ProfilesDashboardComponent,
OpenidConnectProviderTableComponent,
OpenidConnectProviderComponent,
DoiRedirectComponent
],
imports: [CommonModule, AdminRoutesModule, SharedModule],
exports: [
AdminAppContainerComponent,
EmailsComponent,
GroupMemberTableComponent,
UserComponent,
ProfilesDashboardComponent
]
})
export class AdminModule {}
|
MauroDataMapper/mdm-ui
|
src/app/subscribed-catalogues/newer-versions/newer-versions.component.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { AfterViewInit, Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { MatSort } from '@angular/material/sort';
import { QueryParameters, Uuid } from '@maurodatamapper/mdm-resources';
import { FederatedDataModel } from '@mdm/model/federated-data-model';
import { MdmResourcesService } from '@mdm/modules/resources';
import { GridService, StateHandlerService } from '@mdm/services';
import { MdmPaginatorComponent } from '@mdm/shared/mdm-paginator/mdm-paginator';
import { merge } from 'rxjs';
import { catchError, map, startWith, switchMap } from 'rxjs/operators';
@Component({
selector: 'mdm-newer-versions',
templateUrl: './newer-versions.component.html',
styleUrls: ['./newer-versions.component.scss']
})
export class NewerVersionsComponent implements AfterViewInit {
@ViewChild(MdmPaginatorComponent, { static: false }) paginator: MdmPaginatorComponent;
@ViewChild(MatSort, { static: false }) sort: MatSort;
@Input('catalogueItem') catalogueItem: FederatedDataModel;
@Input() catalogueId: Uuid;
@Output() hasErrored = new EventEmitter<void>();
displayedColumns = ['label', 'version', 'navigate'];
isLoadingResults: boolean;
hasFailed = false;
totalNewVersionCount: number;
newVersionsRecords: any;
constructor(
private resouces: MdmResourcesService,
private gridService: GridService,
private stateHandler: StateHandlerService) { }
ngAfterViewInit(): void {
merge(this.sort.sortChange, this.paginator.page)
.pipe(
startWith({}),
switchMap(() => {
this.isLoadingResults = true;
return this.fetchNewerVersions(this.paginator.pageSize, this.paginator.pageOffset, this.sort.active, this.sort.direction);
}),
map((data: any) => {
this.totalNewVersionCount = data.body.newerPublishedModels.length;
this.isLoadingResults = false;
return data.body.newerPublishedModels;
}),
catchError(() => {
this.isLoadingResults = false;
this.hasFailed = true;
this.hasErrored.emit();
return [];
})
)
.subscribe(data => {
this.newVersionsRecords = data;
});
}
fetchNewerVersions(pageSize?: number, pageIndex?: number, sortBy?: string, sortType?: string) {
// Future proofing to enable paging if number of versions increases
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const options: QueryParameters = this.gridService.constructOptions(pageSize, pageIndex, sortBy, sortType);
return this.resouces.subscribedCatalogues
.newerVersions(
this.catalogueId,
this.catalogueItem.modelId,
{},
{ handleGetErrors: false });
}
navigateToNewerVersion(record: FederatedDataModel) {
this.stateHandler.Go('appContainer.mainApp.twoSidePanel.catalogue.federatedDataModel', { parentId: this.catalogueId, id: record.modelId });
}
}
|
MauroDataMapper/mdm-ui
|
src/app/shared/model-icon/model-icon.component.ts
|
<gh_stars>1-10
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, Input, OnInit } from '@angular/core';
import { ModelDomainType } from '@maurodatamapper/mdm-resources';
@Component({
selector: 'mdm-model-icon',
templateUrl: './model-icon.component.html',
styleUrls: ['./model-icon.component.scss']
})
export class ModelIconComponent implements OnInit {
@Input() domainType: ModelDomainType;
@Input() isDataAsset: boolean;
style: string;
constructor() {}
ngOnInit(): void {
switch (this.domainType) {
case ModelDomainType.DataModels:
if (this.isDataAsset) {
this.style = 'fa-database';
} else {
this.style = 'fa-file-alt';
}
break;
case ModelDomainType.ReferenceDataModels:
this.style = 'fa-file-alt';
break;
case ModelDomainType.Folders:
this.style = 'fa-folder';
break;
case ModelDomainType.Terminologies:
this.style = 'fa-book';
break;
default:
this.style = 'fa-folder';
break;
}
}
}
|
MauroDataMapper/mdm-ui
|
src/app/wizards/dataClass/data-class-step2/data-class-step2.component.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import {
Component,
OnInit,
ViewChild,
ViewChildren,
ElementRef,
EventEmitter,
AfterViewInit,
OnDestroy,
QueryList
} from '@angular/core';
import { ValidatorService } from '@mdm/services/validator.service';
import { NgForm } from '@angular/forms';
import { Subscription } from 'rxjs';
import { MessageHandlerService } from '@mdm/services/utility/message-handler.service';
import { MdmResourcesService } from '@mdm/modules/resources';
import { MatSort } from '@angular/material/sort';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { CreateType } from '@mdm/wizards/wizards.model';
@Component({
selector: 'mdm-data-class-step2',
templateUrl: './data-class-step2.component.html',
styleUrls: ['./data-class-step2.component.sass']
})
export class DataClassStep2Component
implements OnInit, AfterViewInit, OnDestroy {
@ViewChild('myForm', { static: false }) myForm: NgForm;
@ViewChildren('filters', { read: ElementRef }) filters: ElementRef[];
@ViewChildren(MatPaginator) paginator = new QueryList<MatPaginator>();
@ViewChildren(MatSort) sort = new QueryList<MatSort>();
step: any;
model: {
[key: string]: any;
createType: CreateType;
};
scope: any;
multiplicityError: any;
selectedDataClassesStr = '';
defaultCheckedMap: any;
loaded = false;
totalItemCount = 0;
totalSelectedItemsCount = 0;
processing: any;
isProcessComplete: any;
finalResult = {};
successCount = 0;
failCount = 0;
pageSize = 20;
pageSizeOptions = [5, 10, 20, 50];
copyMessage = '';
formChangesSubscription: Subscription;
filterEvent = new EventEmitter<string>();
filter: string;
hideFilters = true;
displayedColumns = ['name', 'description', 'status'];
dataSource = new MatTableDataSource<any>();
constructor(
private validator: ValidatorService,
private resources: MdmResourcesService,
private messageHandler: MessageHandlerService
) {
const settings = JSON.parse(localStorage.getItem('userSettings'));
if (settings) {
this.pageSize = settings.countPerTable;
this.pageSizeOptions = settings.counts;
}
}
ngOnInit() {
this.model = this.step.scope.model;
this.scope = this.step.scope;
this.dataSource = new MatTableDataSource<any>(
this.model.selectedDataClasses
);
}
ngAfterViewInit() {}
onLoad() {
this.defaultCheckedMap = this.model.selectedDataClassesMap;
if (
this.sort !== null &&
this.sort !== undefined &&
this.sort.toArray().length > 0 &&
this.paginator !== null &&
this.paginator !== undefined &&
this.paginator.toArray().length > 0
) {
this.sort
.toArray()[0]
.sortChange.subscribe(
() => (this.paginator.toArray()[0].pageIndex = 0)
);
this.filterEvent.subscribe(
() => (this.paginator.toArray()[0].pageIndex = 0)
);
// Selected Data Class table
this.dataSource.sort = this.sort.toArray()[0];
this.sort
.toArray()[0]
.sortChange.subscribe(
() => (this.paginator.toArray()[0].pageIndex = 0)
);
this.dataSource.paginator = this.paginator.toArray()[0];
}
if (this.model.selectedDataClassesMap) {
this.createSelectedArray();
this.validate();
}
if (this.myForm) {
this.formChangesSubscription = this.myForm.form.valueChanges.subscribe(
(x) => {
this.validate(x);
}
);
}
this.loaded = true;
this.failCount = 0;
this.successCount = 0;
this.step.submitBtnDisabled = false;
}
createSelectedArray = () => {
this.model.selectedDataClasses = [];
for (const id in this.model.selectedDataClassesMap) {
if (this.model.selectedDataClassesMap.hasOwnProperty(id)) {
const element = this.model.selectedDataClassesMap[id];
this.model.selectedDataClasses.push(element.node);
}
}
this.totalItemCount = this.model.selectedDataClasses.length;
};
onCheck = (node, parent, checkedMap) => {
this.model.selectedDataClassesMap = checkedMap;
this.createSelectedArray();
this.dataSource.data = this.model.selectedDataClasses;
// eslint-disable-next-line no-underscore-dangle
this.dataSource._updateChangeSubscription();
this.validate();
this.totalSelectedItemsCount = this.model.selectedDataClasses.length;
this.step.submitBtnDisabled = false;
};
validate = (newValue?) => {
let invalid = false;
if (this.model.createType === 'new') {
if (newValue) {
// check Min/Max
this.multiplicityError = this.validator.validateMultiplicities(
newValue.minMultiplicity,
newValue.maxMultiplicity
);
// Check Mandatory fields
if (
!newValue.label ||
newValue.label.trim().length === 0 ||
this.multiplicityError
) {
this.step.invalid = true;
return;
}
}
invalid = this.myForm.invalid;
}
if (['copy', 'import', 'extend'].includes(this.model.createType)) {
switch (this.model.createType) {
case 'copy': this.copyMessage = 'copy'; break;
case 'import': this.copyMessage = 'import'; break;
case 'extend': this.copyMessage = 'extend with'; break;
default: this.copyMessage = '';
}
if (this.model.selectedDataClasses.length === 0) {
this.step.invalid = true;
return;
}
}
this.step.invalid = invalid;
};
ngOnDestroy() {
if (this.formChangesSubscription) {
this.formChangesSubscription.unsubscribe();
}
}
saveCopiedDataClasses = () => {
this.step.submitBtnDisabled = true;
this.processing = true;
this.isProcessComplete = false;
this.failCount = 0;
this.successCount = 0;
let promise = Promise.resolve();
this.model.selectedDataClasses.forEach((dc: any) => {
promise = promise
.then((result: any) => {
this.successCount++;
this.finalResult[dc.id] = { result, hasError: false };
if (this.model.parent.domainType === 'DataClass') {
switch (this.model.createType) {
case 'copy': return this.resources.dataClass.copyChildDataClass(this.model.parent.model, this.model.parent.id, dc.modelId, dc.id, null).toPromise();
case 'import': return this.resources.dataClass.importDataClass(this.model.parent.model, this.model.parent.id, dc.modelId, dc.id, null).toPromise();
case 'extend': return this.resources.dataClass.addExtendDataClass(this.model.parent.model, this.model.parent.id, dc.modelId, dc.id, null).toPromise();
}
} if (this.model.parent.domainType === 'DataModel') {
switch (this.model.createType) {
case 'copy': return this.resources.dataClass.copyDataClass(this.model.parent.id, dc.modelId, dc.id, null).toPromise();
case 'import': return this.resources.dataModel.importDataClass(this.model.parent.id, dc.modelId, dc.id, null).toPromise();
}
} else {
return this.resources.dataClass.copyDataClass(this.model.parent.id, dc.modelId, dc.id, null).toPromise();
}
})
.catch((error) => {
this.failCount++;
const errorText = this.messageHandler.getErrorText(error);
this.finalResult[dc.id] = { result: errorText, hasError: true };
});
});
promise
.then(() => {})
.catch(() => console.warn('error'))
.finally(() => {
this.processing = false;
this.step.submitBtnDisabled = false;
this.isProcessComplete = true;
});
return promise;
};
}
|
MauroDataMapper/mdm-ui
|
src/app/modals/login-modal/login-modal.component.ts
|
<reponame>MauroDataMapper/mdm-ui
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, OnInit } from '@angular/core';
import { SecurityHandlerService } from '@mdm/services/handlers/security-handler.service';
import { MatDialogRef } from '@angular/material/dialog';
import { BroadcastService } from '@mdm/services/broadcast.service';
import { MessageService } from '@mdm/services/message.service';
import { ValidatorService } from '@mdm/services/validator.service';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { catchError, finalize } from 'rxjs/operators';
import { SignInError, SignInErrorType } from '@mdm/services/handlers/security-handler.model';
import { EMPTY } from 'rxjs';
import { MdmHttpHandlerOptions, MdmResourcesService } from '@mdm/modules/resources';
import { PublicOpenIdConnectProvider, PublicOpenIdConnectProvidersIndexResponse } from '@maurodatamapper/mdm-resources';
import { MessageHandlerService, SharedService } from '@mdm/services';
@Component({
selector: 'mdm-login-modal',
templateUrl: './login-modal.component.html',
styleUrls: ['./login-modal.component.scss'],
})
export class LoginModalComponent implements OnInit {
message = '';
authenticating = false;
signInForm!: FormGroup;
openIdConnectProviders?: PublicOpenIdConnectProvider[];
constructor(
private broadcast: BroadcastService,
public dialogRef: MatDialogRef<LoginModalComponent>,
private securityHandler: SecurityHandlerService,
private messageService: MessageService,
private validator: ValidatorService,
private resources: MdmResourcesService,
private shared: SharedService,
private messageHandler: MessageHandlerService) { }
get userName() {
return this.signInForm.get('userName');
}
get password() {
return this.signInForm.get('password');
}
ngOnInit() {
this.signInForm = new FormGroup({
userName: new FormControl('', [
Validators.required, // eslint-disable-line @typescript-eslint/unbound-method
Validators.pattern(this.validator.emailPattern)
]),
password: new FormControl('', [
Validators.required // eslint-disable-line @typescript-eslint/unbound-method
])
});
if (this.shared.features.useOpenIdConnect) {
// If unable to get OpenID Connect providers, silently fail and ignore
const requestOptions: MdmHttpHandlerOptions = {
handleGetErrors: false
};
this.resources.pluginOpenIdConnect
.listPublic({}, requestOptions)
.pipe(
catchError(() => EMPTY)
)
.subscribe((response: PublicOpenIdConnectProvidersIndexResponse) => {
this.openIdConnectProviders = response.body;
});
}
}
login() {
this.message = '';
if (this.signInForm.invalid) {
return;
}
this.authenticating = true;
this.signInForm.disable();
this.securityHandler
.signIn({
username: this.userName?.value,
password: this.password?.value
})
.pipe(
catchError((error: SignInError) => {
switch (error.type) {
case SignInErrorType.InvalidCredentials:
this.message = 'Invalid username or password!';
break;
case SignInErrorType.AlreadySignedIn:
this.message = 'A user is already signed in, please sign out first.';
break;
default:
this.message = 'Unable to sign in. Please try again later.';
break;
}
return EMPTY;
}),
finalize(() => {
this.authenticating = false;
this.signInForm.enable();
})
)
.subscribe(user => {
this.dialogRef.close(user);
this.securityHandler.loginModalDisplayed = false;
this.messageService.loggedInChanged(true);
});
}
forgotPassword() {
this.dialogRef.close();
this.broadcast.dispatch('openForgotPasswordModalDialog');
}
signUp() {
this.dialogRef.close();
this.broadcast.dispatch('openRegisterModalDialog');
}
close() {
this.securityHandler.loginModalDisplayed = false;
this.dialogRef.close();
}
authenticateWithOpenIdConnect(provider: PublicOpenIdConnectProvider) {
if (!provider.authorizationEndpoint) {
this.messageHandler.showError(`Unable to authenticate with ${provider.label} because of a missing endpoint. Please contact your administrator for further support.`);
return;
}
this.securityHandler.authenticateWithOpenIdConnect(provider);
}
}
|
MauroDataMapper/mdm-ui
|
src/app/modals/resolve-merge-conflict-modal/resolve-merge-conflict-modal.component.ts
|
<filename>src/app/modals/resolve-merge-conflict-modal/resolve-merge-conflict-modal.component.ts
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, Inject, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { diff_match_patch } from 'diff-match-patch';
@Component({
selector: 'mdm-resolve-merge-conflict-modal',
templateUrl: './resolve-merge-conflict-modal.component.html',
styleUrls: ['./resolve-merge-conflict-modal.component.scss']
})
export class ResolveMergeConflictModalComponent implements AfterViewInit {
mergeString:any;
mergeDiffrl: any;
mergeDifflr: any;
private mergeViewrl : ElementRef;
private mergeViewlr : ElementRef;
constructor(
private dialogRef: MatDialogRef<ResolveMergeConflictModalComponent>,
@Inject(MAT_DIALOG_DATA) public data: any,
) { }
@ViewChild('mergeDiffrl', {static:false}) set mergeDiffConRl(content: ElementRef) {
this.mergeViewrl = content;
}
@ViewChild('mergeDifflr', {static:false}) set mergeDiffConLR(content: ElementRef) {
this.mergeViewlr = content;
}
ngAfterViewInit(): void {
if (this.data.diffs) {
const diffs = this.data.diffs;
const diffrl = this.diffLineMode(diffs.right, diffs.left);
const difflr = this.diffLineMode(diffs.left, diffs.right);
this.mergeViewrl.nativeElement.innerHTML = this.diffPrettyPlain(diffrl);
this.mergeViewlr.nativeElement.innerHTML = this.diffPrettyPlain(difflr);
this.mergeViewrl.nativeElement.querySelectorAll('button').forEach(x => x.addEventListener('click', this.onMergeConflictPress.bind(this)));
this.mergeViewlr.nativeElement.querySelectorAll('button').forEach(x => x.addEventListener('click', this.onMergeConflictPress.bind(this)));
this.mergeString = this.diffIntoPrettyPlain(diffrl);
}
}
accept() {
this.data.mergeString = this.mergeString;
this.dialogRef.close({ status: 'ok' , data : this.data });
}
onMergeConflictPress(thing:any)
{
const item = thing.currentTarget;
const obj = JSON.parse(item.attributes.test.value);
const id = obj.id;
const value = decodeURI(obj.value);
document.querySelector(`span#loc${id}`).innerHTML = '';
const regex = new RegExp(`<span id="loc${id}">`, 'g');
this.mergeString = this.mergeString.replace(regex,`<span id="loc${id}">${value}`);
}
diffPrettyPlain = (diffs:any) =>
{
const diffDelete = -1;
const diffEqual = 0;
const html = [];
for (let x = 0; x < diffs.length; x++) {
const op = diffs[x][0]; // Operation (insert, delete, equal)
const data = diffs[x][1]; // Text of change.
const text = data;
switch (op) {
case diffDelete:{
const encodedText = encodeURI(text);
const obj = {id: x, loc:'left', value:encodedText};
html[x] = `<button id="${x}" test=${JSON.stringify(obj)} class="diffAdded"><ins>${text}</ins></button>`;
break;
}
case diffEqual:{
html[x] = `<span>${text}</span>`;
break;
}
}
}
return html.join('');
};
diffIntoPrettyPlain = (diffs:any) =>
{
const diffDelete = -1;
const diffEqual = 0;
const diffAdded = 1;
const html = [];
for (let x = 0; x < diffs.length; x++) {
const op = diffs[x][0]; // Operation (insert, delete, equal)
const data = diffs[x][1]; // Text of change.
const text = data;
switch (op) {
case diffDelete:
html[x] = `<span id="loc${x}"></span>`;
break;
case diffAdded:
html[x] = `<span id="loc${x}"></span>`;
break;
case diffEqual:
html[x] = `<span>${text}</span>`;
break;
}
}
return html.join('');
};
diffLineMode(text1, text2) {
const dmp = new diff_match_patch();
const a = this.diffLinesToChars(text1, text2);
const lineText1 = a.chars1;
const lineText2 = a.chars2;
const lineArray = a.lineArray;
const diffs = dmp.diff_main(lineText1, lineText2, false);
dmp.diff_charsToLines_(diffs, lineArray);
return diffs;
}
diffLinesToChars = (text1, text2) => {
const lineArray = []; // e.g. lineArray[4] == 'Hello\n'
const lineHash = {}; // e.g. lineHash['Hello\n'] == 4
// '\x00' is a valid character, but various debuggers don't like it.
// So we'll insert a junk entry to avoid generating a null character.
lineArray[0] = '';
/**
* Split a text into an array of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one line.
* Modifies linearray and linehash through being a closure.
*
* @param {string} text String to encode.
* @return {string} Encoded string.
* @private
*/
// Allocate 2/3rds of the space for text1, the rest for text2.
let maxLines = 40000;
const chars1 = this.diffLinesToCharsMunge(text1, lineArray, lineHash, maxLines);
maxLines = 65535;
const chars2 = this.diffLinesToCharsMunge(text2, lineArray, lineHash, maxLines);
return {chars1, chars2, lineArray};
};
diffLinesToCharsMunge = (text, lineArray, lineHash, maxLines) => {
let chars = '';
// Walk the text, pulling out a substring for each line.
// text.split('\n') would would temporarily double our memory footprint.
// Modifying text would create many large strings to garbage collect.
let lineStart = 0;
let lineEnd = -1;
// Keeping our own length variable is faster than looking it up.
let lineArrayLength = lineArray.length;
while (lineEnd < text.length - 1) {
lineEnd = text.indexOf(' ', lineStart);
if (lineEnd === -1) {
lineEnd = text.length - 1;
}
let line = text.substring(lineStart, lineEnd + 1);
if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) :
(lineHash[line] !== undefined)) {
chars += String.fromCharCode(lineHash[line]);
} else {
if (lineArrayLength === maxLines) {
// Bail out at 65535 because
// String.fromCharCode(65536) == String.fromCharCode(0)
line = text.substring(lineStart);
lineEnd = text.length;
}
chars += String.fromCharCode(lineArrayLength);
lineHash[line] = lineArrayLength;
lineArray[lineArrayLength++] = line;
}
lineStart = lineEnd + 1;
}
return chars;
};
}
|
MauroDataMapper/mdm-ui
|
src/app/errors/error.component.ts
|
<filename>src/app/errors/error.component.ts
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, OnInit } from '@angular/core';
import { MessageService } from '../services/message.service';
import { ClipboardService } from 'ngx-clipboard';
import { YoutrackService } from '../services/youtrack.service';
import { SharedService } from '../services/shared.service';
const columns: string[] = ['field', 'value'];
@Component({
selector: 'mdm-error',
templateUrl: './error.component.html',
styleUrls: ['./error.component.scss']
})
export class ErrorComponent implements OnInit {
showYouTrackLink = true;
showDetails = false;
lastError: any;
dataSource: object[] = [];
displayedColumns: string[] = columns;
codeHighlighted = false;
issueReported = false;
issueReporting = false;
isLoggedIn = false;
summary: string;
errorInSubmit = false;
username: string;
errorHeader: string;
errorMessage: string;
errorResolution: string;
errorReportMessage: string;
constructor(
protected messageService: MessageService,
protected clipboardService: ClipboardService,
protected sharedService: SharedService,
protected youtrackService: YoutrackService
) {
this.lastError = messageService.lastError;
this.isLoggedIn = sharedService.isLoggedIn();
this.summary = `Error ${this.lastError.error?.status} : ${this.lastError.error?.message}`;
}
ngOnInit() {}
copyToClipboard() {
this.clipboardService.copyFromContent(
JSON.stringify(this.lastError, null, 2)
);
}
changeShowDetails() {
this.showDetails = !this.showDetails;
}
reportIssueToYouTrack() {
// make sure youTrack is configured
if (!this.showYouTrackLink) {
return;
}
this.issueReporting = true;
const summary : string = this.lastError.error.message;
const description = JSON.stringify(this.lastError, null, 2);
this.youtrackService.reportIssue(summary, description).subscribe(() => {
this.successfulReport();
}, () => {
this.errorReport();
}
);
}
successfulReport() {
this.issueReporting = false;
this.issueReported = true;
}
errorReport() {
this.issueReporting = false;
this.errorInSubmit = true;
}
}
|
MauroDataMapper/mdm-ui
|
src/app/constraints-rules/constraints-rules.component.ts
|
<reponame>MauroDataMapper/mdm-ui
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
export class BaseDataGrid {
displayedColumns: string[];
records: Array<any>;
totalItemCount: number;
}
export class RuleRepresentation {
id: string;
rule: RuleModel;
language: string;
representation: any;
}
export class RuleModel {
ruleRepresentations: Array<RuleRepresentation>;
name: string;
description: string;
id: string;
constructor(rule: Array<RuleRepresentation>, name: any, description: any) {
this.ruleRepresentations = rule;
this.name = name;
this.description = description;
}
}
export class RuleLanguage {
displayName: any;
value: any;
}
import {
trigger,
state,
style,
transition,
animate
} from '@angular/animations';
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { AddRuleModalComponent } from '@mdm/modals/add-rule-modal/add-rule-modal.component';
import {
AddRuleRepresentationModalComponent,
RuleLanguages
} from '@mdm/modals/add-rule-representation-modal/add-rule-representation-modal.component';
import { ConfirmationModalComponent } from '@mdm/modals/confirmation-modal/confirmation-modal.component';
import { MdmResourcesService } from '@mdm/modules/resources';
import { MessageHandlerService } from '@mdm/services';
import JSZip from 'jszip';
import FileSaver from 'file-saver';
import { Finalisable, Modelable } from '@maurodatamapper/mdm-resources';
@Component({
selector: 'mdm-constraints-rules',
templateUrl: './constraints-rules.component.html',
styleUrls: ['./constraints-rules.component.scss'],
animations: [
trigger('detailExpand', [
state(
'collapsed',
style({ height: '0px', minHeight: '0', display: 'none' })
),
state('expanded', style({ height: '*' })),
transition(
'expanded <=> collapsed',
animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)')
)
])
]
})
export class ConstraintsRulesComponent extends BaseDataGrid implements OnInit {
@Input() parent: Modelable & Finalisable;
@Input() domainType: string;
@Output() totalCount = new EventEmitter<string>();
isLoadingResults: boolean;
expandedElement: any;
languages: Array<RuleLanguage>;
selectedLanguage: RuleLanguage;
clickButton = false;
filteredOpen = false;
canAddRules: boolean;
canDeleteRules: boolean;
fileExtensions = {
'c#': 'cs',
dmn: 'dmn',
java: 'java',
javascript: 'js',
typescript: 'ts',
text: 'txt',
drools: 'drools',
sql: 'sql'
};
constructor(
public dialog: MatDialog,
protected resourcesService: MdmResourcesService,
protected messageHandler: MessageHandlerService
) {
super();
this.languages = Object.assign([], RuleLanguages.supportedLanguages);
this.languages.sort((a:any,b:any) => {return a - b;});
this.languages.push({ displayName: 'All', value: 'all' });
this.isLoadingResults = true;
this.displayedColumns = ['name', 'description', 'rule', 'actions'];
this.selectedLanguage = this.languages.find((x) => x.value === 'all');
}
ngOnInit(): void {
this.loadRules();
this.canAddRules = !this.parent.finalised;
this.canDeleteRules = !this.parent.finalised;
}
expandRow = (record: RuleModel) => {
if (this.expandedElement === record) {
this.expandedElement = null;
} else {
this.expandedElement = record;
this.resourcesService.catalogueItem
.listRuleRepresentations(this.domainType, this.parent.id, record.id)
.subscribe((result) => {
const tempList: Array<RuleRepresentation> = [];
result.body.items.forEach((element : RuleRepresentation) => {
element['rule'] = record;
if (
this.selectedLanguage.value === 'all' ||
this.selectedLanguage.value === element.language
) {
tempList.push(element);
}
});
record.ruleRepresentations = tempList;
});
}
};
add = () => {
this.clickButton = true;
const dialog = this.dialog.open(AddRuleModalComponent, {
data: {
name: '',
description: '',
modalTitle: 'Add New Rule',
okBtn: 'Add',
btnType: 'primary'
},
height: '1000px',
width: '1000px'
});
dialog.afterClosed().subscribe((dialogResult) => {
this.clickButton = false;
if (dialogResult) {
const data = {
name: dialogResult.name,
description: dialogResult.description
};
this.resourcesService.catalogueItem
.saveRule(this.domainType, this.parent.id, data)
.subscribe(
(result) => {
const temp = Object.assign([], this.records);
temp.push(result.body);
this.records = temp;
this.totalItemCount = this.records.length;
this.totalCount.emit(String(this.totalItemCount));
},
(error) => {
this.messageHandler.showError(error);
}
);
} else {
return;
}
});
};
loadRules() {
this.resourcesService.catalogueItem
.listRules(this.domainType, this.parent.id)
.subscribe(
(result) => {
this.records = result.body.items;
this.totalItemCount = result.body.count;
this.totalCount.emit(String(result.body.count));
this.isLoadingResults = false;
},
(error) => {
this.messageHandler.showError(error);
this.isLoadingResults = false;
}
);
}
openEdit(record: RuleModel): void {
if (record) {
const dialog = this.dialog.open(AddRuleModalComponent, {
data: {
name: record.name,
description: record.description,
modalTitle: 'Edit Rule',
okBtn: 'Apply',
btnType: 'primary'
},
height: '1000px',
width: '1000px'
});
dialog.afterClosed().subscribe((dialogResult) => {
if (dialogResult) {
const data = {
name: dialogResult.name,
description: dialogResult.description
};
this.resourcesService.catalogueItem
.updateRule(this.domainType, this.parent.id, record.id, data)
.subscribe(
() => {
this.messageHandler.showSuccess('Successfully Updated');
this.loadRules();
},
(error) => {
this.messageHandler.showError(error);
}
);
} else {
return;
}
});
}
}
openEditRepresentation(rep: RuleRepresentation) {
const dialog = this.dialog.open(AddRuleRepresentationModalComponent, {
data: {
language: rep.language,
representation: rep.representation,
modalTitle: 'Edit Rule Representation',
okBtn: 'Apply',
btnType: 'primary'
},
height: '1000px',
width: '1000px'
});
dialog.afterClosed().subscribe((dialogResult) => {
if (dialogResult) {
const data = {
language: dialogResult.language,
representation: dialogResult.representation
};
this.resourcesService.catalogueItem
.updateRulesRepresentation(
this.domainType,
this.parent.id,
data,
rep.rule.id,
rep.id
)
.subscribe(
() => {
this.messageHandler.showSuccess('Successfully Updated');
this.expandRow(rep.rule);
},
(error) => {
this.messageHandler.showError(error);
}
);
} else {
return;
}
});
}
deleteRule = (record: RuleModel): void => {
const dialog = this.dialog.open(ConfirmationModalComponent, {
data: {
title: 'Delete permanently',
okBtnTitle: 'Yes, delete',
btnType: 'warn',
message: 'Are you sure you wish delete?'
}
});
dialog.afterClosed().subscribe((result) => {
if (result?.status !== 'ok') {
return;
}
this.resourcesService.catalogueItem
.removeRule(this.domainType, this.parent.id, record.id)
.subscribe(
() => {
this.messageHandler.showSuccess('Successfully Deleted');
this.loadRules();
},
(error) => {
this.messageHandler.showError(error.message);
}
);
});
};
addRepresentation(rule: RuleModel): void {
const dialog = this.dialog.open(AddRuleRepresentationModalComponent, {
data: {
language: '',
representation: '',
modalTitle: 'Add Representation',
okBtn: 'Add',
btnType: 'primary'
},
height: '1000px',
width: '1000px'
});
dialog.afterClosed().subscribe((dialogResult) => {
if (dialogResult) {
const data = {
language: dialogResult.language,
representation: dialogResult.representation
};
this.resourcesService.catalogueItem
.saveRulesRepresentation(
this.domainType,
this.parent.id,
data,
rule.id
)
.subscribe(
() => {
this.messageHandler.showSuccess('Rule Added Successfully');
this.expandRow(rule);
},
(error) => {
this.messageHandler.showError(error);
}
);
} else {
return;
}
});
}
deleteRepresentation(record: RuleRepresentation) {
const dialog = this.dialog.open(ConfirmationModalComponent, {
data: {
title: 'Delete permanently',
okBtnTitle: 'Yes, delete',
btnType: 'warn',
message: 'Are you sure you wish delete?'
}
});
dialog.afterClosed().subscribe((result) => {
if (result?.status !== 'ok') {
return;
}
this.resourcesService.catalogueItem
.removeRulesRepresentation(
this.domainType,
this.parent.id,
record.rule.id,
record.id
)
.subscribe(
() => {
this.messageHandler.showSuccess('Successfully Deleted');
this.expandRow(record.rule);
},
(error) => {
this.messageHandler.showError(error.message);
}
);
});
}
filterClick = () => {
this.filteredOpen = !this.filteredOpen;
};
exportRuleRepresentation = (ruleRep: RuleRepresentation) => {
try {
const myFilename = `${ruleRep.rule.name}.${
this.fileExtensions[ruleRep.language]
}`;
const content = new Blob([ruleRep.representation as BlobPart]);
FileSaver.saveAs(content, myFilename);
} catch (error) {
this.messageHandler.showError('Error Exporting', error);
}
};
exportRule = (rule: any) => {
const zip = new JSZip();
let count = 0;
const zipFilename = `${rule.name}.zip`;
try {
rule.ruleRepresentations.forEach((ruleRep : RuleRepresentation) => {
if (
this.selectedLanguage.value === ruleRep.language ||
this.selectedLanguage.value === 'all'
) {
let myFilename = `${rule.name}`;
let fileCount = 1;
while (
zip.files[`${myFilename}.${this.fileExtensions[ruleRep.language]}`]
) {
myFilename = `${myFilename}(${fileCount})`;
fileCount++;
}
zip.file(
`${myFilename}.${this.fileExtensions[ruleRep.language]}`,
ruleRep.representation
);
count++;
if (count === rule.ruleRepresentations.length) {
zip.generateAsync({ type: 'blob' }).then((content) => {
FileSaver.saveAs(content, zipFilename);
this.messageHandler.showSuccess(`${rule.name} Exported`);
});
}
}
});
} catch (error) {
this.messageHandler.showError('Error Exporting', error);
}
};
exportAllRules = () => {
this.clickButton = true;
const zip = new JSZip();
let count = 0;
const zipFilename = `${this.parent.label} Rules.zip`;
try {
this.records.forEach((rule) => {
if (rule.ruleRepresentations) {
rule.ruleRepresentations.forEach((ruleRep) => {
if (
this.selectedLanguage.value === ruleRep.language ||
this.selectedLanguage.value === 'all'
) {
let myFilename = `${rule.name}`;
let fileCount = 1;
while (
zip.files[
`${rule.name}/${myFilename}.${
this.fileExtensions[ruleRep.language]
}`
]
) {
myFilename = `${myFilename}(${fileCount})`;
fileCount++;
}
zip
.folder(`${rule.name}`)
.file(
`${myFilename}.${this.fileExtensions[ruleRep.language]}`,
ruleRep.representation
);
}
});
}
count++;
if (count === this.records.length) {
zip.generateAsync({ type: 'blob' }).then((content) => {
FileSaver.saveAs(content, zipFilename);
this.clickButton = false;
this.messageHandler.showSuccess('All Rules Exported');
});
}
});
} catch (error) {
this.messageHandler.showError('Error Exporting', error);
}
};
selectedLanguageChange = () => {
if (this.selectedLanguage.value === 'all') {
this.loadRules();
return;
}
const data = {
language: this.selectedLanguage.value
};
this.resourcesService.catalogueItem
.listRules(this.domainType, this.parent.id, data)
.subscribe(
(result) => {
this.records = result.body.items;
this.totalItemCount = result.body.count;
this.isLoadingResults = false;
},
(error) => {
this.messageHandler.showError(error);
this.isLoadingResults = false;
}
);
};
}
|
MauroDataMapper/mdm-ui
|
src/app/merge-diff/merge-comparsion/merge-comparsion.component.ts
|
<filename>src/app/merge-diff/merge-comparsion/merge-comparsion.component.ts
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import {
Branchable,
MergeDiffItem,
MergeDiffType,
MergeConflictResolution
} from '@maurodatamapper/mdm-resources';
import {
Component,
Input,
OnInit,
Output,
EventEmitter,
ElementRef,
ViewChild,
OnChanges,
SimpleChanges,
ViewEncapsulation
} from '@angular/core';
import { MergeDiffItemModel, MergeItemValueType } from '../types/merge-item-type';
import { MatDialog } from '@angular/material/dialog';
import { ModalDialogStatus } from '@mdm/constants/modal-dialog-status';
import { filter } from 'rxjs/operators';
import { ConflictEditorModalComponent } from '../conflict-editor/conflict-editor-modal/conflict-editor-modal.component';
import {
ConflictEditorModalData,
ConflictEditorModalResult
} from '../conflict-editor/conflict-editor-modal/conflict-editor-modal.model';
import { StringConflictService } from '../services/string-conflict.service';
@Component({
selector: 'mdm-merge-comparison',
templateUrl: './merge-comparison.component.html',
styleUrls: ['./merge-comparison.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class MergeComparisonComponent implements OnInit, OnChanges {
@ViewChild('sourceContent') sourceContent: ElementRef;
@ViewChild('targetContent') targetContent: ElementRef;
@Input() source: Branchable;
@Input() target: Branchable;
@Input() mergeItem: MergeDiffItemModel;
@Input() isCommitting: boolean;
@Output() cancelCommitEvent = new EventEmitter<MergeDiffItem>();
@Output() acceptCommitEvent = new EventEmitter<MergeDiffItemModel>();
currentElement: string;
linkScroll = false;
sourceUsed: string;
committingContent: string;
sourceText: string;
targetText: string;
valueType: MergeItemValueType;
get hasSourceValue() {
// Possible that value is the number 0, which we don't want to consider to be "falsy"
return this.mergeItem.sourceValue !== undefined || this.mergeItem.sourceValue !== null;
}
get hasTargetValue() {
// Possible that value is the number 0, which we don't want to consider to be "falsy"
return this.mergeItem.targetValue !== undefined || this.mergeItem.targetValue !== null;
}
constructor(private dialog: MatDialog, private stringConflict : StringConflictService) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
ngOnChanges(changes: SimpleChanges): void {
if (this.isCommitting) {
this.sourceUsed = this.mergeItem.branchSelected;
switch (this.mergeItem.branchSelected) {
case MergeConflictResolution.Mixed:
this.committingContent = this.mergeItem.mixedContent;
this.sourceUsed = 'Mixed';
break;
case MergeConflictResolution.Target:
this.committingContent = this.mergeItem.targetValue;
this.sourceUsed = 'Target';
break;
default:
this.committingContent = this.mergeItem.sourceValue;
this.sourceUsed = 'Source';
break;
}
}
else {
this.valueType = this.identifyValueType();
this.sourceText = this.getComparisonDisplayText(this.mergeItem.sourceValue, this.mergeItem.targetValue);
this.targetText = this.getComparisonDisplayText(this.mergeItem.targetValue, this.mergeItem.sourceValue);
}
}
ngOnInit(): void { }
cancelCommit() {
this.cancelCommitEvent.emit(this.mergeItem);
}
acceptCommit(branchUsed: MergeConflictResolution) {
this.mergeItem.branchSelected = branchUsed;
this.acceptCommitEvent.emit(this.mergeItem);
}
openEditor() {
this.dialog
.open<
ConflictEditorModalComponent,
ConflictEditorModalData,
ConflictEditorModalResult
>(ConflictEditorModalComponent, {
disableClose: true,
minWidth: '50%',
maxHeight: '98vh',
maxWidth: '98vw',
data: {
source: this.source,
target: this.target,
item: this.mergeItem,
valueType: this.valueType
}
})
.afterClosed()
.pipe(filter((result) => result.status === ModalDialogStatus.Ok))
.subscribe((result: ConflictEditorModalResult) => {
this.mergeItem.mixedContent = result.resolvedContent;
this.mergeItem.branchSelected = MergeConflictResolution.Mixed;
this.acceptCommitEvent.emit(this.mergeItem);
});
}
public get MergeUsed() {
return MergeConflictResolution;
}
public get MergeType() {
return MergeDiffType;
}
updateVerticalScroll(event): void {
if (this.linkScroll) {
if (this.currentElement === 'targetContent') {
this.sourceContent.nativeElement.scrollTop = event.target.scrollTop;
} else if (this.currentElement === 'sourceContent') {
this.targetContent.nativeElement.scrollTop = event.target.scrollTop;
}
}
}
updateCurrentElement(element: 'sourceContent' | 'targetContent') {
this.currentElement = element;
}
linkScrolls(link: boolean) {
this.linkScroll = link;
}
private identifyValueType(): MergeItemValueType {
if (!this.hasSourceValue && !this.hasTargetValue) {
return 'undefined';
}
const value = this.hasSourceValue ? this.mergeItem.sourceValue : this.mergeItem.targetValue;
if (value === undefined || value === null) {
// Don't want "0" to be a "falsy" value
return 'undefined';
}
if (typeof value === 'number') {
return 'number';
}
return 'string';
}
private getComparisonDisplayText(value: string, other: string) {
if (this.valueType === 'undefined' || !value) {
return '<code>Not defined</code>';
}
if (this.valueType === 'number') {
return `${value}`;
}
// Assume the value is a string
return this.stringConflict.getDiffViewHtml(other, value);
}
}
|
MauroDataMapper/mdm-ui
|
src/app/admin/app-container/app-container.component.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, OnDestroy, OnInit } from '@angular/core';
import { SharedService } from '@mdm/services/shared.service';
import { SecurityHandlerService } from '@mdm/services/handlers/security-handler.service';
import { BroadcastService } from '@mdm/services/broadcast.service';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({
selector: 'mdm-app-container',
templateUrl: './app-container.component.html',
styleUrls: ['./app-container.component.sass']
})
export class AdminAppContainerComponent implements OnInit, OnDestroy {
pendingUsersCount = 0;
features = this.sharedService.features;
private unsubscribe$ = new Subject();
constructor(
private sharedService: SharedService,
private securityHandler: SecurityHandlerService,
private broadcast: BroadcastService) {}
ngOnInit() {
if (this.isAdmin()) {
this.getPendingUsers();
this.broadcast
.on('pendingUserUpdated')
.pipe(takeUntil(this.unsubscribe$))
.subscribe(() => this.getPendingUsers());
}
}
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
isAdmin = () => {
return this.securityHandler.isAdmin();
};
getPendingUsers = () => {
this.sharedService.pendingUsersCount().subscribe(data => {
this.pendingUsersCount = data.body.count;
});
};
logout = () => {
this.sharedService.logout();
};
}
|
MauroDataMapper/mdm-ui
|
src/app/term/term/term.component.ts
|
<filename>src/app/term/term/term.component.ts
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import {
Component,
OnInit,
ViewChild,
ChangeDetectorRef,
AfterViewChecked
} from '@angular/core';
import { Subscription, forkJoin, Observable } from 'rxjs';
import { MdmResourcesService } from '@mdm/modules/resources';
import { MessageService } from '@mdm/services/message.service';
import { UIRouterGlobals } from '@uirouter/core';
import { StateHandlerService } from '@mdm/services/handlers/state-handler.service';
import { MatTabGroup } from '@angular/material/tabs';
import { Title } from '@angular/platform-browser';
import { EditingService } from '@mdm/services/editing.service';
import { MessageHandlerService, SecurityHandlerService } from '@mdm/services';
import {
Term,
CatalogueItemDomainType,
TermDetail,
TermDetailResponse,
TerminologyDetail,
TerminologyDetailResponse,
Uuid
} from '@maurodatamapper/mdm-resources';
import { Access } from '@mdm/model/access';
import { TabCollection } from '@mdm/model/ui.model';
import { DefaultProfileItem } from '@mdm/model/defaultProfileModel';
@Component({
selector: 'mdm-term',
templateUrl: './term.component.html',
styleUrls: ['./term.component.scss']
})
export class TermComponent
implements OnInit, AfterViewChecked {
@ViewChild('tab', { static: false }) tabGroup: MatTabGroup;
terminology: TerminologyDetail = null;
term: TermDetail;
showSecuritySection: boolean;
subscription: Subscription;
showSearch = false;
parentId: string;
afterSave: (result: { body: { id: any } }) => void;
editMode = false;
showExtraTabs = false;
activeTab: number;
result: TermDetail;
hasResult = false;
showEditForm = false;
descriptionView = 'default';
annotationsView = 'default';
showEditDescription = false;
rulesItemCount = 0;
codeSetItemCount = 0;
relationshipItemCount = 0;
isLoadingRules = true;
isLoadingCodeSets = true;
isLoadingRelationships = true;
showEdit = false;
showDelete = false;
access: Access;
tabs = new TabCollection(['description', 'links', 'rules', 'annotations']);
constructor(
private resources: MdmResourcesService,
private messageService: MessageService,
private messageHandler: MessageHandlerService,
private stateHandler: StateHandlerService,
private uiRouterGlobals: UIRouterGlobals,
private changeRef: ChangeDetectorRef,
private title: Title,
private editingService: EditingService,
private securityHandler: SecurityHandlerService
) {
}
ngOnInit() {
if (!this.uiRouterGlobals.params.id) {
this.stateHandler.NotFound({ location: false });
return;
}
if (this.uiRouterGlobals.params.edit === 'true') {
this.editMode = true;
}
this.parentId = this.uiRouterGlobals.params.id;
this.title.setTitle('Term');
this.activeTab = this.tabs.getByName(this.uiRouterGlobals.params.tabView as Uuid).index;
this.tabSelected(this.activeTab);
this.termDetails(this.parentId);
this.subscription = this.messageService.changeSearch.subscribe(
(message: boolean) => {
this.showSearch = message;
}
);
}
ngAfterViewChecked(): void {
if (this.tabGroup && !this.editingService.isTabGroupClickEventHandled(this.tabGroup)) {
this.editingService.setTabGroupClickEvent(this.tabGroup);
}
}
rulesCountEmitter(count: number) {
this.isLoadingRules = false;
this.rulesItemCount = count;
}
termDetails(id: string) {
const terminologyId: string = this.uiRouterGlobals.params.terminologyId;
forkJoin([
this.resources.terminology.get(terminologyId) as Observable<
TerminologyDetailResponse
>,
this.resources.terms.get(terminologyId, id) as Observable<
TermDetailResponse
>
]).subscribe(([terminology, term]) => {
this.terminology = terminology.body;
this.term = term.body;
this.resources.catalogueItem
.listSemanticLinks(CatalogueItemDomainType.Term, this.term.id)
.subscribe((resp) => {
this.term.semanticLinks = resp.body.items;
});
this.watchTermObject();
this.term.finalised = this.terminology.finalised;
this.term.editable = this.terminology.editable;
this.term.classifiers = this.term.classifiers || [];
this.term.terminology = this.terminology;
this.result = this.term;
if (this.result.terminology) {
this.hasResult = true;
}
this.messageService.FolderSendMessage(this.result);
this.messageService.dataChanged(this.result);
this.changeRef.detectChanges();
});
}
watchTermObject() {
this.access = this.securityHandler.elementAccess(this.term);
if (this.access !== undefined) {
this.showEdit = this.access.showEdit;
this.showDelete =
this.access.showPermanentDelete || this.access.showSoftDelete;
}
}
tabSelected(index: number) {
const tab = this.tabs.getByIndex(index);
this.stateHandler.Go('term', { tabView: tab.name }, { notify: false });
}
onCancelEdit() {
this.editMode = false; // Use Input editor whe adding a new folder.
}
save(saveItems: Array<DefaultProfileItem>) {
const resource: Term = {
id: this.term.id,
domainType: this.term.domainType,
code: this.term.code,
definition: this.term.definition
};
saveItems.forEach((item: DefaultProfileItem) => {
resource[item.propertyName] = item.value;
});
this.resources.term
.update(this.terminology.id, this.term.id, resource)
.subscribe(
(result:TermDetailResponse) => {
this.termDetails(result.body.id);
this.messageHandler.showSuccess('Term updated successfully.');
this.editingService.stop();
},
(error) => {
this.messageHandler.showError(
'There was a problem updating the Term.',
error
);
}
);
}
codeSetCountEmitter(count: number) {
this.isLoadingCodeSets = false;
this.codeSetItemCount = count;
}
onCodeSetSelect(codeset) {
this.stateHandler.Go(
'codeset',
{ id: codeset.id },
null
);
}
relationshipCountEmitter(count: number) {
this.isLoadingRelationships = false;
this.relationshipItemCount = count;
}
onTermSelect(term) {
this.stateHandler.Go(
'term',
{ terminologyId: term.model, id: term.id },
null
);
}
}
|
MauroDataMapper/mdm-ui
|
src/app/utility/html-editor/html-editor.component.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { ElementSelectorDialogueService } from '@mdm/services/element-selector-dialogue.service';
import { ElementTypesService } from '@mdm/services/element-types.service';
import { MessageService } from '@mdm/services/message.service';
import { EventObj } from 'jodit-angular/lib/Events';
import { Subscription } from 'rxjs/internal/Subscription';
const standardButtons = [
'source',
'|',
'bold',
'italic',
'underline',
'|',
'ul',
'ol',
'eraser',
'|',
'outdent',
'indent',
'|',
'font',
'fontsize',
'brush',
'paragraph',
'|',
'table',
'|',
'align',
'\n',
'undo',
'redo',
'|',
'hr',
'copyformat',
'fullsize',
];
const basicButtons = [
'bold',
'italic',
'underline',
'|',
'ul',
'ol',
'eraser',
'|',
'outdent',
'indent',
'|',
'font',
'fontsize',
'brush',
'paragraph'
];
export enum HtmlButtonMode {
Standard,
Basic
}
@Component({
selector: 'mdm-html-editor',
templateUrl: './html-editor.component.html'
})
export class HtmlEditorComponent implements OnInit {
/* Inputs for manual properties */
@Input() inEditMode: boolean;
@Input() description: string;
@Output() descriptionChange = new EventEmitter<string>();
/* Inputs for model binding */
@Input() element: any;
@Input() property: string;
@Input() buttonMode: HtmlButtonMode;
ButtonModeType = HtmlButtonMode;
editorConfig: object;
private elementSelectorSubscription: Subscription;
constructor(
private elementDialogService: ElementSelectorDialogueService,
private messageService: MessageService,
private elementTypesService: ElementTypesService) { }
ngOnInit(): void {
const buttons = this.buttonMode === HtmlButtonMode.Basic ? basicButtons : standardButtons;
const extraButtons = [
{
name: 'addelement',
text: 'Add Element',
icon: '',
exec: (editor: any) => this.onAddElementLink(this, editor)
}
];
this.editorConfig = {
buttons,
buttonsMD: buttons,
buttonsSM: buttons,
buttonsXS: buttons,
extraButtons
};
}
onHtmlEditorChanged(event: EventObj) {
this.description = event.editor.value;
this.descriptionChange.emit(this.description);
}
// Requires a reference to the HtmlEditorComponent to get correct scope
onAddElementLink(component: HtmlEditorComponent, editor: any) {
if (component.elementSelectorSubscription) {
component.elementSelectorSubscription.unsubscribe();
component.elementSelectorSubscription = null;
}
const focusNode = editor.selection.sel.focusNode;
component.elementSelectorSubscription = component.messageService.elementSelector.subscribe(element => {
if (!element) {
return;
}
const href = component.elementTypesService.getLinkUrl(element);
const html = editor.create.fromHTML(`<a href='${href}' title='${element.label}'>${element.label}</a>`);
editor.selection.setCursorIn(focusNode);
editor.selection.insertHTML(html);
});
component.elementDialogService.open([], []);
}
}
|
MauroDataMapper/mdm-ui
|
src/app/diagram/diagram-toolbar/diagram-toolbar.component.ts
|
<reponame>MauroDataMapper/mdm-ui
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import {
Component,
EventEmitter,
Input,
Output
} from '@angular/core';
@Component({
selector: 'mdm-diagram-toolbar',
templateUrl: './diagram-toolbar.component.html',
styleUrls: [ './diagram-toolbar.component.scss' ]
})
export class DiagramToolbarComponent {
@Output() toolbarClick = new EventEmitter<string>();
@Input() isPopup: boolean;
@Input() canMoveUp: boolean;
constructor() {
}
click(buttonName: string): void {
this.toolbarClick.emit(buttonName);
}
}
|
MauroDataMapper/mdm-ui
|
src/app/modules/shared/shared.module.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { EditableFormButtonsComponent } from '@mdm/utility/editable-form-buttons/editable-form-buttons.component';
import { FormsModule } from '@angular/forms';
import { MoreDescriptionComponent } from '@mdm/shared/more-description/more-description.component';
import { UIRouterModule } from '@uirouter/angular';
import { McSelectComponent } from '@mdm/utility/mc-select/mc-select.component';
import { ReactiveFormsModule } from '@angular/forms';
import { MatPasswordStrengthModule } from '@angular-material-extensions/password-strength';
import { InlineTextEditComponent } from '@mdm/shared/inline-text-edit/inline-text-edit.component';
import { FooterComponent } from '@mdm/shared/footer/footer.component';
import { MetadataCompareComponent } from '@mdm/shared/metadata-compare/metadata-compare.component';
import { EnumerationCompareComponent } from '@mdm/shared/enumeration-compare/enumeration-compare.component';
import { MaterialModule } from '../material/material.module';
import { NgxJsonViewerModule } from 'ngx-json-viewer';
import { ErrorComponent } from '@mdm/errors/error.component';
import { FlexLayoutModule } from '@angular/flex-layout';
import { MdmPaginatorComponent } from '@mdm/shared/mdm-paginator/mdm-paginator';
import { NgxSkeletonLoaderModule } from 'ngx-skeleton-loader';
import { CodemirrorModule } from '@ctrl/ngx-codemirror';
import { SafePipe } from '@mdm/pipes/safe.pipe';
import { ShareWithComponent } from '@mdm/access/share-with/share-with.component';
import { GroupAccessNewComponent } from '@mdm/access/group-access-new/group-access-new.component';
import { TextDiffComponent } from '@mdm/shared/text-diff/text-diff.component';
import { ElementLinkComponent } from '@mdm/utility/element-link/element-link.component';
import { DownloadLinkComponent } from '@mdm/utility/download-link/download-link.component';
import { NewVersionComponent } from '@mdm/shared/new-version/new-version.component';
import { AlertComponent } from '@mdm/shared/alert/alert.component';
import { BranchSelectorComponent } from '@mdm/shared/branch-selector/branch-selector.component';
import { ResizableDirective } from '@mdm/directives/resizable.directive';
import { DataTypeListButtonsComponent } from '@mdm/shared/data-type-list-buttons/data-type-list-buttons.component';
import { ModelIconComponent } from '@mdm/shared/model-icon/model-icon.component';
import { PathNameComponent } from '../../shared/path-name/path-name.component';
import { FavoriteButtonComponent } from '../../shared/favorite-button/favorite-button.component';
import { CatalogueItemPropertiesComponent } from '../../shared/catalogue-item-properties/catalogue-item-properties.component';
@NgModule({
declarations: [
EditableFormButtonsComponent,
MoreDescriptionComponent,
McSelectComponent,
InlineTextEditComponent,
FooterComponent,
MetadataCompareComponent,
EnumerationCompareComponent,
ErrorComponent,
MdmPaginatorComponent,
SafePipe,
ShareWithComponent,
GroupAccessNewComponent,
TextDiffComponent,
ElementLinkComponent,
DownloadLinkComponent,
NewVersionComponent,
AlertComponent,
BranchSelectorComponent,
ResizableDirective,
DataTypeListButtonsComponent,
ModelIconComponent,
PathNameComponent,
FavoriteButtonComponent,
CatalogueItemPropertiesComponent
],
imports: [
CommonModule,
FormsModule,
MaterialModule,
ReactiveFormsModule,
MatPasswordStrengthModule,
NgxJsonViewerModule,
FlexLayoutModule,
ReactiveFormsModule,
NgxSkeletonLoaderModule,
CodemirrorModule
],
exports: [
EditableFormButtonsComponent,
FormsModule,
MoreDescriptionComponent,
UIRouterModule,
MaterialModule,
McSelectComponent,
ReactiveFormsModule,
MatPasswordStrengthModule,
InlineTextEditComponent,
FooterComponent,
MetadataCompareComponent,
EnumerationCompareComponent,
NgxJsonViewerModule,
ErrorComponent,
FlexLayoutModule,
MdmPaginatorComponent,
NgxSkeletonLoaderModule,
CodemirrorModule,
SafePipe,
ShareWithComponent,
GroupAccessNewComponent,
TextDiffComponent,
ElementLinkComponent,
TextDiffComponent,
DownloadLinkComponent,
NewVersionComponent,
AlertComponent,
BranchSelectorComponent,
ResizableDirective,
DataTypeListButtonsComponent,
PathNameComponent,
ModelIconComponent,
FavoriteButtonComponent,
CatalogueItemPropertiesComponent
]
})
export class SharedModule {}
|
MauroDataMapper/mdm-ui
|
src/app/shared/branch-selector/branch-selector.component.spec.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { CatalogueItemDomainType } from '@maurodatamapper/mdm-resources';
import { MdmResourcesService } from '@mdm/modules/resources';
import { ComponentHarness, setupTestModuleForComponent } from '@mdm/testing/testing.helpers';
import { of } from 'rxjs';
import { BranchSelectorComponent } from './branch-selector.component';
interface MdmResourcesBranchableApiStub {
simpleModelVersionTree: jest.Mock;
}
interface MdmResourcesServiceStub {
dataModel: MdmResourcesBranchableApiStub;
}
describe('BranchSelectorComponent', () => {
let harness: ComponentHarness<BranchSelectorComponent>;
const mdmResourcesStub: MdmResourcesServiceStub = {
dataModel: {
simpleModelVersionTree: jest.fn(() => of())
}
};
beforeEach(async () => {
harness = await setupTestModuleForComponent(
BranchSelectorComponent,
{
providers: [
{
provide: MdmResourcesService,
useValue: mdmResourcesStub
}
]
});
harness.detectChanges(component => {
component.catalogueItem = {
id: '1234',
domainType: CatalogueItemDomainType.DataModel
};
});
});
it('should create', () => {
expect(harness?.isComponentCreated).toBeTruthy();
});
});
|
MauroDataMapper/mdm-ui
|
src/app/shared/more-description/more-description.component.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, OnInit, Input } from '@angular/core';
import { UserSettingsHandlerService } from '@mdm/services/utility/user-settings-handler.service';
import { MarkdownParserService } from '@mdm/utility/markdown/markdown-parser/markdown-parser.service';
@Component({
selector: 'mdm-more-description',
templateUrl: './more-description.component.html',
styleUrls: ['./more-description.component.sass']
})
export class MoreDescriptionComponent implements OnInit {
@Input() description: string;
@Input() length: any;
maxLength = 100;
showMore = false;
shortDesc: string;
fullDesc: string;
constructor(
userSettingsHandler: UserSettingsHandlerService,
private markdownParser: MarkdownParserService
) {
this.showMore = userSettingsHandler.get('expandMoreDescription');
}
ngOnInit() {
if (this.length !== undefined) {
this.maxLength = this.length;
}
this.shortDesc = this.createShortDescription();
this.fullDesc = this.markdownParser.parse(this.description, 'html');
}
toggle() {
this.showMore = !this.showMore;
}
createShortDescription() {
const desc = this.markdownParser.parse(this.description, 'text');
if (desc && desc.length > this.maxLength) {
let subStr = desc.substring(0, this.maxLength);
const lastIndexOf = subStr.lastIndexOf(' ');
subStr = subStr.substring(0, lastIndexOf);
return `${subStr}...`;
} else {
return desc;
}
}
}
|
MauroDataMapper/mdm-ui
|
src/app/wizards/dataElement/data-element-main/data-element-main.component.ts
|
<filename>src/app/wizards/dataElement/data-element-main/data-element-main.component.ts
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import {
ChangeDetectorRef,
Component,
EventEmitter,
OnInit
} from '@angular/core';
import { Step } from '@mdm/model/stepModel';
import { StateService } from '@uirouter/core';
import { StateHandlerService } from '@mdm/services/handlers/state-handler.service';
import { MdmResourcesService } from '@mdm/modules/resources';
import { DataElementStep1Component } from '../data-element-step1/data-element-step1.component';
import { DataElementStep2Component } from '../data-element-step2/data-element-step2.component';
import { MessageHandlerService } from '@mdm/services/utility/message-handler.service';
import { Title } from '@angular/platform-browser';
import { CatalogueItemDomainType, DataElement, DataElementDetailResponse, DataType, DataTypeDetail, DataTypeDetailResponse } from '@maurodatamapper/mdm-resources';
import { ElementTypesService } from '@mdm/services';
@Component({
selector: 'mdm-data-element-main',
templateUrl: './data-element-main.component.html',
styleUrls: ['./data-element-main.component.sass']
})
export class DataElementMainComponent implements OnInit {
steps: Step[] = [];
doneEvent = new EventEmitter<any>();
parentDataModelId: any;
grandParentDataClassId: any;
parentDataClassId: any;
processing: any;
isProcessComplete: any;
finalResult = {};
successCount = 0;
failCount = 0;
datatype: DataTypeDetail;
model = {
metadata: [],
dataType: undefined,
description: undefined,
classifiers: [],
parentDataModel: { id: null},
parentDataClass: { id: null},
parent: {},
createType: 'new',
copyFromDataClass: [],
selectedDataElements: [],
label: '',
inlineDataTypeValid: false,
showNewInlineDataType: false,
allDataTypesCount: 0,
newlyAddedDataType: {
label: '',
description: '',
metadata: [],
domainType: CatalogueItemDomainType.PrimitiveType,
enumerationValues: [],
classifiers: [],
organisation: '',
referencedDataType: { id: '' },
referencedDataClass: { id: '' },
referencedModel: { id: '', domainType: '' }
},
isProcessComplete: false
};
constructor(
private stateService: StateService,
private stateHandler: StateHandlerService,
private resources: MdmResourcesService,
private messageHandler: MessageHandlerService,
private changeRef: ChangeDetectorRef,
private title: Title,
private elementTypes: ElementTypesService
) { }
ngOnInit() {
this.title.setTitle('New Data Element');
// tslint:disable-next-line: deprecation
this.parentDataModelId = this.stateService.params.parentDataModelId;
// tslint:disable-next-line: deprecation
this.grandParentDataClassId = this.stateService.params.grandParentDataClassId;
// tslint:disable-next-line: deprecation
this.parentDataClassId = this.stateService.params.parentDataClassId;
if (!this.parentDataModelId) {
this.stateHandler.NotFound({ location: false });
return;
}
this.model.parentDataModel.id = this.parentDataModelId;
this.model.parentDataClass.id = this.parentDataClassId;
const step1 = new Step();
step1.title = 'Data Element Import Method';
step1.component = DataElementStep1Component;
step1.scope = this;
step1.hasForm = true;
step1.invalid = false;
const step2 = new Step();
step2.title = 'Data Element Details';
step2.component = DataElementStep2Component;
step2.scope = this;
step2.invalid = true;
this.resources.dataClass.getChildDataClass(this.parentDataModelId, this.grandParentDataClassId, this.parentDataClassId).subscribe(result => {
result.body.breadcrumbs.push(Object.assign([], result.body));
this.model.parent = result.body;
this.steps.push(step1);
this.steps.push(step2);
this.changeRef.detectChanges();
});
this.resources.dataType.list(this.parentDataModelId).subscribe(result => {
this.model.allDataTypesCount = result.count;
if (result.count === 0) {
this.model.showNewInlineDataType = true;
}
this.changeRef.detectChanges();
});
}
closeWizard = () => {
this.stateHandler.GoPrevious();
};
save = () => {
if (this.model.createType === 'new') {
this.validateDataType();
this.saveNewDataElement();
} else {
this.saveCopiedDataClasses();
}
};
getMultiplicity = (resource, multiplicity) => {
if (this.model[multiplicity] === '*') {
this.model[multiplicity] = -1;
}
if (!isNaN(this.model[multiplicity])) {
resource[multiplicity] = parseInt(this.model[multiplicity], 10);
}
};
fireChanged = (tab: any) => {
for (let i = 0; i < this.steps.length; i++) {
const step: Step = this.steps[i];
if (i === tab.selectedIndex) {
if (step.compRef) {
if (step.compRef.instance.onLoad !== undefined) {
step.compRef.instance.onLoad();
}
step.active = true;
this.changeRef.detectChanges();
}
} else {
step.active = false;
}
}
this.changeRef.detectChanges();
};
saveNewDataElement = () => {
let dataType;
if (!this.model.showNewInlineDataType) {
dataType = { id: this.model.dataType.id };
this.saveDataElement(dataType);
}
else {
const domainType = this.elementTypes.isModelDataType(this.model.newlyAddedDataType.domainType)
? CatalogueItemDomainType.ModelDataType
: this.model.newlyAddedDataType.domainType;
const res: DataType = {
label: this.model.newlyAddedDataType.label,
description: this.model.newlyAddedDataType.description,
organisation: this.model.newlyAddedDataType.organisation,
domainType,
referenceDataType: {
id: this.model.newlyAddedDataType.referencedDataType ? this.model.newlyAddedDataType.referencedDataType.id : null
},
referenceClass: {
id: this.model.newlyAddedDataType.referencedDataClass ? this.model.newlyAddedDataType.referencedDataClass.id : null
},
modelResourceDomainType: domainType === CatalogueItemDomainType.ModelDataType ? this.model.newlyAddedDataType.referencedModel.domainType : null,
modelResourceId: domainType === CatalogueItemDomainType.ModelDataType ? this.model.newlyAddedDataType.referencedModel.id : null,
classifiers: this.model.classifiers.map(cls => ({ id: cls.id })),
enumerationValues: this.model.newlyAddedDataType.enumerationValues.map(
m => ({
key: m.key,
value: m.value,
category: m.category
})
),
metadata: this.model.metadata.map(m => ({
key: m.key,
value: m.value,
namespace: m.namespace
}))
};
this.resources.dataType.save(this.parentDataModelId, res).subscribe((response: DataTypeDetailResponse) => {
dataType = response.body;
this.saveDataElement(response.body);
}, error => {
this.messageHandler.showError('There was a problem saving the Data Type.', error);
});
}
};
saveDataElement(dataType: any) {
const resource: DataElement = {
domainType: CatalogueItemDomainType.DataElement,
label: this.model.label,
description: this.model.description,
dataType: {
id: dataType.id
},
classifiers: this.model.classifiers.map(cls => {
return { id: cls.id };
}),
metadata: this.model.metadata.map(m => {
return {
key: m.key,
value: m.value,
namespace: m.namespace
};
}),
minMultiplicity: null,
maxMultiplicity: null
};
this.getMultiplicity(resource, 'minMultiplicity');
this.getMultiplicity(resource, 'maxMultiplicity');
// deferred
this.resources.dataElement.save(this.parentDataModelId, this.parentDataClassId, resource).subscribe((response: DataElementDetailResponse) => {
this.messageHandler.showSuccess('Data Element saved successfully.');
this.stateHandler.Go(
'dataElement',
{
dataModelId: response.body.model || '',
dataClassId: response.body.dataClass || '',
id: response.body.id
},
{ reload: true, location: true }
);
}, error => {
this.messageHandler.showError('There was a problem saving the Data Element.', error);
});
}
validateDataType() {
let isValid = true;
if (!this.model.showNewInlineDataType) {
return true;
}
if (
!this.model.newlyAddedDataType.label ||
this.model.newlyAddedDataType.label.trim().length === 0
) {
isValid = false;
}
// Check if for EnumerationType, at least one value is added
if (this.model.newlyAddedDataType.domainType === CatalogueItemDomainType.EnumerationType && this.model.newlyAddedDataType.enumerationValues.length === 0) {
isValid = false;
}
// Check if for ReferenceType, the dataClass is selected
if (this.model.newlyAddedDataType.domainType === CatalogueItemDomainType.ReferenceType && !this.model.newlyAddedDataType.referencedDataClass) {
isValid = false;
}
// Check if for TerminologyType, the terminology is selected
if (this.model.newlyAddedDataType.domainType === CatalogueItemDomainType.TerminologyType && !this.model.newlyAddedDataType.referencedModel) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
isValid = false;
}
}
saveCopiedDataClasses = () => {
this.steps[1].compRef.instance.saveCopiedDataClasses();
};
}
|
MauroDataMapper/mdm-ui
|
src/app/admin/api-property-table/api-property-table.component.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { AfterViewInit, Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatSelectChange } from '@angular/material/select';
import { MatSort, Sort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { ApiPropertyEditableState, ApiPropertyEditType } from '@mdm/model/api-properties';
import { MdmResourcesService } from '@mdm/modules/resources';
import { BroadcastService, MessageHandlerService, StateHandlerService } from '@mdm/services';
import { catchError, switchMap } from 'rxjs/operators';
export interface ApiPropertyTableViewChange {
category?: string;
sortBy?: string;
sortType?: string;
}
@Component({
selector: 'mdm-api-property-table',
templateUrl: './api-property-table.component.html',
styleUrls: ['./api-property-table.component.scss']
})
export class ApiPropertyTableComponent implements OnInit, OnChanges, AfterViewInit {
@ViewChild(MatSort, { static: true }) sort: MatSort;
@Input() properties: ApiPropertyEditableState[] = [];
@Input() categories: string[] = [];
@Output() readonly viewChange = new EventEmitter<ApiPropertyTableViewChange>();
@Output() valueCleared = new EventEmitter();
dataSource = new MatTableDataSource<ApiPropertyEditableState>();
readonly displayedColumns = ['key', 'category', 'value', 'icons'];
totalItemCount = 0;
selectedCategory = '';
EditType = ApiPropertyEditType;
constructor(
private stateHandler: StateHandlerService,
private resources: MdmResourcesService,
private dialog: MatDialog,
private messageHandler: MessageHandlerService,
private broadcast: BroadcastService) { }
ngOnInit(): void {
this.dataSource = new MatTableDataSource(this.properties);
}
ngAfterViewInit(): void {
this.sort.sortChange.subscribe((sort: Sort) => this.viewChange.emit({
category: this.selectedCategory,
sortBy: sort.active,
sortType: sort.direction
}));
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.properties) {
this.dataSource.data = this.properties;
this.totalItemCount = this.properties.length;
}
}
categoryChanged(change: MatSelectChange) {
this.viewChange.emit({
category: change.value,
sortBy: this.sort.active,
sortType: this.sort.direction
});
}
add = () => {
this.stateHandler.Go('appContainer.adminArea.apiPropertyAdd');
};
edit(record: ApiPropertyEditableState) {
if (!record.original) {
return;
}
this.stateHandler.Go('appContainer.adminArea.apiPropertyEdit', { id: record.original.id });
}
delete(record: ApiPropertyEditableState) {
this.dialog
.openConfirmationAsync({
data: {
title: 'Are you sure?',
okBtnTitle: 'Yes',
btnType: 'warn',
message: `<p>Are you sure you want to delete the property "${record.original.key}"?</p>
<p>Once deleted, this property and value cannot be retrieved.</p>`
}
})
.pipe(
switchMap(() => this.resources.apiProperties.remove(record.original.id)),
catchError(errors => {
this.messageHandler.showError('There was a problem deleting the property.', errors);
return [];
})
)
.subscribe(() => {
this.messageHandler.showSuccess(`Successfully deleted the property ${record.original.key}.`);
this.broadcast.apiPropertyUpdated({
key: record.original.key,
value: record.original.value,
deleted: true });
if (record.metadata.requiresReload) {
this.stateHandler.reload();
}
else {
this.viewChange.emit({
category: this.selectedCategory,
sortBy: this.sort.active,
sortType: this.sort.direction
});
}
});
}
}
|
MauroDataMapper/mdm-ui
|
src/app/merge-diff/merge-diff.module.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from '@mdm/modules/shared/shared.module';
import { MaterialModule } from '@mdm/modules/material/material.module';
import { MergeDiffContainerComponent } from '@mdm/merge-diff/merge-diff-container/merge-diff-container.component';
import { MergeItemSelectorComponent } from './merge-item-selector/merge-item-selector.component';
import { MergeComparisonComponent } from './merge-comparsion/merge-comparsion.component';
import { CatalogueModule } from '@mdm/modules/catalogue/catalogue.module';
import { MergeFilterPipe } from './pipes/merge-filter.pipe';
import { ConflictEditorModalComponent } from './conflict-editor/conflict-editor-modal/conflict-editor-modal.component';
import { StringConflictEditorComponent } from './conflict-editor/string-conflict-editor/string-conflict-editor.component';
import { NumberConflictEditorComponent } from './conflict-editor/number-conflict-editor/number-conflict-editor.component';
@NgModule({
declarations: [
MergeDiffContainerComponent,
MergeItemSelectorComponent,
MergeComparisonComponent,
MergeFilterPipe,
ConflictEditorModalComponent,
StringConflictEditorComponent,
NumberConflictEditorComponent
],
imports: [
CommonModule,
SharedModule,
MaterialModule,
CatalogueModule
],
exports: [
MergeDiffContainerComponent
]
})
export class MergeDiffModule { }
|
MauroDataMapper/mdm-ui
|
src/app/navbar/navbar.component.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, OnDestroy, OnInit } from '@angular/core';
import { SecurityHandlerService } from '@mdm/services/handlers/security-handler.service';
import { LoginModalComponent } from '@mdm/modals/login-modal/login-modal.component';
import { ForgotPasswordModalComponent } from '@mdm/modals/forgot-password-modal/forgot-password-modal.component';
import { SharedService } from '@mdm/services/shared.service';
import { BroadcastService } from '@mdm/services/broadcast.service';
import { MatDialog } from '@angular/material/dialog';
import { RegisterModalComponent } from '@mdm/modals/register-modal/register-modal.component';
import { Subject } from 'rxjs';
import { EditingService } from '@mdm/services/editing.service';
import { ThemingService } from '@mdm/services/theming.service';
import { MdmResourcesService } from '@mdm/modules/resources';
import { catchError, map, takeUntil } from 'rxjs/operators';
import { ApiProperty, ApiPropertyIndexResponse } from '@maurodatamapper/mdm-resources';
@Component({
selector: 'mdm-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.scss']
})
export class NavbarComponent implements OnInit, OnDestroy {
profilePictureReloadIndex = 0;
profile: any;
logoUrl: string;
logoWidth?: string;
backendURL: any;
imgChanged: boolean;
simpleViewSupport: any;
current: any;
HDFLink: any;
sideNav: any;
pendingUsersCount = 0;
isLoggedIn = this.securityHandler.isLoggedIn();
features = this.sharedService.features;
private unsubscribe$ = new Subject();
constructor(
private sharedService: SharedService,
private dialog: MatDialog,
private securityHandler: SecurityHandlerService,
private broadcast: BroadcastService,
private editingService: EditingService,
private theming: ThemingService,
private resources: MdmResourcesService) { }
ngOnInit() {
this.broadcast
.onUserLoggedIn()
.pipe(takeUntil(this.unsubscribe$))
.subscribe(() => this.isLoggedIn = true);
this.broadcast
.onUserLoggedOut()
.pipe(takeUntil(this.unsubscribe$))
.subscribe(() => this.isLoggedIn = false);
if (this.isLoggedIn) {
this.profile = this.securityHandler.getCurrentUser();
// if (this.isAdmin()) {
// this.getPendingUsers();
// }
}
this.backendURL = this.sharedService.backendURL;
this.setupLogo();
this.imgChanged = false;
this.HDFLink = this.sharedService.HDFLink;
this.current = this.sharedService.current;
this.broadcast
.on('pendingUserUpdated')
.pipe(takeUntil(this.unsubscribe$))
.subscribe(() => this.getPendingUsers());
this.broadcast
.on('profileImageUpdated')
.pipe(takeUntil(this.unsubscribe$))
.subscribe(() => {
this.imgChanged = true;
setTimeout(() => {
this.imgChanged = false;
}, 1000);
});
}
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
setupLogo() {
// First default to the static asset, then try to override with a custom API property if available
this.logoUrl = this.theming.getAssetPath('logo.png');
this.resources.apiProperties
.listPublic()
.pipe(
map((response: ApiPropertyIndexResponse) => response.body.items.filter(p => p.key.startsWith('theme.logo.'))),
catchError(() => [])
)
.subscribe((properties: ApiProperty[]) => {
const logoUrl = properties.find(p => p.key === 'theme.logo.url');
const logoWidth = properties.find(p => p.key === 'theme.logo.width');
if (logoUrl) {
this.logoUrl = logoUrl.value;
}
if (logoWidth) {
this.logoWidth = logoWidth.value;
}
});
}
getPendingUsers = () => {
this.sharedService.pendingUsersCount().subscribe(data => {
this.pendingUsersCount = data.body.count;
});
};
isAdmin = () => {
return this.securityHandler.isAdmin();
};
login = () => {
this.dialog.open(LoginModalComponent, {}).afterClosed().subscribe((user) => {
if (user) {
if (user.needsToResetPassword) {
this.broadcast.userLoggedIn({ nextRoute: 'appContainer.userArea.changePassword' });
return;
}
this.profile = user;
this.broadcast.userLoggedIn({ nextRoute: 'appContainer.mainApp.twoSidePanel.catalogue.allDataModel' });
}
});
};
logout = () => {
this.securityHandler.logout();
};
forgottenPassword = () => {
this.dialog.open(ForgotPasswordModalComponent, {});
};
register = () => {
const dialog = this.dialog.open(RegisterModalComponent, { panelClass: 'register-modal' });
this.editingService.configureDialogRef(dialog);
dialog.afterClosed().subscribe(user => {
if (user) {
if (user.needsToResetPassword) {
this.broadcast.userLoggedIn({ nextRoute: 'appContainer.userArea.change-password' });
return;
}
this.profile = user;
this.broadcast.userLoggedIn({ nextRoute: 'appContainer.mainApp.twoSidePanel.catalogue.allDataModel' });
}
});
};
}
|
MauroDataMapper/mdm-ui
|
src/app/shared/table-buttons/table-buttons.component.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { EditingService } from '@mdm/services/editing.service';
@Component({
selector: 'mdm-table-buttons',
templateUrl: './table-buttons.component.html',
styleUrls: ['./table-buttons.component.sass']
})
export class TableButtonsComponent {
@Input() record: any;
@Input() index: any;
@Input() hideDelete: boolean;
@Input() hideEdit: any;
@Input() confirmDelete = true;
@Input() validate: (record: any, index: any) => boolean;
@Input() records: any;
@Output() cancelEdit = new EventEmitter<any>();
@Output() edit = new EventEmitter<any>();
@Output() delete = new EventEmitter<any>();
@Output() save = new EventEmitter<any>();
constructor(private editingService: EditingService) {}
saveClicked(record, index) {
if (!this.validate) {
this.save.emit([record, index]);
return;
}
if (this.validate(record, index)) {
this.save.emit([record, index]);
return;
}
}
editClicked(record, index) {
record.inEdit = true;
record.edit = Object.assign({}, record);
if (this.edit) {
this.edit.emit([record, index]);
}
}
editCancelled(record, index) {
this.editingService.confirmCancelAsync().subscribe(confirm => {
if (!confirm) {
return;
}
record.inEdit = undefined;
record.edit = undefined;
if (this.cancelEdit) {
this.cancelEdit.emit([record, index]);
}
});
}
deleteClicked(record) {
if (this.confirmDelete) {
record.inDelete = true;
}
else {
this.delete.emit([record, this.index]);
}
}
deleteCancelled(record) {
record.inDelete = undefined;
}
deleteApproved(record, index) {
if (this.delete) {
this.delete.emit([record, index]);
}
}
}
|
MauroDataMapper/mdm-ui
|
src/app/utility/mc-enumeration-list-with-category/mc-enumeration-list-with-category.component.ts
|
<reponame>MauroDataMapper/mdm-ui<filename>src/app/utility/mc-enumeration-list-with-category/mc-enumeration-list-with-category.component.ts
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, OnInit, Input, ViewChild, Output, EventEmitter } from '@angular/core';
import { UserSettingsHandlerService } from '@mdm/services/utility/user-settings-handler.service';
import { SecurityHandlerService } from '@mdm/services/handlers/security-handler.service';
import { MdmResourcesService } from '@mdm/modules/resources';
import { MessageHandlerService } from '@mdm/services/utility/message-handler.service';
import { ValidatorService } from '@mdm/services/validator.service';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { MatTable } from '@angular/material/table';
import { MdmPaginatorComponent } from '@mdm/shared/mdm-paginator/mdm-paginator';
import { StateHandlerService } from '@mdm/services';
import { EditingService } from '@mdm/services/editing.service';
import { DataClassDetail, DataModelDetail } from '@maurodatamapper/mdm-resources';
@Component({
selector: 'mdm-mc-enumeration-list-with-category',
templateUrl: './mc-enumeration-list-with-category.component.html',
styleUrls: ['./mc-enumeration-list-with-category.component.sass']
})
export class McEnumerationListWithCategoryComponent implements OnInit {
@Input() parent : DataModelDetail | DataClassDetail;
@Input() clientSide = false;
@Input() enumerationValues ;
@Input() onUpdate;
@Input() type: any;
@Input() isEditable = false;
@Input() domainType: string;
@Output() afterSave = new EventEmitter<any>();
@ViewChild(MdmPaginatorComponent, { static: true }) paginator: MdmPaginatorComponent;
@ViewChild(MatTable, { static: false }) table: MatTable<any>;
dataSource: any;
enumsCount: number;
total: number;
displayItems: any[];
categories = [];
allRecords = [];
allRecordsWithGroups = [];
hasCategory = false;
showEdit = false;
hideFilters = true;
currentPage = 0;
pageSize = this.userSettingsHandler.get('countPerTable');
pageSizes = this.userSettingsHandler.get('counts');
displayedColumnsEnums = ['group', 'key', 'value', 'buttons'];
sortBy = 'group';
sortType = '';
constructor(
private userSettingsHandler: UserSettingsHandlerService,
private securityHandler: SecurityHandlerService,
private resourcesService: MdmResourcesService,
private messageHandler: MessageHandlerService,
private validator: ValidatorService,
private stateHandler: StateHandlerService,
private editingService: EditingService) {
}
ngOnInit() {
if (!this.clientSide) {
this.displayedColumnsEnums = ['group', 'key', 'value', 'more', 'buttons'];
} else {
this.displayedColumnsEnums = ['group', 'key', 'value', 'buttons'];
}
if (this.enumerationValues !== null && this.enumerationValues !== undefined) {
this.showRecords(this.enumerationValues);
if (this.parent !== null && this.parent !== undefined) {
const access = this.securityHandler.elementAccess(this.parent);
this.showEdit = access.showEdit;
}
}
}
// Drag and drop
dropTable(event: CdkDragDrop<any[]>) {
const prevIndex = this.displayItems.findIndex(r => r.id === event.item.data.id);
moveItemInArray(this.displayItems, prevIndex, event.currentIndex);
let prevRec = this.displayItems[event.currentIndex - 1];
const nextRec = this.displayItems[event.currentIndex + 1];
if (prevRec === undefined) {
return;
}
let newPosition = 0;
if (prevRec.isCategoryRow) {
newPosition = nextRec.index;
} else {
newPosition = parseInt(prevRec.index, 10) + 1;
}
let newCategory = null;
let nextIndex = null;
if (prevRec.isCategoryRow) {
newCategory = prevRec.category;
} else {
while (!newCategory && prevRec) {
nextIndex = this.displayItems.indexOf(prevRec) - 1;
prevRec = this.displayItems[nextIndex];
if (prevRec && prevRec.isCategoryRow) {
newCategory = prevRec.category;
break;
}
}
}
this.updateOrder(event.item.data.id, newPosition, newCategory);
this.table.renderRows();
}
updateOrder = (enumId, newPosition, newCategory) => {
if (this.clientSide) {
const sorted = this.allRecords;
// find it & remove it
let index = 0;
sorted.forEach((item, i) => {
if (item.id === enumId) {
index = i;
}
});
const foundRecords = sorted.splice(index, 1);
if (foundRecords && foundRecords.length > 0) {
const record = foundRecords[0];
let location = -1;
for (let i = 0; i < sorted.length && location === -1; i++) {
if (
(i === 0 && newPosition < sorted[i].index) ||
sorted[i].index === newPosition ||
(sorted[i].index < newPosition &&
i + 1 < sorted.length &&
newPosition < sorted[i + 1].index)
) {
record.index = newPosition;
// record[0].edit.index = newPosition;
sorted.splice(i, 0, record);
location = i;
}
}
for (let i = 0; i < sorted.length; i++) {
sorted[i].index = i + 1;
}
this.showRecords(sorted);
}
} else {
const resource = {
index: newPosition,
category: newCategory
};
this.resourcesService.enumerationValues.updateInEnumeratedType(this.parent.model, this.parent.id, enumId, resource).subscribe(() => {
this.reloadRecordsFromServer().subscribe(data => {
this.showRecords(data.body.enumerationValues);
});
this.messageHandler.showSuccess('Enumeration updated successfully.');
},
error => {
this.messageHandler.showError('There was a problem updating the enumeration.', error);
}
);
}
};
identify(item) {
return item.id;
}
// Accepts the array and key
groupBy = (array, key) => {
// Return the end result
return array.reduce((result, currentValue) => {
// If an array already present for key, push it to the array. Else create an array and push the object
(result[currentValue[key]] = result[currentValue[key]] || []).push(
currentValue
);
// Order by index
result[currentValue[key]].sort((x, y) => x.index - y.index);
// Return the current iteration `result` value, this will be taken as next iteration `result` value and accumulate
return result;
}, {}); // empty object is the initial value for result object
};
showRecords(values) {
if (!values && values.length > 0) {
return;
}
this.categories = [];
this.allRecords = [].concat(values);
this.enumsCount = this.allRecords.length;
this.hasCategory = false;
for (const record of this.allRecords) {
if (record && record.category) {
this.hasCategory = true;
break;
}
}
let categoryNames = [];
let categories = [];
categories = this.groupBy(this.allRecords, 'category');
let hasEmptyCategory = false;
for (const category in categories) {
if (category !== null && category !== 'null' && !categoryNames.includes(category)) {
categoryNames.push(category);
} else {
hasEmptyCategory = true;
}
}
if (hasEmptyCategory) {
categoryNames.push(null);
}
if (this.sortType === 'asc') {
categoryNames = categoryNames.sort((a, b) => a[0].localeCompare(b[0]));
} else if (this.sortType === 'desc') {
categoryNames = categoryNames.reverse();
}
const allRecordsWithGroups = [];
categoryNames.forEach(category => {
// TODO sort
// categories[category] = _.sortBy(categories[category], 'index');
if (category !== null && category !== '' && category !== undefined) {
this.categories.push({ key: category, value: category });
}
allRecordsWithGroups.push({
id: category !== 'null' ? category : null,
category: category !== 'null' ? category : null,
isCategoryRow: true
});
categories[category].forEach(row => {
allRecordsWithGroups.push(row);
});
});
this.displayItems = [];
this.total = this.enumsCount;
const start = this.pageSize * this.currentPage;
let e = 0;
let skippedCategories = 0;
for (let i = 0; i < allRecordsWithGroups.length; i++) {
if (i < start + skippedCategories) {
if (allRecordsWithGroups[i].isCategoryRow) {
skippedCategories++;
}
continue;
}
if (allRecordsWithGroups[i].isCategoryRow) {
this.displayItems.push(allRecordsWithGroups[i]);
continue;
}
if (e < this.pageSize) {
this.displayItems.push(allRecordsWithGroups[i]);
e++;
} else {
break;
}
}
// If the current page ends with a category, don't display it
if (
this.displayItems[this.displayItems.length - 1] !== undefined &&
this.displayItems[this.displayItems.length - 1].isCategoryRow
) {
this.displayItems.splice(-1, 1);
}
// If the current page doesn't start with a category, check if the first item has a category and add it to the list
if (
this.displayItems[0] !== undefined &&
!this.displayItems[0].isCategoryRow
) {
if (
this.displayItems[0].category !== '' ||
this.displayItems[0].category !== undefined
) {
this.displayItems = [
{
id: this.displayItems[0].category,
category: this.displayItems[0].category,
isCategoryRow: true
},
...this.displayItems
];
}
}
}
openEnumerationValues = record => {
this.stateHandler.Go('enumerationvalues', { dataModelId: this.parent.model, dataTypeId: this.parent.id, id: record.id}, {reload: true, location: true, notify: false});
};
add() {
const newRecord = {
id: 'temp-' + this.validator.guid(),
key: '',
value: '',
category: '',
isCategoryRow: false,
edit: {
id: '',
key: '',
value: '',
category: '',
errors: ''
},
inEdit: true,
inDelete: false,
isNew: true
};
if (this.displayItems === undefined) {
this.displayItems = [];
}
this.displayItems = this.displayItems.concat(newRecord);
this.editingService.setFromCollection(this.displayItems);
}
validate(record) {
let isValid = true;
record.edit.errors = [];
if (record.edit.key.trim().length === 0) {
record.edit.errors.key = 'Key can\'t be empty!';
isValid = false;
}
if (record.edit.value.trim().length === 0) {
record.edit.errors.value = 'Value can\'t be empty!';
isValid = false;
}
if (
this.allRecordsWithGroups !== null &&
this.allRecordsWithGroups !== undefined
) {
for (const recordWithGroup of this.allRecordsWithGroups) {
if (!recordWithGroup) {
continue;
}
if (
recordWithGroup.isCategoryRow ||
record.id === recordWithGroup.id
) {
continue;
}
if (
recordWithGroup.key.toLowerCase().trim() ===
record.edit.key.toLowerCase().trim()
) {
record.edit.errors.key = 'Key already exists';
isValid = false;
}
}
}
if (isValid) {
delete record.edit.errors;
}
return isValid;
}
editClicked(record) {
record.edit = Object.assign({}, record);
record.edit.errors = [];
record.inEdit = true;
this.editingService.setFromCollection(this.displayItems);
}
deleteClicked(record) {
record.inDelete = true;
}
confirmDeleteClicked(record) {
if (this.clientSide) {
let i = this.allRecords.length - 1;
while (i >= 0) {
if (this.allRecords[i].id === record.id) {
this.allRecords.splice(i, 1);
}
i--;
}
this.showRecords([].concat(this.allRecords));
} else {
this.resourcesService.enumerationValues.removeFromEnumeratedType(this.parent.model, this.parent.id, record.id).subscribe(() => {
this.messageHandler.showSuccess('Enumeration deleted successfully.');
// reload all enums
this.reloadRecordsFromServer().subscribe((data) => {
this.showRecords(data.body.enumerationValues);
});
}, error => {
this.messageHandler.showError('There was a problem deleting the enumeration.', error);
});
}
if (this.onUpdate) {
this.onUpdate(this.allRecords);
}
}
cancelDeleteClicked(record) {
record.inDelete = false;
}
cancelEditClicked(record) {
this.editingService.confirmCancelAsync().subscribe(confirm => {
if (!confirm) {
return;
}
if (record.isNew && this.allRecords) {
let i = this.allRecords.length - 1;
while (i >= 0) {
if (this.allRecords[i].id === record.id) {
this.allRecords.splice(i, 1);
}
i--;
}
this.showRecords([].concat(this.allRecords));
}
record.inEdit = false;
this.editingService.setFromCollection(this.displayItems);
});
}
saveClicked(record) {
if (!this.validate(record)) {
return;
}
record.edit.errors = [];
const resource = {
key: record.edit.key,
value: record.edit.value,
category: record.edit.category
};
// if clientSide is true, it should not pass details to the server
// this is used in wizard for adding metadata items when creating a new model,class or element
if (this.clientSide) {
record.key = resource.key;
record.value = resource.value;
record.category = resource.category;
record.inEdit = false;
record.isNew = false;
this.editingService.setFromCollection(this.displayItems);
// New Record
if (record.id.indexOf('temp-') === 0) {
// find max index
let maxIndex = -1;
this.allRecords.forEach(item => {
if (item.index > maxIndex) {
maxIndex = item.index;
}
});
record.index = maxIndex + 1;
record.edit.index = maxIndex + 1;
// remove the "temp-" prefix of the id
record.id = record.id.replace('temp-', '');
const newRecs = [].concat(this.allRecords);
newRecs.push(record);
this.showRecords(newRecs);
}
const allRecs = [].concat(this.allRecords);
this.showRecords(allRecs);
if (this.onUpdate) {
this.onUpdate(this.allRecords);
}
return;
}
// in edit mode, we save them here
if (record.id && record.id.indexOf('temp-') !== 0) {
this.resourcesService.enumerationValues.updateInEnumeratedType(this.parent.model, this.parent.id, record.id, resource).subscribe(() => {
if (this.afterSave) {
this.afterSave.emit(resource);
}
record.key = resource.key;
record.value = resource.value;
record.category = resource.category;
record.inEdit = false;
this.editingService.setFromCollection(this.displayItems);
this.reloadRecordsFromServer().subscribe((data) => {
this.showRecords(data.body.enumerationValues);
});
this.messageHandler.showSuccess('Enumeration updated successfully.');
}, error => {
this.messageHandler.showError('There was a problem updating the enumeration.', error);
});
} else {
this.resourcesService.enumerationValues.saveToEnumeratedType(this.parent.model, this.parent.id, resource).subscribe(() => {
this.reloadRecordsFromServer().subscribe(data => {
this.showRecords(data.body.enumerationValues);
});
this.messageHandler.showSuccess('Enumeration saved successfully.');
}, error => {
this.messageHandler.showError('There was a problem saving the enumeration.', error);
});
}
}
onCategorySelect(selectedValue, record) {
if (selectedValue == null || (selectedValue && selectedValue.key === -1)) {
return;
}
record.category = selectedValue.key;
}
onCategoryTextUpdated(text, record) {
record.category = text;
}
reloadRecordsFromServer() {
return this.resourcesService.dataType.get(this.parent.model, this.parent.id);
}
pageSizeClicked(paginator) {
this.pageSize = paginator.pageSize;
this.currentPage = paginator.pageIndex;
this.showRecords(this.allRecords);
}
}
|
MauroDataMapper/mdm-ui
|
src/app/admin/user/user.component.ts
|
<gh_stars>1-10
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, OnInit } from '@angular/core';
import { MdmResourcesService } from '@mdm/modules/resources';
import { Title } from '@angular/platform-browser';
import { ROLES } from '@mdm/constants/roles';
import { StateHandlerService } from '@mdm/services/handlers/state-handler.service';
import { StateService } from '@uirouter/core';
import { MessageHandlerService } from '@mdm/services/utility/message-handler.service';
import { ValidatorService } from '@mdm/services/validator.service';
import { GridService } from '@mdm/services/grid.service';
import { EditingService } from '@mdm/services/editing.service';
import { Uuid } from '@maurodatamapper/mdm-resources';
@Component({
selector: 'mdm-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.scss']
})
export class UserComponent implements OnInit {
id: Uuid;
result = [];
allGroups = [];
selectedGroups = [];
errors = {
id: null,
emailAddress: '',
firstName: '',
lastName: '',
organisation: '',
jobTitle: '',
userRole: 'EDITOR',
groups: []
};
user = {
id: null,
emailAddress: '',
firstName: '',
lastName: '',
organisation: '',
jobTitle: '',
userRole: 'EDITOR',
groups: []
};
roles: any[];
constructor(
private role: ROLES,
private title: Title,
private resourcesService: MdmResourcesService,
private stateSvc: StateService,
private messageHandler: MessageHandlerService,
private validator: ValidatorService,
private stateHandler: StateHandlerService,
private gridService: GridService,
private editingService: EditingService) { }
ngOnInit() {
this.editingService.start();
this.title.setTitle('Admin - Add User');
this.roles = this.role.notPendingArray;
// tslint:disable-next-line: deprecation
this.id = this.stateSvc.params.id;
if (this.id) {
this.resourcesService.catalogueUser.get(this.id).subscribe(res => {
const user = res.body;
this.user = user;
this.title.setTitle('Admin - Edit User');
if (this.user.groups) {
for (const val of this.user.groups) {
this.selectedGroups.push(val.id);
}
}
});
}
const options = this.gridService.constructOptions(null, null, 'name', 'asc');
options['all'] = true;
this.resourcesService.userGroups.list(options).subscribe(res => {
this.allGroups = res.body.items;
}, error => {
this.messageHandler.showError('There was a problem getting the group list', error);
}
);
}
validateEmail = () => {
let isValid = true;
if (!this.user.emailAddress.trim().length) {
this.errors.emailAddress = 'Email can\'t be empty!';
isValid = false;
}
if (isValid) {
const parts = this.user.emailAddress.split('@');
const username = parts[0];
const delimiters = ['.', '-', '_'];
let fname = '';
let lname = '';
delimiters.forEach((key) => {
const partsName = username.replace(/\d+/g, '');
const num = partsName.indexOf(key);
if (num > -1) {
fname = partsName.substring(0, (num));
lname = partsName.substring(num + 1, (partsName.length));
fname = fname.toLowerCase();
lname = lname.toLowerCase();
fname = fname.charAt(0).toUpperCase() + fname.slice(1);
lname = lname.charAt(0).toUpperCase() + lname.slice(1);
}
});
this.user.lastName = lname;
this.user.firstName = fname;
}
};
validate = () => {
let isValid = true;
if (!this.user.emailAddress.trim().length) {
this.errors.emailAddress = 'Email can\'t be empty!';
isValid = false;
}
if (this.user.emailAddress && !this.validator.validateEmail(this.user.emailAddress)) {
this.errors.emailAddress = 'Invalid Email';
isValid = false;
}
if (!this.user.firstName.trim().length) {
this.errors.firstName = 'First Name can\'t be empty!';
isValid = false;
}
if (!this.user.lastName.trim().length) {
this.errors.lastName = 'Last Name can\'t be empty!';
isValid = false;
}
if (isValid) {
delete this.errors;
}
return isValid;
};
save = () => {
if (this.validate()) {
const resource = {
emailAddress: this.user.emailAddress,
firstName: this.user.firstName,
lastName: this.user.lastName,
organisation: this.user.organisation,
jobTitle: this.user.jobTitle,
groups: this.user.groups || []
};
// it's in edit mode
if (this.user.id) {
// it's in edit mode (update)
this.resourcesService.catalogueUser.update(this.user.id as Uuid, resource).subscribe(() => {
this.messageHandler.showSuccess('User updated successfully.');
this.navigateToParent();
}, error => {
this.messageHandler.showError('There was a problem updating the user.', error);
});
} else {
// it's in new mode (create)
this.resourcesService.catalogueUser.adminRegister(resource).subscribe(() => {
this.messageHandler.showSuccess('User saved successfully.');
this.navigateToParent();
},
error => {
this.messageHandler.showError('There was a problem saving the user.', error);
});
}
}
};
cancel = () => {
this.editingService.confirmCancelAsync().subscribe(confirm => {
if (confirm) {
this.navigateToParent();
}
});
};
onGroupSelect = (groups) => {
this.user.groups = [];
for (const val of this.allGroups) {
if (groups.value.includes(val.id)) {
this.user.groups.push(
val.id
// label: val.label
);
}
}
};
private navigateToParent() {
this.editingService.stop();
this.stateHandler.Go('admin.users');
}
}
|
MauroDataMapper/mdm-ui
|
src/app/pipes/byte-array-to-base64.pipe.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'byteArrayToBase64'
})
export class ByteArrayToBase64Pipe implements PipeTransform {
transform(value: any): any {
let binary = '';
const bytes = new Uint8Array(value);
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
}
|
MauroDataMapper/mdm-ui
|
src/app/services/highlight.service.ts
|
<filename>src/app/services/highlight.service.ts
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Injectable, Inject } from '@angular/core';
import { PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
// import 'clipboard';
import 'prismjs';
import 'prismjs/plugins/toolbar/prism-toolbar';
import 'prismjs/plugins/copy-to-clipboard/prism-copy-to-clipboard';
import 'prismjs/components/prism-css';
import 'prismjs/components/prism-json';
import 'prismjs/components/prism-javascript';
import 'prismjs/components/prism-java';
import 'prismjs/components/prism-markup';
import 'prismjs/components/prism-typescript';
import 'prismjs/components/prism-sass';
import 'prismjs/components/prism-scss';
declare let prism: any;
@Injectable()
export class HighlightService {
constructor(@Inject(PLATFORM_ID) private platformId: object) { }
highlightAll() {
if (isPlatformBrowser(this.platformId)) {
prism.highlightAll();
}
}
}
|
MauroDataMapper/mdm-ui
|
src/app/diagram/services/basic-diagram.service.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Injectable, Optional } from '@angular/core';
import * as joint from 'jointjs';
import { BehaviorSubject, Observable, Subject } from 'rxjs';
import dagre from 'dagre';
import graphlib from 'graphlib';
import { MdmResourcesService } from '@mdm/modules/resources';
import { MessageHandlerService } from '@mdm/services/utility/message-handler.service';
import _ from 'lodash';
import { DiagramParameters } from '../diagram/diagram.model';
@Injectable({
providedIn: 'root'
})
/* eslint-disable @typescript-eslint/member-ordering */
/* eslint-disable @typescript-eslint/no-unused-vars */
export abstract class BasicDiagramService {
fontColorWhite = '#ffffff';
darkBackground = '#4a708b';
lightBackground = '#e0e5e9';
lightOrangeBackground = '#f7a900';
shadedOrange = '#fec994';
linkColor: '#949494';
hierarchy: any;
public graph: joint.dia.Graph;
protected clickSubject = new Subject<any>();
protected goUpSubject = new Subject<any>();
protected dataComponentSubject = new BehaviorSubject('');
public currentComponent = this.dataComponentSubject.asObservable();
public constructor(protected resourcesService: MdmResourcesService,
protected messageHandler: MessageHandlerService) {
this.graph = new joint.dia.Graph();
}
abstract canGoUp(): boolean;
abstract goUp(): void;
abstract getDiagramContent(params: DiagramParameters): Observable<any>;
abstract render(data: any): void;
abstract configurePaper(paper: joint.dia.Paper): void;
public updateDataClassComponentLevel(data: any): void { }
public updateDataElementLevel(data: any): void { }
public onDrag(cellView: joint.dia.CellView): void {
if (cellView instanceof joint.dia.ElementView) {
this.adjustVertices(this.graph, (cellView).model);
}
}
public layoutNodes(rankDir: 'TB' | 'BT' | 'LR' | 'RL' = 'LR'): void {
let nodeSep = 100;
let rankSep = 400;
if (rankDir === 'TB') {
nodeSep = 100;
rankSep = 250;
}
joint.layout.DirectedGraph.layout(this.graph, {
setLabels: true,
setVertices: true,
setLinkVertices: true,
dagre,
graphlib,
rankDir,
marginX: 40,
marginY: 40,
nodeSep: 100,
rankSep: 400,
edgeSep: 0
});
}
protected addCylinderCell(id: string, label: string): joint.dia.Cell {
const cylinder = new joint.shapes.standard.Cylinder({
id,
size: { width: 120, height: 80 },
});
cylinder.attr('label/text', joint.util.breakText(label, { width: 110 }));
// cylinder.attr('label/text', label);
cylinder.attr('label/fontWeight', 'bold');
cylinder.attr('label/fontSize', 12);
cylinder.attr('label/fill', this.fontColorWhite);
cylinder.attr('body/fill', this.darkBackground);
cylinder.attr('body/strokeWidth', 0);
cylinder.attr('top/fill', this.lightBackground);
cylinder.attr('text/ref-y', -50);
this.graph.addCell(cylinder);
return cylinder;
}
protected addRectangleCell(id: string, label: string, width: number = 120, height: number = 80, textWidth: number = 110): joint.dia.Cell {
const rectangle = new joint.shapes.standard.Rectangle({
id,
size: { width, height }
});
rectangle.attr('label/text', joint.util.breakText(label, { width: textWidth }));
rectangle.attr('label/fontWeight', 'bold');
rectangle.attr('label/fontSize', 12);
rectangle.attr('label/fill', this.fontColorWhite);
rectangle.attr('body/fill', this.darkBackground);
rectangle.attr('body/strokeWidth', 0);
rectangle.attr('body/rx', 10);
rectangle.attr('body/ry', 10);
// rectangle.attr('text/ref-y', -50);
this.graph.addCell(rectangle);
return rectangle;
}
protected addColoredRectangleCell(textColor: string, rectangleColor: string, id: string, label: string, width: number = 120, height: number = 80, textWidth: number = 110): joint.dia.Cell {
const rectangle = new joint.shapes.standard.Rectangle({
id,
size: { width, height }
});
rectangle.attr('label/text', joint.util.breakText(label, { width: textWidth }));
rectangle.attr('label/fontWeight', 'bold');
rectangle.attr('label/fontSize', 12);
rectangle.attr('label/fill', textColor);
rectangle.attr('body/fill', rectangleColor);
rectangle.attr('body/strokeWidth', 0);
rectangle.attr('body/rx', 10);
rectangle.attr('body/ry', 10);
this.graph.addCell(rectangle);
return rectangle;
}
protected addSmallRectangleCell(id: string, label: string): joint.dia.Cell {
const rectangle = new joint.shapes.standard.Rectangle({
id,
size: { width: 150, height: 40 }
});
rectangle.attr('label/text', joint.util.breakText(label, { width: 130 }));
rectangle.attr('label/fontWeight', 'bold');
rectangle.attr('label/fontSize', 12);
rectangle.attr('body/fill', this.lightBackground);
rectangle.attr('body/strokeWidth', 0);
rectangle.attr('body/rx', 10);
rectangle.attr('body/ry', 10);
// rectangle.attr('text/ref-y', -50);
this.graph.addCell(rectangle);
return rectangle;
}
protected addLink(id: string, sourceId: string, targetId: string): joint.dia.Link {
const link = new joint.shapes.standard.Link({
id,
source: { id: sourceId },
target: { id: targetId }
});
link.attr('line/stroke', this.darkBackground);
link.connector('rounded', { radius: 40 });
link.toBack();
this.graph.addCell(link);
return link;
}
protected addSmallColorfulRectangleCell(id: string, label: string): joint.dia.Cell {
const rectangle = new joint.shapes.standard.Rectangle({
id,
size: { width: 150, height: 40 }
});
rectangle.attr('label/text', joint.util.breakText(label, { width: 130 }));
rectangle.attr('label/fontWeight', 'bold');
rectangle.attr('label/fontSize', 12);
rectangle.attr('body/fill', this.lightOrangeBackground);
rectangle.attr('body/strokeWidth', 0);
rectangle.attr('body/rx', 10);
rectangle.attr('body/ry', 10);
// rectangle.attr('text/ref-y', -50);
this.graph.addCell(rectangle);
return rectangle;
}
protected addUmlClassCell(id: string, label: string, attributes: Array<any>,
@Optional() position: joint.g.Point = null,
@Optional() existingClassBox: joint.shapes.standard.Rectangle): joint.dia.Cell {
const cells: Array<joint.dia.Cell> = [];
if (!position) {
position = new joint.g.Point({ x: 0, y: 0 });
}
let classBox = null;
if (existingClassBox) {
classBox = existingClassBox;
position = existingClassBox.position();
// classBox.attr('body/fill', this.lightBackground);
classBox.attr('body/fillOpacity', 0);
classBox.attr('z', 2);
} else {
classBox = new joint.shapes.standard.Rectangle({
id,
position,
z: 2,
size: { width: 300, height: attributes.length * 25 + 31 },
attrs: {
body: {
fill: this.lightBackground,
fillOpacity: 0
}
}
});
classBox.attr('rect/fontWeight', 'bold');
cells.push(classBox);
}
const classNameBox = new joint.shapes.standard.Rectangle({
id: id + '-name',
position,
size: { width: 300, height: 30 },
z: 1,
attrs: {
label: {
text: joint.util.breakText(label, { width: 290 }),
fontWeight: 'bold',
fill: this.fontColorWhite,
fontSize: 13
},
body: {
fill: this.darkBackground,
strokeWidth: 0,
stroke: this.darkBackground
}
}
});
classBox.embed(classNameBox);
cells.push(classNameBox);
attributes.forEach((attribute, idx) => {
const attributeBox = new joint.shapes.standard.Rectangle({
position: { x: position.x, y: position.y + 31 + idx * 25 },
id: attribute.id,
size: { width: 300, height: 25 },
z: 1,
attrs: {
label: {
text: joint.util.breakText(`${attribute.label} : ${attribute.dataType.label}`, { width: 280 }),
fontWeight: 'normal',
fontSize: 12,
textAnchor: 'left',
refX: 10
},
body: {
fill: this.lightBackground,
strokeWidth: 0
},
}
});
// attributeBox.addPort();
classBox.embed(attributeBox);
cells.push(attributeBox);
});
this.graph.addCells(cells);
return classBox;
}
/*
private adjustAllVertices(graph: joint.dia.Graph) {
graph.getCells().forEach((cell) => {
if (cell instanceof joint.dia.Link) {
this.adjustVertices(graph, cell);
}
});
}
*/
private adjustVertices(graph: joint.dia.Graph, cell: joint.dia.Cell) {
// if `cell` is a view, find its model
// cell = cell.model || cell;
if (cell instanceof joint.dia.Element) {
// `cell` is an element
_.chain(graph.getConnectedLinks(cell))
.groupBy((link) => {
// the key of the group is the model id of the link's source or target
// cell id is omitted
return _.omit([link.source().id, link.target().id], cell.id)[0];
})
.each((group, key) => {
// if the member of the group has both source and target model
// then adjust vertices
if (key !== 'undefined') {
this.adjustVertices(graph, _.first(group));
}
})
.value();
return;
}
// `cell` is a link
// get its source and target model IDs
const sourceId = cell.get('source').id || cell.previous('source').id;
const targetId = cell.get('target').id || cell.previous('target').id;
// if one of the ends is not a model
// (if the link is pinned to paper at a point)
// the link is interpreted as having no siblings
if (!sourceId || !targetId) {
return;
}
// identify link siblings
const siblings = graph.getLinks().filter((sibling: joint.dia.Link) => {
const siblingSourceId = sibling.source().id;
const siblingTargetId = sibling.target().id;
// if source and target are the same
// or if source and target are reversed
return ((siblingSourceId === sourceId) && (siblingTargetId === targetId))
|| ((siblingSourceId === targetId) && (siblingTargetId === sourceId));
});
const numSiblings = siblings.length;
switch (numSiblings) {
case 0: {
// the link has no siblings
break;
}
case 1: {
// there is only one link
// no vertices needed
// cell.unset('vertices');
break;
}
default: {
// there are multiple siblings
// we need to create vertices
// find the middle point of the link
const sourceCenter = graph.getCell(sourceId).getBBox().center();
const targetCenter = graph.getCell(targetId).getBBox().center();
const midPoint = new joint.g.Line(sourceCenter, targetCenter).midpoint();
// find the angle of the link
const theta = sourceCenter.theta(targetCenter);
// constant
// the maximum distance between two sibling links
const gap = 30;
siblings.forEach((sibling, index) => {
// we want offset values to be calculated as 0, 20, 20, 40, 40, 60, 60 ...
let offset = gap * Math.ceil(index / 2);
// place the vertices at points which are `offset` pixels perpendicularly away
// from the first link
//
// as index goes up, alternate left and right
//
// ^ odd indices
// |
// |----> index 0 sibling - centerline (between source and target centers)
// |
// v even indices
const sign = ((index % 2) ? 1 : -1);
// to assure symmetry, if there is an even number of siblings
// shift all vertices leftward perpendicularly away from the centerline
if ((numSiblings % 2) === 0) {
offset -= ((gap / 2) * sign);
}
// make reverse links count the same as non-reverse
const reverse = ((theta < 180) ? 1 : -1);
// we found the vertex
const angle = joint.g.toRad(theta + (sign * reverse * 90));
const vertex = joint.g.Point.fromPolar(offset, angle, midPoint);
// replace vertices array with `vertex`
sibling.vertices([vertex]);
});
}
}
}
getClickSubject(): Subject<any> {
return this.clickSubject;
}
getGoUpSubject(): Subject<any> {
return this.goUpSubject;
}
getComponentSubject(): Subject<any> {
return this.dataComponentSubject;
}
changeComponent(dataClassComponent: any) {
this.dataComponentSubject.next(dataClassComponent);
}
}
|
MauroDataMapper/mdm-ui
|
src/app/modules/resources/mdm-resources.module.ts
|
<gh_stars>1-10
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { NgModule, Optional, SkipSelf } from '@angular/core';
import { MdmResourcesConfiguration } from '@maurodatamapper/mdm-resources';
import { MdmResourcesService } from './mdm-resources.service';
import { MdmRestHandlerService } from './mdm-rest-handler.service';
/**
* A wrapper Angular module for @mdm-api/resources
*/
@NgModule({
providers: [
MdmResourcesService,
MdmRestHandlerService
]
})
export class MdmResourcesModule {
constructor(@Optional() @SkipSelf() parentModule?: MdmResourcesModule) {
if (parentModule) {
throw new Error(
'MdmResourcesModule is already loaded. Import it in the AppModule only');
}
}
// Support customization of apiEndpoint
static forRoot(config: MdmResourcesConfiguration) {
return {
ngModule: MdmResourcesModule,
providers: [
{provide: MdmResourcesConfiguration, useValue: config }
]
};
}
}
|
MauroDataMapper/mdm-ui
|
src/app/utility/element-link/element-link.component.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { getCatalogueItemDomainTypeIcon } from '@mdm/folders-tree/flat-node';
import { ElementTypesService } from '@mdm/services/element-types.service';
@Component({
selector: 'mdm-element-link',
templateUrl: './element-link.component.html',
})
export class ElementLinkComponent implements OnInit {
@Input() hideVersionNumber: boolean;
@Input() justShowCodeForTerm: boolean;
@Input() showTypeTitle: boolean;
@Input() showTypeIcon = false;
@Input() newWindow: boolean;
@Input() parentDataModel: any;
@Input() parentDataClass: any;
@Input() showHref = true;
@Input() showParentDataModelName: boolean;
@Input() showLink = true;
@Output() selectedElementsChange = new EventEmitter<any[]>();
elementVal: any;
linkUrl: string;
@Input()
get element() {
return this.elementVal;
}
set element(val) {
this.elementVal = val;
this.selectedElementsChange.emit(this.elementVal);
this.ngOnInit();
}
label: string;
versionNumber: string;
openLinkLocation: string;
elementTypeTitle: string;
types: any[];
replaceLabelBy: any;
disableLink: any;
constructor(private elementTypes: ElementTypesService) {}
ngOnInit() {
this.label = '';
this.versionNumber = '';
this.linkUrl = this.elementTypes.getLinkUrl(this.element);
if (!this.hideVersionNumber) {
this.versionNumber = this.element?.documentationVersion ? `Documentation Version: ${this.element.documentationVersion}` : '';
}
this.label = this.element?.label || this.element?.definition;
if (this.element?.domainType === 'Term' && !this.justShowCodeForTerm) {
this.label = `${this.element.label}`;
}
if (this.element?.domainType === 'Term' && this.justShowCodeForTerm) {
this.label = this.element.label;
}
if (this.replaceLabelBy) {
this.label = this.replaceLabelBy;
}
if (this.showParentDataModelName && this.element?.domainType !== 'DataModel' && this.element?.domainType !== 'Term' && this.element?.domainType !== 'Terminology') {
const parentDM = this.element?.breadcrumbs && this.element?.breadcrumbs.length > 0 ? this.element?.breadcrumbs[0] : null;
this.label = parentDM?.label ? (`${parentDM?.label} : ${this.label}`) : this.label;
if (this.label === 'undefined : undefined') {
this.label = '';
}
}
this.initTypeLabel();
this.initLink();
}
public initTypeLabel(): any {
this.elementTypeTitle = '';
this.types = this.elementTypes.getTypes();
if (
this.element &&
this.element.domainType &&
this.types.filter(x => x.id === this.element.domainType)
) {
this.elementTypeTitle = this.types.filter(
x => x.id === this.element.domainType
)[0].title;
}
}
public initLink() {
this.openLinkLocation = '_self';
if (this.newWindow) {
this.openLinkLocation = '_blank';
}
// if it's true or it's NOT mentioned then make it true
if (
this.showLink === true ||
this.showLink ||
this.showLink === undefined
) {
this.showLink = true;
}
}
getIcon() {
return getCatalogueItemDomainTypeIcon(this.element.domainType);
}
hasIcon() {
return getCatalogueItemDomainTypeIcon(this.element.domainType) !== null;
}
}
|
MauroDataMapper/mdm-ui
|
src/app/pipes/marked.pipe.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Pipe, PipeTransform } from '@angular/core';
import marked from 'marked/lib/marked';
/**
* A utility to do simple markdown parsing.
*
* Usage: <span [innerHTML]="value | marked:<options>"></span>
*/
@Pipe({ name: 'marked' })
export class MarkedPipe implements PipeTransform {
transform(value: string, options = {}) {
if (value) {
const md = marked.setOptions(options);
return md.parse(value);
}
return value;
}
}
|
MauroDataMapper/mdm-ui
|
src/app/referenceData/reference-data-details/reference-data-details.component.ts
|
<reponame>MauroDataMapper/mdm-ui
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { MdmResourcesService } from '@mdm/modules/resources';
import { Component, OnInit, Input } from '@angular/core';
import { EMPTY } from 'rxjs';
import { SecurityHandlerService } from '@mdm/services/handlers/security-handler.service';
import { MessageHandlerService } from '@mdm/services/utility/message-handler.service';
import { StateHandlerService } from '@mdm/services/handlers/state-handler.service';
import { SharedService } from '@mdm/services/shared.service';
import { ExportHandlerService } from '@mdm/services/handlers/export-handler.service';
import { BroadcastService } from '@mdm/services/broadcast.service';
import { MatDialog } from '@angular/material/dialog';
import { Title } from '@angular/platform-browser';
import { EditingService } from '@mdm/services/editing.service';
import {
FinaliseModalComponent,
FinaliseModalResponse
} from '@mdm/modals/finalise-modal/finalise-modal.component';
import { catchError, finalize } from 'rxjs/operators';
import { VersioningGraphModalComponent } from '@mdm/modals/versioning-graph-modal/versioning-graph-modal.component';
import { ModalDialogStatus } from '@mdm/constants/modal-dialog-status';
import {
CatalogueItemDomainType,
ModelUpdatePayload,
ReferenceDataModelDetail,
ReferenceDataModelDetailResponse
} from '@maurodatamapper/mdm-resources';
import { ValidatorService } from '@mdm/services';
import { Access } from '@mdm/model/access';
@Component({
selector: 'mdm-reference-data-details',
templateUrl: './reference-data-details.component.html',
styleUrls: ['./reference-data-details.component.scss']
})
export class ReferenceDataDetailsComponent implements OnInit {
@Input() refDataModel: ReferenceDataModelDetail;
originalRefDataModel: ReferenceDataModelDetail;
showEdit = false;
isAdminUser: boolean;
isLoggedIn: boolean;
deleteInProgress: boolean;
exporting: boolean;
errorMessage = '';
processing = false;
exportError = null;
exportList = [];
compareToList = [];
downloadLinks = new Array<HTMLAnchorElement>();
access: Access;
constructor(
private resourcesService: MdmResourcesService,
private messageHandler: MessageHandlerService,
private securityHandler: SecurityHandlerService,
private stateHandler: StateHandlerService,
private sharedService: SharedService,
private broadcast: BroadcastService,
private dialog: MatDialog,
private exportHandler: ExportHandlerService,
private title: Title,
private editingService: EditingService,
private validatorService: ValidatorService
) {}
ngOnInit() {
this.isAdminUser = this.sharedService.isAdmin;
this.isLoggedIn = this.securityHandler.isLoggedIn();
this.loadExporterList();
this.ReferenceModelDetails();
this.originalRefDataModel = Object.assign({}, this.refDataModel);
}
ReferenceModelDetails(): any {
if (this.refDataModel.semanticLinks) {
this.refDataModel.semanticLinks.forEach((link) => {
if (link.linkType === 'New Version Of') {
this.compareToList.push(link.target);
}
});
}
if (this.refDataModel.semanticLinks) {
this.refDataModel.semanticLinks.forEach((link) => {
if (link.linkType === 'Superseded By') {
this.compareToList.push(link.target);
}
});
}
this.access = this.securityHandler.elementAccess(this.refDataModel);
this.title.setTitle(
`${this.refDataModel?.type} - ${this.refDataModel?.label}`
);
}
restore() {
if (!this.isAdminUser || !this.refDataModel.deleted) {
return;
}
this.processing = true;
this.resourcesService.referenceDataModel
.undoSoftDelete(this.refDataModel.id)
.pipe(
catchError((error) => {
this.messageHandler.showError(
'There was a problem restoring the Reference Data Model.',
error
);
return EMPTY;
}),
finalize(() => {
this.processing = false;
})
)
.subscribe(() => {
this.messageHandler.showSuccess(
`The Reference Data Model "${this.refDataModel.label}" has been restored.`
);
this.stateHandler.reload();
this.broadcast.reloadCatalogueTree();
});
}
finalise() {
this.resourcesService.referenceDataModel
.latestModelVersion(this.refDataModel.id)
.subscribe((response) => {
const dialog = this.dialog.open<
FinaliseModalComponent,
any,
FinaliseModalResponse
>(FinaliseModalComponent, {
data: {
modelVersion: response.body.modelVersion,
title: 'Finalise Reference Data Model',
okBtnTitle: 'Finalise Reference Data Model',
btnType: 'accent',
message: `<p class='marginless'>Please select the version you would like this Reference Data Model</p>
<p>to be finalised with: </p>`
}
});
dialog.afterClosed().subscribe((dialogResult) => {
if (dialogResult?.status !== ModalDialogStatus.Ok) {
return;
}
this.processing = true;
this.resourcesService.referenceDataModel
.finalise(this.refDataModel.id, dialogResult.request)
.subscribe(
() => {
this.processing = false;
this.messageHandler.showSuccess(
'Reference Data Model finalised successfully.'
);
this.stateHandler.Go(
'referencedatamodel',
{ id: this.refDataModel.id },
{ reload: true }
);
},
(error) => {
this.processing = false;
this.messageHandler.showError(
'There was a problem finalising the Data Model.',
error
);
}
);
});
});
}
toggleSecuritySection() {
this.dialog.openSecurityAccess(this.refDataModel, 'referenceDataModel');
}
delete(permanent: boolean) {
if (!this.access.showDelete) {
return;
}
this.deleteInProgress = true;
this.resourcesService.referenceDataModel
.remove(this.refDataModel.id, { permanent })
.subscribe(
() => {
this.broadcast.reloadCatalogueTree();
if (permanent) {
this.stateHandler.Go(
'allDataModel',
{ reload: true, location: true },
null
);
} else {
this.stateHandler.reload();
}
},
(error) => {
this.deleteInProgress = false;
this.messageHandler.showError(
'There was a problem deleting the Reference Data Model.',
error
);
}
);
}
askForSoftDelete() {
if (!this.access.showSoftDelete) {
return;
}
this.dialog
.openConfirmationAsync({
data: {
title: 'Are you sure you want to delete this Reference Data Model?',
okBtnTitle: 'Yes, delete',
btnType: 'warn',
message: `<p class="marginless">This Reference Data Model will be marked as deleted and will not be viewable by users </p>
<p class="marginless">except Administrators.</p>`
}
})
.subscribe(() => {
this.processing = true;
this.delete(false);
this.processing = false;
});
}
askForPermanentDelete(): any {
if (!this.access.showPermanentDelete) {
return;
}
this.dialog
.openDoubleConfirmationAsync(
{
data: {
title: 'Permanent deletion',
okBtnTitle: 'Yes, delete',
btnType: 'warn',
message:
'Are you sure you want to <span class=\'warning\'>permanently</span> delete this Reference Data Model?'
}
},
{
data: {
title: 'Confirm permanent deletion',
okBtnTitle: 'Confirm deletion',
btnType: 'warn',
message: `<p class='marginless'><strong>Note: </strong>All its 'Types', 'Elements' and 'Data Values'
<p class='marginless'>will be deleted <span class='warning'>permanently</span>.</p>`
}
}
)
.subscribe(() => this.delete(true));
}
save() {
this.showEdit = false;
this.errorMessage = '';
const resource: ModelUpdatePayload = {
id: this.refDataModel.id,
domainType: CatalogueItemDomainType.ReferenceDataModel,
label: this.refDataModel.label
};
if (this.validatorService.validateLabel(this.refDataModel.label)) {
this.resourcesService.referenceDataModel
.update(this.refDataModel.id, resource)
.subscribe(
(res: ReferenceDataModelDetailResponse) => {
this.refDataModel = res.body;
this.ReferenceModelDetails();
this.messageHandler.showSuccess(
'Reference Data Model updated successfully.'
);
this.editingService.stop();
this.broadcast.reloadCatalogueTree();
},
(error) => {
this.messageHandler.showError(
'There was a problem updating the Reference Data Model.',
error
);
}
);
}
}
enableEdit() {
this.editingService.start();
this.showEdit = true;
}
cancel() {
this.refDataModel = Object.assign({}, this.originalRefDataModel);
this.errorMessage = '';
this.editingService.stop();
this.showEdit = false;
}
export(exporter) {
this.exportError = null;
this.processing = true;
this.exportHandler
.exportDataModel([this.refDataModel], exporter, 'referenceDataModels')
.subscribe(
(refDataModel) => {
if (refDataModel != null) {
const tempDownloadList = Object.assign([], this.downloadLinks);
const label =
[this.refDataModel].length === 1
? [this.refDataModel][0].label
: 'reference_models';
const fileName = this.exportHandler.createFileName(label, exporter);
const file = new Blob([refDataModel.body], {
type: exporter.fileType
});
const link = this.exportHandler.createBlobLink(file, fileName);
tempDownloadList.push(link);
this.downloadLinks = tempDownloadList;
this.processing = false;
} else {
this.processing = false;
this.messageHandler.showError(
'There was a problem exporting the Reference Data Model.',
''
);
}
},
(error) => {
this.processing = false;
this.messageHandler.showError(
'There was a problem exporting the Reference Data Model.',
error
);
}
);
}
loadExporterList() {
this.exportList = [];
this.securityHandler.isAuthenticated().subscribe((refDataModel) => {
if (!refDataModel.body.authenticatedSession) {
return;
}
this.resourcesService.referenceDataModel.exporters().subscribe(
(res) => {
this.exportList = res.body;
},
(error) => {
this.messageHandler.showError(
'There was a problem loading exporters list.',
error
);
}
);
});
}
newVersion() {
this.stateHandler.Go(
'newversionmodel',
{
id: this.refDataModel.id,
domainType: this.refDataModel.domainType
}
);
}
compare(referenceDataModel = null) {
this.stateHandler.NewWindow(
'modelscomparison',
{
sourceId: this.refDataModel.id,
targetId: referenceDataModel ? referenceDataModel.id : null
},
null
);
}
merge() {
if (this.sharedService.features.useMergeUiV2) {
return this.stateHandler.Go(
'mergediff',
{
sourceId: this.refDataModel.id,
catalogueDomainType: this.refDataModel.domainType
});
}
return this.stateHandler.Go(
'modelsmerging',
{
sourceId: this.refDataModel.id,
targetId: null
},
null
);
}
showMergeGraph() {
const dialog = this.dialog.open(VersioningGraphModalComponent, {
data: { parentDataModel: this.refDataModel.id },
panelClass: 'versioning-graph-modal'
});
dialog.afterClosed().subscribe((refDataModel) => {
if (refDataModel != null && refDataModel.status === 'ok') {
}
});
}
}
|
MauroDataMapper/mdm-ui
|
src/app/utility/markdown/markdown-parser/markdown-parser.service.ts
|
<reponame>MauroDataMapper/mdm-ui
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Injectable } from '@angular/core';
import { ElementTypesService } from '@mdm/services/element-types.service';
import marked from 'marked/lib/marked';
import { MdmResourcesService } from '@mdm/modules/resources';
import { BroadcastService } from '@mdm/services/broadcast.service';
import { CustomTokenizerService } from '@mdm/utility/markdown/markdown-parser/custom-tokenizer.service';
import { CustomHtmlRendererService } from '@mdm/utility/markdown/markdown-parser/custom-html-renderer.service';
import { CustomTextRendererService } from '@mdm/utility/markdown/markdown-parser/custom-text-renderer.service';
@Injectable({
providedIn: 'root'
})
export class MarkdownParserService {
constructor(private elementTypes: ElementTypesService,
private tokenizer: CustomTokenizerService,
private customHtmlRendererService: CustomHtmlRendererService,
private customTextRendererService: CustomTextRendererService,
private resourcesService: MdmResourcesService,
private broadcastSvc: BroadcastService) {
}
public parse(source: string, renderType : string) {
// Find only the text within brackets and replace the empty spaces with a special char ^ in order to be able to parse the markdown link
source = source?.replace(/\[([^\]]+)\]\(([^\)]+)\)/gm, ($0, $1, $2) => `[${$1}](${$2.replace(/\s/gm, '^')})`);
let renderer: marked.Renderer = this.customHtmlRendererService;
if (renderType === 'text') {
renderer = this.customTextRendererService;
}
marked.use({ tokenizer: this.tokenizer as any });
marked.setOptions({
renderer,
gfm: true,
breaks: true,
});
if (source) {
source = marked(source);
source = source?.replace('\\r\\n','');
return source;
}
}
public async createMarkdownLink(element) {
const baseTypes = this.elementTypes.getTypes();
const dataTypeNames = this.elementTypes.getTypesForBaseTypeArray('DataType').map((dt) => {
return dt.id;
});
let parentId = null;
if (element.domainType === 'DataClass') {
parentId = element.modelId;
}
if (!parentId && element.breadcrumbs) {
parentId = element.breadcrumbs[0].id;
}
let parentDataClassId = null;
if (element.parentDataClass) {
parentDataClassId = element.parentDataClass;
} else if (element.dataClass) {
parentDataClassId = element.dataClass;
} else if (element.breadcrumbs) {
parentDataClassId = element.breadcrumbs[element.breadcrumbs.length - 1].id;
}
let str = '';
if (element.domainType === 'DataClass') {
const dataModelName = await this.getDataModelName(parentId);
str = `[${element.label}](dm:${dataModelName}|${baseTypes.find(x => x.id === element.domainType).markdown}:${element.label}`;
}
if (element.domainType === 'DataModel') {
str = `[${element.label}](${baseTypes.find(x => x.id === element.domainType).markdown}:${element.label}`;
}
if (element.domainType === 'DataType' || dataTypeNames.includes(element.element?.domainType)) {
let dataModelName = '';
if (!parentId) {
parentId = element.element.model;
dataModelName = await this.getDataModelName(parentId);
str += `[${element.element.label}](dm:${dataModelName}|${baseTypes.find(x => x.id === element.element.domainType).markdown}:${element.element.label}`;
} else {
dataModelName = await this.getDataModelName(parentId);
str += `[${element.label}](dm:${dataModelName}|${baseTypes.find(x => x.id === element.domainType).markdown}:${element.label}`;
}
}
if (element.domainType === 'DataElement' || element.element?.domainType === 'DataElement') {
let dataModelName = '';
let dataClassName = '';
if (!parentId) {
parentId = element.element.model;
parentDataClassId = element.element.dataClass;
dataModelName = await this.getDataModelName(parentId);
dataClassName = await this.getDataClassName(parentId, parentDataClassId);
str += `[${element.element.label}](dm:${dataModelName}|dc:${dataClassName}|${baseTypes.find(x => x.id === element.element.domainType).markdown}:${element.element.label}`;
} else {
dataModelName = await this.getDataModelName(parentId);
dataClassName = await this.getDataClassName(parentId, parentDataClassId);
str += `[${element.label}](dm:${dataModelName}|dc:${dataClassName}|${baseTypes.find(x => x.id === element.domainType).markdown}:${element.label}`;
}
}
if (element.domainType === 'Term') {
const terminologyName = await this.getTerminologyName(parentId);
str += `[${element.label}](te:${terminologyName}|${baseTypes.find(x => x.id === element.domainType).markdown}:${element.label}`;
}
if (element.domainType === 'CodeSet') {
str = `[${element.label}](${baseTypes.find(x => x.id === element.domainType).markdown}:${element.label}`;
}
// Not supported at the moment. Keeping for further use.
// if (element.domainType === 'Folder') {
// str = `[${element.label}](${baseTypes.find(x => x.id === element.domainType).markdown}:${element.label}`;
// }
str += ')';
return str;
}
private async getDataModelName(id: any) {
const response = await this.resourcesService.dataModel.get(id).toPromise();
return response.body.label;
}
private async getTerminologyName(id: any) {
const response = await this.resourcesService.terminology.get(id).toPromise();
return response.body.label;
}
private async getDataClassName(dataModelId: any, id: any) {
const response = await this.resourcesService.dataClass.get(dataModelId, id).toPromise();
return response.body.label;
}
}
|
MauroDataMapper/mdm-ui
|
src/app/dataClass/data-class/data-class.component.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { AfterViewChecked, Component, OnInit, ViewChild } from '@angular/core';
import { MdmResourcesService } from '@mdm/modules/resources';
import { MessageService } from '@mdm/services/message.service';
import { SharedService } from '@mdm/services/shared.service';
import { UIRouterGlobals } from '@uirouter/core';
import { StateHandlerService } from '@mdm/services/handlers/state-handler.service';
import { Subscription } from 'rxjs';
import { MatTabGroup } from '@angular/material/tabs';
import { Title } from '@angular/platform-browser';
import { EditingService } from '@mdm/services/editing.service';
import {
MessageHandlerService,
SecurityHandlerService
} from '@mdm/services';
import {
DataClass,
DataClassDetail,
DataClassDetailResponse
} from '@maurodatamapper/mdm-resources';
import { Access } from '@mdm/model/access';
import { TabCollection } from '@mdm/model/ui.model';
import { DefaultProfileItem } from '@mdm/model/defaultProfileModel';
import { BaseComponent } from '@mdm/shared/base/base.component';
@Component({
selector: 'mdm-data-class',
templateUrl: './data-class.component.html',
styleUrls: ['./data-class.component.sass']
})
export class DataClassComponent
extends BaseComponent
implements OnInit, AfterViewChecked {
@ViewChild('tab', { static: false }) tabGroup: MatTabGroup;
dataClass: DataClassDetail;
showSecuritySection: boolean;
subscription: Subscription;
showSearch = false;
showExtraTabs = false;
activeTab: any;
parentDataClass = { id: null };
parentDataModel = {};
isEditable: boolean;
max: any;
min: any;
error = '';
aliases: any[] = [];
access: Access;
tabs = new TabCollection(['description', 'elements', 'context', 'data', 'rules', 'annotations', 'history']);
newMinText: any;
newMaxText: any;
descriptionView = 'default';
annotationsView = 'default';
showEditDescription = false;
constructor(
private resourcesService: MdmResourcesService,
private messageService: MessageService,
private uiRouterGlobals: UIRouterGlobals,
private sharedService: SharedService,
private stateHandler: StateHandlerService,
private securityHandler: SecurityHandlerService,
private title: Title,
private editingService: EditingService,
private messageHandler: MessageHandlerService
) {
super();
}
ngOnInit() {
if (
this.isGuid(this.uiRouterGlobals.params.id) &&
(!this.uiRouterGlobals.params.id ||
!this.uiRouterGlobals.params.dataModelId)
) {
this.stateHandler.NotFound({ location: false });
return;
}
if (
this.uiRouterGlobals.params.id &&
this.uiRouterGlobals.params.dataClassId &&
this.uiRouterGlobals.params.dataClassId.trim() !== ''
) {
this.parentDataClass = { id: this.uiRouterGlobals.params.dataClassId };
}
this.activeTab = this.tabs.getByName(this.uiRouterGlobals.params.tabView as string).index;
this.tabSelected(this.activeTab);
this.showExtraTabs = this.sharedService.isLoggedIn();
this.title.setTitle('Data Class');
this.subscription = this.messageService.changeSearch.subscribe(
(message: boolean) => {
this.showSearch = message;
}
);
this.dataClassDetails(
this.uiRouterGlobals.params.dataModelId,
this.uiRouterGlobals.params.id,
this.parentDataClass.id
);
}
ngAfterViewChecked(): void {
if (this.tabGroup && !this.editingService.isTabGroupClickEventHandled(this.tabGroup)) {
this.editingService.setTabGroupClickEvent(this.tabGroup);
}
}
dataClassDetails(model, id, parentDataClass?) {
if (!parentDataClass) {
this.resourcesService.dataClass
.get(model, id)
.subscribe((result: DataClassDetailResponse) => {
this.dataClass = result.body;
this.access = this.securityHandler.elementAccess(this.dataClass);
this.catalogueItem = this.dataClass;
this.isEditable = this.dataClass.availableActions?.includes('update');
this.parentDataModel = {
id: result.body.model,
finalised: this.dataClass.breadcrumbs[0].finalised
};
this.messageService.FolderSendMessage(this.dataClass);
this.messageService.dataChanged(this.dataClass);
if (
this.dataClass.minMultiplicity &&
this.dataClass.minMultiplicity === -1
) {
this.min = '*';
} else {
this.min = this.dataClass.minMultiplicity;
}
if (
this.dataClass.maxMultiplicity &&
this.dataClass.maxMultiplicity === -1
) {
this.max = '*';
} else {
this.max = this.dataClass.maxMultiplicity;
}
});
} else {
this.resourcesService.dataClass
.getChildDataClass(model, parentDataClass, id)
.subscribe((result: DataClassDetailResponse) => {
this.dataClass = result.body;
this.parentDataModel = {
id: result.body.model,
finalised: this.dataClass.breadcrumbs[0].finalised
};
this.isEditable = this.dataClass.availableActions?.includes('update');
this.messageService.FolderSendMessage(this.dataClass);
this.messageService.dataChanged(this.dataClass);
this.catalogueItem = this.dataClass;
this.access = this.securityHandler.elementAccess(this.dataClass);
});
}
}
save(saveItems: Array<DefaultProfileItem>) {
this.error = '';
const resource: DataClass = {
id: this.dataClass.id,
label: this.dataClass.label,
domainType: this.dataClass.domainType
};
saveItems.forEach((item: DefaultProfileItem) => {
if (item.maxMultiplicity !== undefined) {
if ((item.minMultiplicity as string) === '*') {
item.minMultiplicity = -1;
}
if ((item.maxMultiplicity as string) === '*') {
item.maxMultiplicity = -1;
}
resource.minMultiplicity = item.minMultiplicity as number;
resource.maxMultiplicity = item.maxMultiplicity;
} else {
resource[item.propertyName] = item.value;
}
});
if (!this.dataClass.parentDataClass) {
this.resourcesService.dataClass
.update(this.dataClass.model, this.dataClass.id, resource)
.subscribe(
(result: DataClassDetailResponse) => {
this.dataClass = result.body;
this.catalogueItem = result.body;
this.messageHandler.showSuccess('Data Class updated successfully.');
this.editingService.stop();
this.messageService.dataChanged(result.body);
},
(error) => {
this.messageHandler.showError(
'There was a problem updating the Data Class.',
error
);
}
);
} else {
this.resourcesService.dataClass
.updateChildDataClass(
this.dataClass.model,
this.dataClass.parentDataClass,
this.dataClass.id,
resource
)
.subscribe(
(result: DataClassDetailResponse) => {
this.messageHandler.showSuccess('Data Class updated successfully.');
this.editingService.stop();
this.dataClass = result.body;
},
(error) => {
this.messageHandler.showError(
'There was a problem updating the Data Class.',
error
);
}
);
}
}
toggleShowSearch() {
this.messageService.toggleSearch();
}
tabSelected(index: number) {
const tab = this.tabs.getByIndex(index);
this.stateHandler.Go('dataClass', { tabView: tab.name }, { notify: false });
}
}
|
MauroDataMapper/mdm-ui
|
src/app/shared/profile-picture/profile-picture.component.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'mdm-profile-picture',
templateUrl: './profile-picture.component.html',
styleUrls: ['./profile-picture.component.sass']
})
export class ProfilePictureComponent implements OnInit {
@Input() user: any;
image: any;
dynamicTooltipText: string;
constructor() {}
ngOnInit() {
const displayName = `${this.user?.firstName ?? ''} ${this.user?.lastName ?? ''}`;
const organisation = this.user?.organisation ?? '';
const emailAddress = this.user?.emailAddress ?? '';
this.dynamicTooltipText = [displayName.trim(), organisation.trim(), emailAddress.trim()].join(', ');
}
getImage = () => {
if (this.user.profilePicture.fileType !== 'base64') {
this.image = this.user.profilePicture.fileContents;
}
};
}
|
MauroDataMapper/mdm-ui
|
src/app/admin/model-management/model-management.component.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, OnInit } from '@angular/core';
import { MdmResourcesService } from '@mdm/modules/resources';
import { MessageHandlerService } from '@mdm/services/utility/message-handler.service';
import { SecurityHandlerService } from '@mdm/services/handlers/security-handler.service';
import { MatDialog } from '@angular/material/dialog';
import { Title } from '@angular/platform-browser';
import { ContainerDomainType } from '@maurodatamapper/mdm-resources';
@Component({
selector: 'mdm-model-management',
templateUrl: './model-management.component.html',
styleUrls: ['./model-management.component.sass'],
})
export class ModelManagementComponent implements OnInit {
filterElement: string;
filterStatus = 'all';
selectedElements: Array<any>;
selectedElementsCount = 0;
reloading = false;
deleteInProgress = false;
deleteSuccessMessage: string;
folders: any;
constructor(
private resourcesService: MdmResourcesService,
private securityHandler: SecurityHandlerService,
private messageHandler: MessageHandlerService,
private dialog: MatDialog,
private title: Title
) { }
ngOnInit() {
this.selectedElements = [];
this.selectedElementsCount = 0;
this.filterStatus = 'all';
this.filterElement = '';
this.loadFolders();
this.title.setTitle('Model management');
}
onFilterChange = () => {
// if (this.filterElement === '') {
// this.filterStatus = '';
// }
this.loadFolders();
};
loadFolders = () => {
this.reloading = true;
const options = {
queryStringParams: {
includeDocumentSuperseded: true,
includeModelSuperseded: true,
includeDeleted: true,
},
};
let url = this.resourcesService.tree.list(ContainerDomainType.Folders, options.queryStringParams);
if (this.filterStatus === 'all') {
url = this.resourcesService.tree.list(ContainerDomainType.Folders, options.queryStringParams);
} else if (this.filterStatus === 'includeDeleted') {
url = this.resourcesService.admin.deletedModels('folders', 'dataModels');
} else if (this.filterStatus === 'includeDocumentSuperseded') {
url = this.resourcesService.admin.documentationSupersededModels('folders', 'dataModels');
} else if (this.filterStatus === 'includeModelSuperseded') {
url = this.resourcesService.admin.modelSupersededModels('folders', 'dataModels');
}
url.subscribe((resp) => {
this.folders = {
children: resp.body,
isRoot: true,
};
for (const entry of this.folders.children) {
entry.checked = false;
this.markChildren(entry);
}
this.reloading = false;
}, (err) => {
this.reloading = false;
this.messageHandler.showError('There was a problem loading tree.', err);
});
};
markChildren = (node) => {
if (this.selectedElements) {
if (this.selectedElements[node.id]) {
node.checked = true;
}
}
if (node.children) {
for (const entry of node.children) {
this.markChildren(entry);
}
}
};
onNodeChecked = (node) => {
const currentIdx = this.selectedElements.findIndex(
(x) => x.node.id === node.node.id
);
if (currentIdx === -1) {
this.selectedElements.push(node);
this.selectedElementsCount++;
this.removeChildren(node);
} else {
this.selectedElements.splice(currentIdx, 1);
this.selectedElementsCount--;
this.removeChildren(node);
}
};
resetSettings = () => {
this.loadFolders();
this.selectedElements = [];
this.selectedElementsCount = 0;
this.deleteSuccessMessage = null;
};
askForPermanentDelete() {
if (!this.securityHandler.isAdmin()) {
this.messageHandler.showError('Only Admins are allowed to delete records!');
return;
}
let message = 'Are you sure you want to <span class=\'warning\'>permanently</span> delete these records?';
if (this.selectedElementsCount === 1) {
message = 'Are you sure you want to <span class=\'warning\'>permanently</span> delete this record?';
}
let confirmTitle = 'Are you sure you want to delete these records?';
const confirmMessage = `<p class='marginless'><strong>Note: </strong>All 'Data Classes', 'Data Elements' and 'Data Types'
<p class='marginless'>will be deleted <span class='warning'>permanently</span>.</p>`;
if (this.selectedElementsCount === 1) {
confirmTitle = 'Are you sure you want to delete this record?';
}
this.dialog
.openDoubleConfirmationAsync({
data: {
title: 'Delete permanently',
okBtnTitle: 'Yes, delete',
btnType: 'warn',
message,
}
}, {
data: {
title: confirmTitle,
okBtnTitle: 'Confirm deletion',
btnType: 'warn',
message: confirmMessage,
}
})
.subscribe(() => this.delete(true));
}
delete(permanent?) {
const dataModelResources = {
permanent,
ids: [],
};
for (const id in this.selectedElements) {
if (this.selectedElements[id].domainType === 'DataModel') {
dataModelResources.ids.push(this.selectedElements[id].id);
}
}
this.deleteInProgress = true;
this.resourcesService.dataModel.removeAll({}, { body: dataModelResources }).subscribe(() => {
if (permanent) {
this.deleteSuccessMessage = `${this.selectedElementsCount} Data Model(s) deleted successfully.`;
this.deleteInProgress = false;
setTimeout(() => {
this.resetSettings();
}, 2000);
} else {
this.deleteSuccessMessage = `${this.selectedElementsCount} Data Model(s) marked as deleted successfully.`;
this.deleteInProgress = false;
setTimeout(() => {
this.resetSettings();
}, 2000);
}
}, (error) => {
this.deleteInProgress = false;
this.messageHandler.showError('There was a problem deleting the Data Model(s).', error);
});
}
askForSoftDelete() {
if (!this.securityHandler.isAdmin()) {
this.messageHandler.showError('Only Admins are allowed to delete records!');
return;
}
let title = 'Are you sure you want to delete these records?';
let message = `<p class="marginless">They will be marked as deleted and will not be viewable by users</p>
<p class="marginless">except Administrators.</p>`;
if (this.selectedElementsCount === 1) {
title = 'Are you sure you want to delete this record?';
message = `<p class="marginless">It will be marked as deleted and will not be viewable by users</p>
<p class="marginless">except Administrators.</p>`;
}
this.dialog
.openConfirmationAsync({
data: {
title,
okBtnTitle: 'Yes, delete',
btnType: 'warn',
message,
}
})
.subscribe(() => this.delete(false));
}
private removeChildren(node: any) {
if (node.hasChildren && node.children) {
let i = 0;
while (i < node.children.length) {
const childIdx = this.selectedElements.findIndex((y) => y.node.id === node.children[i].id);
if (childIdx >= 0) {
this.selectedElements.splice(childIdx, 1);
this.selectedElementsCount--;
}
i++;
}
}
}
}
|
MauroDataMapper/mdm-ui
|
src/app/utility/markdown/markdown-parser/custom-html-renderer.service.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import {Injectable} from '@angular/core';
// import marked from 'marked/lib/marked';
import {LinkCreatorService} from '@mdm/utility/markdown/markdown-parser/link-creator.service';
import * as marked from 'marked';
@Injectable({
providedIn: 'root'
})
export class CustomHtmlRendererService extends marked.Renderer {
constructor(private linkCreatorService: LinkCreatorService) {
super();
}
link = (href: string, title: any, text: string) => {
if (href) {
const createdLink = this.linkCreatorService.createLink(href, title, text);
return `<a href='${createdLink}'>${text}</a>`;
}
// return the actual format if it does not star with MC
return `<a href='${href}' target="_blank">${text}</a>`;
};
// just reduce header tags for one level
heading = (text, level) => {
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
const l = level + 1;
return `<h${l}>${text}</h${l}>`;
};
table = (header, body) => {
return `<table class='table table-bordered'> ${header} ${body}</table>`;
};
}
|
MauroDataMapper/mdm-ui
|
src/app/utility/all-links-in-paged-list/all-links-in-paged-list.component.ts
|
<reponame>MauroDataMapper/mdm-ui<filename>src/app/utility/all-links-in-paged-list/all-links-in-paged-list.component.ts
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'mdm-all-links-in-paged-list',
templateUrl: './all-links-in-paged-list.component.html',
styleUrls: ['./all-links-in-paged-list.component.sass']
})
export class AllLinksInPagedListComponent implements OnInit {
@Input() parent: any;
@Input() showDescription: any;
@Input() showNoLinksMessage: any;
@Input() showLoadingSpinner: any;
@Input() type: any;
mcLinks = {
refines: [],
doesNotRefine: [],
from: [],
total: 0
};
linkTypes = [];
allLinksMap: any;
total: any;
loading = false;
constructor() { }
ngOnInit() {
if (!this.parent || (this.parent && this.parent.length === 0)) {
this.loading = false;
return;
}
this.loading = true;
this.loadLinksStatic();
this.loading = false;
}
loadLinksStatic = () => {
this.linkTypes = [];
this.allLinksMap = {};
this.total = 0;
this.loading = true;
if (!this.parent || !this.parent.length) {
return;
}
this.parent.forEach(link => {
if (!this.allLinksMap[link.linkType]) {
this.allLinksMap[link.linkType] = {
linkType: link.linkType,
count: 0,
links: []
};
this.linkTypes.push(link.linkType);
}
this.allLinksMap[link.linkType].links.push(link);
this.allLinksMap[link.linkType].count++;
this.total++;
});
this.loading = false;
};
}
|
MauroDataMapper/mdm-ui
|
src/app/services/broadcast.model.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { CatalogueItem } from '@maurodatamapper/mdm-resources';
import { FlatNode } from '@mdm/folders-tree/flat-node';
/**
* Represents the global events that can happen throughout the application.
*/
export type BroadcastEvent =
'applicationOffline'
| 'openLoginModalDialog'
| 'openForgotPasswordModalDialog'
| 'openRegisterModalDialog'
| 'userLoggedIn'
| 'userLoggedOut'
| 'reloadCatalogueTree'
| 'catalogueTreeNodeSelected'
| 'pendingUserUpdated'
| 'favoritesChanged'
| 'elementDetailsUpdated'
| 'elementDeleted'
| 'profileImageUpdated'
| 'apiPropertyUpdated'
| 'favoritesChanged'
| 'reloadClassificationTree';
/**
* Represents a message to broadcast with an optional data payload.
*/
export class BroadcastMessage<T> {
constructor(
public event: BroadcastEvent,
public data?: T) { }
}
/**
* Data to broadcast for the `userLoggedIn` {@link BroadcastEvent}.
*/
export interface UserLoggedInBroadcastData {
/**
* The next UI route to navigate to after logging in.
*/
nextRoute: string;
}
/**
* Data to broadcast for the `catalogueTreeNodeSelected` {@link BroadcastEvent}.
*/
export interface CatalogueTreeNodeSelectedBroadcastData {
/**
* The node that was selected.
*/
node: FlatNode;
}
/**
* Data to broadcast for the `apiPropertyUpdated` {@link BroadcastEvent}.
*/
export interface ApiPropertyUpdatedBroadcastData {
/**
* The key of the property updated.
*/
key: string;
/**
* The value of the property updated.
*/
value: string;
/**
* State if the update involved deleting the API property.
*/
deleted?: boolean;
}
export interface FavouritesUpdatedBroadcastData {
name: 'add' | 'remove';
element: CatalogueItem;
}
|
MauroDataMapper/mdm-ui
|
src/app/shared/alert/alert.component.spec.ts
|
<reponame>MauroDataMapper/mdm-ui<filename>src/app/shared/alert/alert.component.spec.ts
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AlertComponent } from './alert.component';
import { AlertStyle } from './alert.model';
describe('AlertComponent', () => {
let component: AlertComponent;
let fixture: ComponentFixture<AlertComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AlertComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AlertComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should have no icon when icon is disabled', () => {
component.showIcon = false;
fixture.detectChanges();
expect(component.iconName).toBeFalsy();
});
it.each<[string, AlertStyle]>([
['', 'none'],
['fa-check-circle', 'success'],
['fa-info-circle', 'info'],
['fa-exclamation-triangle', 'warning'],
['fa-times-circle', 'error']
])('should use "%s" icon for %s style', (expected, style) => {
component.showIcon = true;
component.alertStyle = style;
fixture.detectChanges();
expect(component.iconName).toBe(expected);
});
it('should have no CSS modified when icon is disabled', () => {
component.showIcon = false;
fixture.detectChanges();
expect(component.cssModifier).toBeFalsy();
});
it.each<[string, AlertStyle]>([
['', 'none'],
['mdm-alert--success', 'success'],
['mdm-alert--info', 'info'],
['mdm-alert--warning', 'warning'],
['mdm-alert--error', 'error']
])('should use "%s" CSS modifier for %s style', (expected, style) => {
component.showIcon = true;
component.alertStyle = style;
fixture.detectChanges();
expect(component.cssModifier).toBe(expected);
});
});
|
MauroDataMapper/mdm-ui
|
src/app/services/validator.service.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ValidatorService {
// eslint-disable-next-line no-useless-escape
readonly emailPattern = /^[_A-Za-z0-9-'!#%&=\/~\`\+\$\*\?\^\{\|\}]+(\.[_A-Za-z0-9-'!#%&=\/~\`\+\$\*\?\^\{\|\}]+)*@[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-\+]+)*(\.[A-Za-z]{2,})$/;
constructor() { }
index(obj, i) {
return obj[i];
}
getProperty(obj, str) {
// eslint-disable-next-line @typescript-eslint/unbound-method
return str.split('.').reduce(this.index, obj);
}
capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
}
validateEmail(email): boolean {
return this.emailPattern.test(email);
}
isDate(date: any): boolean {
if (!isNaN(date)) {
return date instanceof Date;
}
return false;
}
isEmpty(str: string): boolean {
if (str === null || str === undefined) {
return true;
}
if (typeof str === 'string' && str.trim().length === 0) {
return true;
}
return false;
}
validateMultiplicities(min, max) {
if ((min == null && max == null) ||
(min === undefined && max === undefined)) {
return null;
}
if (min === undefined || min === null) {
min = '';
}
if (max === undefined || max === null) {
max = '';
}
if (min.trim().length === 0 && max.trim().length === 0) {
return null;
}
if (min === '*') {
min = '-1';
}
if (max === '*') {
max = '-1';
}
if (min.length > 0 && (parseInt(min, 10) < -1 || isNaN(min) || min.indexOf('.') !== -1)) {
return 'Invalid Min Multiplicity';
}
if (max.length > 0 && (parseInt(max, 10) < -1 || isNaN(max) || max.indexOf('.') !== -1)) {
return 'Invalid Max Multiplicity';
}
if (min.trim().length === 0 && max.trim().length > 0) {
return 'Min Multiplicity should have a value';
}
if (max.trim().length === 0 && min.trim().length > 0) {
return 'Max Multiplicity should have a value';
}
if (min.length > 0 && max.length > 0) {
let minInt = parseInt(min, 10);
let maxInt = parseInt(max, 10);
if (minInt === -1) {
minInt = Number.MAX_VALUE;
}
if (maxInt === -1) {
maxInt = Number.MAX_VALUE;
}
if (minInt > maxInt) {
return 'Min Multiplicity should be Equal or Less than Max Multiplicity';
}
if (minInt === 0 && maxInt === 0) {
return 'Min and Max Multiplicities can not both be 0';
}
if (minInt === Number.MAX_VALUE && maxInt === Number.MAX_VALUE) {
return 'Min and Max Multiplicities can not both be unbound';
}
}
return null;
}
validateLabel(label :string): boolean {
if (!label || (label && label.trim().length === 0)) {
return false;
} else {
return true;
}
}
guid() {
// eslint-disable-next-line prefer-arrow/prefer-arrow-functions
function s4() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}
}
|
MauroDataMapper/mdm-ui
|
src/app/versioned-folder/versioned-folder-detail/versioned-folder-detail.component.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Title } from '@angular/platform-browser';
import { MultiFacetAwareDomainType, VersionedFolderDetail, VersionedFolderDetailResponse } from '@maurodatamapper/mdm-resources';
import { ModalDialogStatus } from '@mdm/constants/modal-dialog-status';
import { FinaliseModalComponent, FinaliseModalResponse } from '@mdm/modals/finalise-modal/finalise-modal.component';
import { VersioningGraphModalComponent } from '@mdm/modals/versioning-graph-modal/versioning-graph-modal.component';
import { VersioningGraphModalConfiguration } from '@mdm/modals/versioning-graph-modal/versioning-graph-modal.model';
import { Access } from '@mdm/model/access';
import { MdmResourcesService } from '@mdm/modules/resources';
import { BroadcastService, MessageHandlerService, MessageService, SecurityHandlerService, SharedService, StateHandlerService, ValidatorService } from '@mdm/services';
import { EditingService } from '@mdm/services/editing.service';
import { EMPTY } from 'rxjs';
import { catchError, finalize } from 'rxjs/operators';
@Component({
selector: 'mdm-versioned-folder-detail',
templateUrl: './versioned-folder-detail.component.html',
styleUrls: ['./versioned-folder-detail.component.scss']
})
export class VersionedFolderDetailComponent implements OnInit {
@Input() detail: VersionedFolderDetail;
@Output() afterSave = new EventEmitter<VersionedFolderDetail>();
isEditing = false;
original: VersionedFolderDetail;
isAdminUser = false;
processing = false;
access: Access;
constructor(
private resourcesService: MdmResourcesService,
private messages: MessageService,
private messageHandler: MessageHandlerService,
private securityHandler: SecurityHandlerService,
private stateHandler: StateHandlerService,
private shared: SharedService,
private broadcast: BroadcastService,
private dialog: MatDialog,
private title: Title,
private editing: EditingService,
private validator: ValidatorService) { }
ngOnInit(): void {
this.isAdminUser = this.shared.isAdmin;
this.access = this.securityHandler.elementAccess(this.detail);
this.title.setTitle(`Versioned Folder - ${this.detail?.label}`);
this.original = Object.assign({}, this.detail);
}
toggleShowSearch() {
this.messages.toggleSearch();
}
showSecurityDialog() {
this.dialog.openSecurityAccess(this.detail, 'versionedFolder');
}
showForm() {
this.editing.start();
this.isEditing = true;
}
cancel() {
this.isEditing = false;
this.editing.stop();
this.detail = Object.assign({}, this.original);
}
save() {
if (!this.validator.validateLabel(this.detail.label)) {
this.messageHandler.showError('There is an error with the label. Please correct and try again.');
return;
}
this.resourcesService.versionedFolder
.update(
this.detail.id,
{
id: this.detail.id,
label: this.detail.label
})
.pipe(
catchError(error => {
this.messageHandler.showError('There was a problem updating the Versioned Folder.', error);
return EMPTY;
})
)
.subscribe(
(response: VersionedFolderDetailResponse) => {
this.messageHandler.showSuccess('Versioned Folder updated successfully.');
this.isEditing = false;
this.original = response.body;
this.editing.stop();
this.afterSave.emit(response.body);
this.broadcast.reloadCatalogueTree();
});
}
askForSoftDelete() {
if (!this.access.showSoftDelete) {
return;
}
this.dialog
.openConfirmationAsync({
data: {
title: 'Are you sure you want to delete this Versioned Folder?',
okBtnTitle: 'Yes, delete',
btnType: 'warn',
message: `<p class="marginless">This Versioned Folder will be marked as deleted and will not be viewable by users </p>
<p class="marginless">except Administrators.</p>`
}
})
.subscribe(() => this.delete(false));
}
askForPermanentDelete(): any {
if (!this.access.showPermanentDelete) {
return;
}
this.dialog
.openDoubleConfirmationAsync(
{
data: {
title: 'Permanent deletion',
okBtnTitle: 'Yes, delete',
btnType: 'warn',
message:
'Are you sure you want to <span class=\'warning\'>permanently</span> delete this Versioned Folder?'
}
},
{
data: {
title: 'Confirm permanent deletion',
okBtnTitle: 'Confirm deletion',
btnType: 'warn',
message: `<p class='marginless'><strong>Note: </strong>All its contents
<p class='marginless'>will be deleted <span class='warning'>permanently</span>.</p>`
}
}
)
.subscribe(() => this.delete(true));
}
finalise() {
const dialog = this.dialog.open<
FinaliseModalComponent,
any,
FinaliseModalResponse
>(FinaliseModalComponent, {
data: {
title: 'Finalise Versioned Folder',
okBtnTitle: 'Finalise Versioned Folder',
btnType: 'accent',
message: `<p class='marginless'>Please select the version you would like this Versioned Folder</p>
<p>to be finalised with: </p>`
}
});
dialog.afterClosed().subscribe((dialogResult) => {
if (dialogResult?.status !== ModalDialogStatus.Ok) {
return;
}
this.processing = true;
this.resourcesService.versionedFolder
.finalise(this.detail.id, dialogResult.request)
.subscribe(
() => {
this.processing = false;
this.messageHandler.showSuccess(
'Versioned Folder finalised successfully.'
);
this.stateHandler.Go(
'versionedFolder',
{ id: this.detail.id },
{ reload: true }
);
},
(error) => {
this.processing = false;
this.messageHandler.showError(
'There was a problem finalising the Versioned Folder.',
error
);
}
);
});
}
newVersion() {
this.stateHandler.Go(
'newVersionModel',
{
id: this.detail.id,
domainType: this.detail.domainType
}
);
}
merge() {
return this.stateHandler.Go(
'mergediff',
{
sourceId: this.detail.id,
catalogueDomainType: MultiFacetAwareDomainType.VersionedFolders
});
}
showMergeGraph() {
this.dialog.open<VersioningGraphModalComponent, VersioningGraphModalConfiguration>(
VersioningGraphModalComponent,
{
data: {
catalogueItem: this.detail
},
panelClass: 'versioning-graph-modal'
});
}
private delete(permanent: boolean) {
if (!this.access.showSoftDelete && !this.access.showPermanentDelete) {
return;
}
this.processing = true;
this.resourcesService.versionedFolder
.remove(this.detail.id, { permanent })
.pipe(
catchError(error => {
this.messageHandler.showError(
'There was a problem deleting the Versioned Folder.',
error
);
return EMPTY;
}),
finalize(() => {
this.processing = false;
})
)
.subscribe(
() => {
this.broadcast.reloadCatalogueTree();
if (permanent) {
this.stateHandler.Go(
'appContainer.mainApp.twoSidePanel.catalogue.allDataModel'
);
} else {
this.stateHandler.reload();
}
});
}
}
|
MauroDataMapper/mdm-ui
|
src/app/wizards/dataModel/data-model-step1/data-model-step1.component.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, OnDestroy, OnInit } from '@angular/core';
import { HelpDialogueHandlerService } from '@mdm/services/helpDialogue.service';
import { MdmResourcesService } from '@mdm/modules/resources';
import { ControlContainer, FormControl, FormGroup, NgForm, Validators } from '@angular/forms';
import { Subject } from 'rxjs';
import { WizardStep } from '@mdm/wizards/wizards.model';
import { DataModelMainComponent } from '../data-model-main/data-model-main.component';
import { takeUntil } from 'rxjs/operators';
@Component({
selector: 'mdm-data-model-step1',
templateUrl: './data-model-step1.component.html',
styleUrls: ['./data-model-step1.component.sass'],
viewProviders: [{ provide: ControlContainer, useExisting: NgForm }]
})
export class DataModelStep1Component implements OnInit, OnDestroy {
allDataModelTypes: any;
step: WizardStep<DataModelMainComponent>;
setupForm: FormGroup;
private unsubscribe$ = new Subject();
constructor(
private helpDialogueHandler: HelpDialogueHandlerService,
private resources: MdmResourcesService
) {}
get label() {
return this.setupForm.get('label');
}
get author() {
return this.setupForm.get('author');
}
get organisation() {
return this.setupForm.get('organisation');
}
get description() {
return this.setupForm.get('description');
}
get dataModelType() {
return this.setupForm.get('dataModelType');
}
get classifiers() {
return this.setupForm.get('classifiers');
}
set classifiersValue(value: any[]) {
this.classifiers.setValue(value);
}
ngOnInit() {
this.setupForm = new FormGroup({
label: new FormControl('', Validators.required), // eslint-disable-line @typescript-eslint/unbound-method
author: new FormControl(''),
organisation: new FormControl(''),
description: new FormControl(''),
dataModelType: new FormControl('', Validators.required), // eslint-disable-line @typescript-eslint/unbound-method
classifiers: new FormControl([])
});
this.setupForm.valueChanges
.pipe(takeUntil(this.unsubscribe$))
.subscribe(() => {
this.step.invalid = this.setupForm.invalid;
});
this.resources.dataModel.types().toPromise().then(dataTypes => {
this.allDataModelTypes = dataTypes.body;
});
}
ngOnDestroy() {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
loadHelp = () => {
this.helpDialogueHandler.open('Create_a_new_model');
};
}
|
MauroDataMapper/mdm-ui
|
src/app/data-type/data-type.component.ts
|
<filename>src/app/data-type/data-type.component.ts<gh_stars>1-10
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { UIRouterGlobals } from '@uirouter/core';
import { StateHandlerService } from '../services/handlers/state-handler.service';
import { Title } from '@angular/platform-browser';
import { MdmResourcesService } from '@mdm/modules/resources';
import { SharedService } from '../services/shared.service';
import { MatTabGroup } from '@angular/material/tabs';
import { EditingService } from '@mdm/services/editing.service';
import {
ElementTypesService,
MessageHandlerService,
SecurityHandlerService,
} from '@mdm/services';
import { DefaultProfileItem } from '@mdm/model/defaultProfileModel';
import { DataModel, DataType, DataTypeDetail, DataTypeDetailResponse, Uuid } from '@maurodatamapper/mdm-resources';
import { TabCollection } from '@mdm/model/ui.model';
import { BaseComponent } from '@mdm/shared/base/base.component';
@Component({
selector: 'mdm-data-type',
templateUrl: './data-type.component.html',
styleUrls: ['./data-type.component.scss']
})
export class DataTypeComponent extends BaseComponent
implements OnInit, AfterViewInit {
@ViewChild('tab', { static: false }) tabGroup: MatTabGroup;
dataType: DataTypeDetail;
dataModelId: Uuid;
dataModel: DataModel;
id: Uuid;
activeTab: number;
showExtraTabs: boolean;
showEditForm = false;
loadingData = false;
schemaView = 'list';
descriptionView = 'default';
contextView = 'default';
rulesItemCount = 0;
isLoadingRules = true;
errorMessage: any;
elementType: any;
showEdit: boolean;
showEditDescription = false;
access: any;
tabs = new TabCollection([
'description',
'dataElements',
'rules',
'comments',
'links',
'attachments'
]);
allDataTypes = this.elementTypes.getAllDataTypesArray();
allDataTypesMap = this.elementTypes.getAllDataTypesMap();
constructor(
private title: Title,
private uiRouterGlobals: UIRouterGlobals,
private stateHandler: StateHandlerService,
private resources: MdmResourcesService,
private sharedService: SharedService,
private messageHandler: MessageHandlerService,
private securityHandler: SecurityHandlerService,
private elementTypes: ElementTypesService,
private editingService: EditingService,
) {
super();
}
ngOnInit() {
this.id = this.uiRouterGlobals.params.id;
this.dataModelId = this.uiRouterGlobals.params.dataModelId;
if (this.isGuid(this.id) && (!this.id || !this.dataModelId)) {
this.stateHandler.NotFound({ location: false });
return;
}
this.title.setTitle('Data Type');
this.activeTab = this.tabs.getByName(
this.uiRouterGlobals.params.tabView as string
).index;
this.tabSelected(this.activeTab);
this.loadingData = true;
this.resources.dataType.get(this.dataModelId, this.id).subscribe(
(result) => {
const data = result.body;
// If the Id is a path get the actual Id
this.dataModelId = data.model;
this.id = data.id;
this.dataType = data;
this.watchDataTypeObject();
this.title.setTitle(`Data Type - ${this.dataType?.label}`);
this.dataType.classifiers = this.dataType.classifiers || [];
this.loadingData = false;
this.showExtraTabs =
!this.sharedService.isLoggedIn() || !this.dataType.editable;
},
() => {
this.loadingData = false;
}
);
}
ngAfterViewInit(): void {
this.editingService.setTabGroupClickEvent(this.tabGroup);
}
watchDataTypeObject() {
this.access = this.securityHandler.elementAccess(this.dataType);
if (this.access !== undefined) {
this.showEdit = this.access.showEdit;
}
}
tabSelected(index: number) {
const tab = this.tabs.getByIndex(index);
this.stateHandler.Go('dataType', { tabView: tab.name }, { notify: false });
}
save(saveItems: Array<DefaultProfileItem>) {
const resource: DataType = {
id: this.dataType.id,
domainType: this.dataType.domainType,
label: this.dataType.label
};
saveItems.forEach((item: DefaultProfileItem) => {
resource[item.propertyName] = item.value;
});
this.resources.dataType
.update(this.dataModel.id, this.dataType.id, resource)
.subscribe(
(res: DataTypeDetailResponse) => {
this.dataType = res.body;
this.messageHandler.showSuccess('Data Type updated successfully.');
this.editingService.stop();
},
(error) => {
this.messageHandler.showError(
'There was a problem updating the Data Type.',
error
);
}
);
}
rulesCountEmitter($event) {
this.isLoadingRules = false;
this.rulesItemCount = $event;
}
}
|
MauroDataMapper/mdm-ui
|
src/app/model-comparison/model-comparison.component.ts
|
<filename>src/app/model-comparison/model-comparison.component.ts
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { MdmResourcesService } from '@mdm/modules/resources';
import { ValidatorService } from '../services/validator.service';
import { MessageHandlerService } from '../services/utility/message-handler.service';
import { StateService } from '@uirouter/core';
import { Observable } from 'rxjs';
@Component({
selector: 'mdm-model-comparison',
templateUrl: './model-comparison.component.html',
styleUrls: ['./model-comparison.component.scss']
})
export class ModelComparisonComponent implements OnInit {
diffMap = {};
diffMapLeft = {};
diffMapRight = {};
max = 100;
dynamic = 100;
diffs: any;
processing: boolean;
activeTab: any;
diffElements = ['dataClasses', 'dataElements', 'dataTypes'];
diffProps = ['label', 'description', 'author', 'organisation'];
sourceModel: any;
targetModel: any;
form = {
dataTypeFilter: null,
dataElementFilter: null
};
constructor(
private messageHandler: MessageHandlerService,
private validator: ValidatorService,
private resources: MdmResourcesService,
private stateService: StateService,
private changeDetector: ChangeDetectorRef
) { }
/* eslint-disable no-shadow */
async ngOnInit() {
// tslint:disable-next-line: deprecation
const sourceId = this.stateService.params.sourceId;
// tslint:disable-next-line: deprecation
const targetId = this.stateService.params.targetId;
if (sourceId) {
this.sourceModel = await this.loadDataModelDetail(sourceId);
}
if (targetId) {
this.targetModel = await this.loadDataModelDetail(targetId);
}
if (this.sourceModel && this.targetModel) {
// check if source and target need to be swapped
if (this.checkIfSwapNeeded()) {
this.swap();
}
this.runDiff();
}
}
checkIfSwapNeeded = () => {
let swapNeeded = false;
for (
let i = 0;
this.sourceModel.semanticLinks &&
i < this.sourceModel.semanticLinks.length;
i++
) {
const link = this.sourceModel.semanticLinks[i];
if (
link.linkType === 'New Version Of' &&
link.target.id === this.targetModel.id
) {
swapNeeded = true;
}
}
for (
let i = 0;
this.targetModel.semanticLinks &&
i < this.targetModel.semanticLinks.length;
i++
) {
const link = this.targetModel.semanticLinks[i];
if (
link.linkType === 'Superseded By' &&
link.target.id === this.sourceModel.id
) {
swapNeeded = true;
}
}
return swapNeeded;
};
async loadDataModelDetail(modelId) {
if (!modelId) {
return null;
}
const response = await this.resources.dataModel.get(modelId).toPromise();
const model = response.body;
const children = await this.resources.tree.get('dataModels', model.domainType, model.id).toPromise();
model.children = children.body;
if (model.children?.length > 0) {
model.hasChildren = true;
}
return model;
}
async onModelSelect(selected, side) {
const selectedId = Array.isArray(selected) ? selected[0]?.id : selected?.id;
if (!selectedId) {
if (side === 'left') {
this.sourceModel = null;
} else if (side === 'right') {
this.targetModel = null;
}
this.diffs = [];
return;
}
if (side === 'left') {
this.sourceModel = await this.loadDataModelDetail(selectedId);
this.targetModel = await this.loadDataModelDetail(this.targetModel?.id);
} else if (side === 'right') {
this.sourceModel = await this.loadDataModelDetail(this.sourceModel?.id);
this.targetModel = await this.loadDataModelDetail(selectedId);
}
if (this.sourceModel && this.targetModel) {
this.runDiff();
}
}
swap() {
const tmp = this.sourceModel;
this.sourceModel = this.targetModel;
this.targetModel = tmp;
this.runDiff();
}
modifiedParents = (breadcrumbs, diffMap) => {
if (!breadcrumbs) {
return;
}
breadcrumbs.forEach((element) => {
this.initDiff(element.id, diffMap);
// Not deleted & Not modified -> modified
if (!diffMap[element.id].deleted && !diffMap[element.id].created) {
diffMap[element.id].modified = true;
diffMap[element.id].deleted = false;
diffMap[element.id].created = false;
}
});
};
initDiff = (id, diffMap) => {
if (diffMap[id]) {
return;
}
diffMap[id] = {
id,
diffs: {
properties: [],
metadata: [],
enumerationValues: [],
dataTypes: [],
dataClasses: [],
dataElements: []
}
};
};
findDiffDataTypeChanges = (leftId, rightId, dataTypeDiff, diffMap) => {
this.initDiff(leftId, diffMap);
this.initDiff(rightId, diffMap);
diffMap[leftId].modified = true;
diffMap[rightId].modified = true;
const update = {
property: 'dataType',
title: 'DataType',
left: dataTypeDiff.left,
right: dataTypeDiff.right
};
diffMap[leftId].diffs.properties.push(update);
diffMap[rightId].diffs.properties.push(update);
};
findDiffProps = (propName, leftId, rightId, labelDiff, diffMap) => {
this.initDiff(leftId, diffMap);
this.initDiff(rightId, diffMap);
diffMap[leftId].modified = true;
diffMap[rightId].modified = true;
const update = {
property: propName,
title: this.validator.capitalize(propName),
left:
!labelDiff.left || labelDiff.left === 'null' ? '\' \'' : labelDiff.left,
right:
!labelDiff.right || labelDiff.right === 'null' ? '\' \'' : labelDiff.right
};
diffMap[leftId].diffs.properties.push(update);
diffMap[rightId].diffs.properties.push(update);
};
findDiffMetadata = (leftId, rightId, metadataDiff, diffMap) => {
this.initDiff(leftId, diffMap);
this.initDiff(rightId, diffMap);
diffMap[leftId].modified = true;
diffMap[rightId].modified = true;
if (metadataDiff.created) {
metadataDiff.created.forEach(item => {
const created = item.value ?? item;
created.created = true;
diffMap[leftId].diffs.metadata.push(created);
diffMap[rightId].diffs.metadata.push(created);
});
}
if (metadataDiff.deleted) {
metadataDiff.deleted.forEach(item => {
const deleted = item.value ?? item;
deleted.deleted = true;
diffMap[leftId].diffs.metadata.push(deleted);
diffMap[rightId].diffs.metadata.push(deleted);
});
}
if (metadataDiff.modified) {
metadataDiff.modified.forEach(modified => {
const update = {
leftId: modified.leftId,
rightId: modified.rightId,
key: modified.key,
namespace: modified.namespace,
property: 'value',
left: modified.diffs[0].value.left,
right: modified.diffs[0].value.right,
modified: true
};
diffMap[leftId].diffs.metadata.push(update);
diffMap[rightId].diffs.metadata.push(update);
});
}
};
findDiffEnumerationValues = (
leftId,
rightId,
enumerationValuesDiff,
diffMap
) => {
this.initDiff(leftId, diffMap);
this.initDiff(rightId, diffMap);
diffMap[leftId].modified = true;
diffMap[rightId].modified = true;
if (enumerationValuesDiff.created) {
enumerationValuesDiff.created.forEach(item => {
const created = item.value ?? item;
created.created = true;
diffMap[leftId].diffs.enumerationValues.push(created);
diffMap[rightId].diffs.enumerationValues.push(created);
});
}
if (enumerationValuesDiff.deleted) {
enumerationValuesDiff.deleted.forEach(item => {
const deleted = item.value ?? item;
deleted.deleted = true;
diffMap[leftId].diffs.enumerationValues.push(deleted);
diffMap[rightId].diffs.enumerationValues.push(deleted);
});
}
if (enumerationValuesDiff.modified) {
enumerationValuesDiff.modified.forEach(modified => {
const update = {
leftId: modified.leftId,
rightId: modified.rightId,
label: modified.label,
property: 'value',
left: modified.diffs[0].value.left,
right: modified.diffs[0].value.right,
modified: true
};
diffMap[leftId].diffs.enumerationValues.push(update);
diffMap[rightId].diffs.enumerationValues.push(update);
});
}
};
runDiff = () => {
if (!this.sourceModel || !this.targetModel) {
return;
}
this.diffMap = {};
this.diffs = [];
this.processing = true;
this.resources.dataModel.diff(this.sourceModel.id, this.targetModel.id)
.subscribe(
res => {
this.processing = false;
const result = res.body;
const diffMap = {};
// Run for DataModel
result.diffs.forEach(diff => {
if (diff.label) {
this.findDiffProps(
'label',
result.leftId,
result.rightId,
diff.label,
diffMap
);
}
if (diff.description) {
this.findDiffProps(
'description',
result.leftId,
result.rightId,
diff.description,
diffMap
);
}
if (diff.author) {
this.findDiffProps(
'author',
result.leftId,
result.rightId,
diff.author,
diffMap
);
}
if (diff.organisation) {
this.findDiffProps(
'organisation',
result.leftId,
result.rightId,
diff.organisation,
diffMap
);
}
if (diff.metadata) {
this.findDiffMetadata(
result.leftId,
result.rightId,
diff.metadata,
diffMap
);
}
});
result.diffs.forEach(diff => {
this.diffElements.forEach(diffElement => {
if (!diff[diffElement]) {
return;
}
diff[diffElement].created?.forEach(item => {
const el = item.value ?? item;
this.initDiff(el.id, diffMap);
diffMap[el.id].id = el.id;
diffMap[el.id].created = true;
diffMap[el.id].deleted = false;
diffMap[el.id].modified = false;
if (diffElement === 'dataClasses') {
this.modifiedParents(el.breadcrumbs, diffMap);
}
if (diffElement === 'dataElements' && el.breadcrumbs) {
this.modifiedParents(el.breadcrumbs, diffMap);
const parentDC = el.breadcrumbs[el.breadcrumbs.length - 1];
this.initDiff(parentDC.id, diffMap);
el.created = true;
el.modified = false;
el.deleted = false;
el.domainType = 'DataElement';
diffMap[parentDC.id].diffs.dataElements.push(el);
}
if (diffElement === 'dataTypes') {
this.modifiedParents([{ id: this.sourceModel.id }], diffMap);
this.modifiedParents([{ id: this.targetModel.id }], diffMap);
this.initDiff(this.sourceModel.id, diffMap);
this.initDiff(this.targetModel.id, diffMap);
el.created = true;
el.modified = false;
el.deleted = false;
el.domainType = 'DataType';
diffMap[this.sourceModel.id].diffs.dataTypes.push(el);
diffMap[this.targetModel.id].diffs.dataTypes.push(el);
}
});
diff[diffElement].deleted?.forEach(item => {
const el = item.value ?? item;
this.initDiff(el.id, diffMap);
diffMap[el.id].id = el.id;
diffMap[el.id].deleted = true;
diffMap[el.id].created = false;
diffMap[el.id].modified = false;
if (diffElement === 'dataClasses') {
if (el.breadcrumbs) {
this.modifiedParents(
el.breadcrumbs.slice(0, el.breadcrumbs.length - 1),
diffMap
);
}
}
if (diffElement === 'dataElements' && el.breadcrumbs) {
this.modifiedParents(el.breadcrumbs, diffMap);
const parentDC = el.breadcrumbs[el.breadcrumbs.length - 1];
this.initDiff(parentDC.id, diffMap);
el.deleted = true;
el.created = false;
el.modified = false;
el.domainType = 'DataElement';
diffMap[parentDC.id].diffs.dataElements.push(el);
}
if (diffElement === 'dataTypes') {
this.modifiedParents([{ id: this.sourceModel.id }], diffMap);
this.modifiedParents([{ id: this.targetModel.id }], diffMap);
this.initDiff(this.sourceModel.id, diffMap);
this.initDiff(this.targetModel.id, diffMap);
el.deleted = true;
el.created = false;
el.modified = false;
el.domainType = 'DataType';
diffMap[this.sourceModel.id].diffs.dataTypes.push(el);
diffMap[this.targetModel.id].diffs.dataTypes.push(el);
}
});
diff[diffElement].modified?.forEach(item => {
const el = item.value ?? item;
this.initDiff(el.leftId, diffMap);
diffMap[el.leftId].modified = true;
diffMap[el.leftId].id = el.leftId;
this.initDiff(el.rightId, diffMap);
diffMap[el.rightId].modified = true;
diffMap[el.rightId].id = el.rightId;
if (diffElement === 'dataClasses') {
if (el.leftBreadcrumbs) {
this.modifiedParents(
el.leftBreadcrumbs.slice(
0,
el.leftBreadcrumbs.length - 1
),
diffMap
);
}
if (el.rightBreadcrumbs) {
this.modifiedParents(
el.rightBreadcrumbs.slice(
0,
el.rightBreadcrumbs.length - 1
),
diffMap
);
}
}
if (diffElement === 'dataElements' && el.leftBreadcrumbs) {
this.modifiedParents(el.leftBreadcrumbs, diffMap);
const parentDC =
el.leftBreadcrumbs[el.leftBreadcrumbs.length - 1];
this.initDiff(parentDC.id, diffMap);
el.modified = true;
el.created = false;
el.deleted = false;
el.domainType = 'DataElement';
diffMap[parentDC.id].diffs.dataElements.push(el);
}
if (diffElement === 'dataElements' && el.rightBreadcrumbs) {
this.modifiedParents(el.rightBreadcrumbs, diffMap);
const parentDC =
el.rightBreadcrumbs[el.rightBreadcrumbs.length - 1];
this.initDiff(parentDC.id, diffMap);
el.modified = true;
el.created = false;
el.deleted = false;
el.domainType = 'DataElement';
diffMap[parentDC.id].diffs.dataElements.push(el);
}
if (diffElement === 'dataTypes' && el.leftBreadcrumbs) {
this.modifiedParents(el.leftBreadcrumbs, diffMap);
const parentDM = el.leftBreadcrumbs[0];
this.initDiff(parentDM.id, diffMap);
el.modified = true;
el.deleted = false;
el.created = false;
el.domainType = 'DataType';
diffMap[parentDM.id].diffs.dataTypes.push(el);
}
if (diffElement === 'dataTypes' && el.rightBreadcrumbs) {
this.modifiedParents(el.rightBreadcrumbs, diffMap);
const parentDM = el.rightBreadcrumbs[0];
this.initDiff(parentDM.id, diffMap);
el.modified = true;
el.deleted = false;
el.created = false;
el.domainType = 'DataType';
diffMap[parentDM.id].diffs.dataTypes.push(el);
}
// Run for Element
// tslint:disable-next-line: no-shadowed-variable
el.diffs.forEach(elemDiff => {
if (elemDiff.label) {
this.findDiffProps(
'label',
el.leftId,
el.rightId,
elemDiff.label,
diffMap
);
}
if (elemDiff.description) {
this.findDiffProps(
'description',
el.leftId,
el.rightId,
elemDiff.description,
diffMap
);
}
if (elemDiff.author) {
this.findDiffProps(
'author',
el.leftId,
el.rightId,
elemDiff.author,
diffMap
);
}
if (elemDiff.organisation) {
this.findDiffProps(
'organisation',
el.leftId,
el.rightId,
elemDiff.organisation,
diffMap
);
}
if (elemDiff.minMultiplicity) {
this.findDiffProps(
'minMultiplicity',
el.leftId,
el.rightId,
elemDiff.minMultiplicity,
diffMap
);
}
if (elemDiff.maxMultiplicity) {
this.findDiffProps(
'maxMultiplicity',
el.leftId,
el.rightId,
elemDiff.maxMultiplicity,
diffMap
);
}
if (elemDiff.metadata) {
this.findDiffMetadata(
el.leftId,
el.rightId,
elemDiff.metadata,
diffMap
);
}
if (diffElement === 'dataTypes' && elemDiff.enumerationValues) {
this.findDiffEnumerationValues(
el.leftId,
el.rightId,
elemDiff.enumerationValues,
diffMap
);
}
if (
diffElement === 'dataElements' &&
elemDiff['dataType.label']
) {
this.findDiffDataTypeChanges(
el.leftId,
el.rightId,
elemDiff['dataType.label'],
diffMap
);
}
});
});
});
});
this.diffMap = diffMap;
if (this.diffMap[this.sourceModel.id]) {
this.sourceModel.modified = this.diffMap[
this.sourceModel.id
].modified;
}
if (this.diffMap[this.targetModel.id]) {
this.targetModel.modified = this.diffMap[
this.targetModel.id
].modified;
}
this.sourceModel.children.forEach(dc => {
if (this.diffMap[dc.id]) {
dc.deleted = this.diffMap[dc.id].deleted;
dc.created = this.diffMap[dc.id].created;
dc.modified = this.diffMap[dc.id].modified;
}
});
this.targetModel.children.forEach(dc => {
if (this.diffMap[dc.id]) {
dc.deleted = this.diffMap[dc.id].deleted;
dc.created = this.diffMap[dc.id].created;
dc.modified = this.diffMap[dc.id].modified;
}
});
this.onNodeClick(this.sourceModel);
},
error => {
this.messageHandler.showError(
'There was a problem comparing the Data Models.',
error
);
this.processing = false;
}
);
};
onNodeExpand = node => {
const obs = new Observable(sub => {
this.resources.tree.get('dataModels', node.domainType, node.id).subscribe(res => {
const result = res.body;
result.forEach(dc => {
if (this.diffMap[dc.id]) {
dc.deleted = this.diffMap[dc.id].deleted;
dc.created = this.diffMap[dc.id].created;
dc.modified = this.diffMap[dc.id].modified;
}
});
sub.next(result);
});
});
return obs;
};
onNodeClick = node => {
this.diffs = [];
if (!this.diffMap[node.id]) {
return;
}
this.diffs = this.diffMap[node.id].diffs;
this.diffs.filteredDataTypes = Object.assign([], this.diffs.dataTypes);
this.diffs.dataTypesStatus = {
deleted: 0,
created: 0,
modified: 0
};
this.diffs.dataTypes.forEach(value => {
if (value.deleted) {
this.diffs.dataTypesStatus.deleted++;
}
if (value.created) {
this.diffs.dataTypesStatus.created++;
}
if (value.modified) {
this.diffs.dataTypesStatus.modified++;
}
});
this.diffs.filteredDataElements = Object.assign(
[],
this.diffs.dataElements
);
this.diffs.dataElementsStatus = {
deleted: 0,
created: 0,
modified: 0
};
this.diffs.dataElements.forEach(value => {
if (value.deleted) {
this.diffs.dataElementsStatus.deleted++;
}
if (value.created) {
this.diffs.dataElementsStatus.created++;
}
if (value.modified) {
this.diffs.dataElementsStatus.modified++;
}
});
this.form = {
dataTypeFilter: null,
dataElementFilter: null
};
this.activeTab = { index: 0 };
if (this.diffs.properties.length > 0) {
this.activeTab.index = 0;
} else if (this.diffs.metadata.length > 0) {
this.activeTab.index = 1;
} else if (this.diffs.dataTypes.length > 0) {
this.activeTab.index = 2;
} else if (this.diffs.dataElements.length > 0) {
this.activeTab.index = 3;
}
};
dataElementFilterChange = () => {
if (this.diffs.dataElements && this.diffs.dataElements.length > 0) {
if (!this.form.dataElementFilter) {
this.diffs.filteredDataElements = Object.assign(
[],
this.diffs.dataElements
);
return;
}
this.diffs.filteredDataElements = this.diffs.dataElements.filter(dataType => {
return (this.form.dataElementFilter === 'deleted' && dataType.deleted) ||
(this.form.dataElementFilter === 'created' && dataType.created) ||
(this.form.dataElementFilter === 'modified' && dataType.modified);
});
}
};
dataTypeFilterChange = () => {
if (this.diffs.dataTypes && this.diffs.dataTypes.length > 0) {
if (!this.form.dataTypeFilter) {
this.diffs.filteredDataTypes = Object.assign([], this.diffs.dataTypes);
return;
}
this.diffs.filteredDataTypes = this.diffs.dataTypes.filter(dataType => {
return (this.form.dataTypeFilter === 'deleted' && dataType.deleted) ||
(this.form.dataTypeFilter === 'created' && dataType.created) ||
(this.form.dataTypeFilter === 'modified' && dataType.modified);
}
);
}
};
}
|
MauroDataMapper/mdm-ui
|
src/app/shared/element-icon/element-icon.component.ts
|
<filename>src/app/shared/element-icon/element-icon.component.ts
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, Input } from '@angular/core';
import { CatalogueItem } from '@maurodatamapper/mdm-resources';
import { getCatalogueItemDomainTypeIcon } from '@mdm/folders-tree/flat-node';
@Component({
selector: 'mdm-element-icon',
templateUrl: './element-icon.component.html',
styleUrls: ['./element-icon.component.sass']
})
export class ElementIconComponent {
@Input() element: CatalogueItem;
constructor() { }
getIcon() {
return getCatalogueItemDomainTypeIcon(this.element.domainType);
}
hasIcon() {
return getCatalogueItemDomainTypeIcon(this.element.domainType) !== null;
}
}
|
MauroDataMapper/mdm-ui
|
src/app/dataClass/data-class-details/data-class-details.component.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import {
Component,
Input,
OnInit} from '@angular/core';
import { MdmResourcesService } from '@mdm/modules/resources';
import { ValidatorService } from '@mdm/services/validator.service';
import { MessageHandlerService } from '@mdm/services/utility/message-handler.service';
import { StateHandlerService } from '@mdm/services/handlers/state-handler.service';
import { BroadcastService } from '@mdm/services/broadcast.service';
import { Title } from '@angular/platform-browser';
import { MatDialog } from '@angular/material/dialog';
import { SecurityHandlerService } from '@mdm/services/handlers/security-handler.service';
import { EditingService } from '@mdm/services/editing.service';
import {
DataClass,
DataClassDetail,
DataClassDetailResponse
} from '@maurodatamapper/mdm-resources';
import { Access } from '@mdm/model/access';
@Component({
selector: 'mdm-data-class-details',
templateUrl: './data-class-details.component.html',
styleUrls: ['./data-class-details.component.sass']
})
export class DataClassDetailsComponent implements OnInit {
@Input() dataClass: DataClassDetail;
editMode = false;
originalDataClass: DataClassDetail;
hasResult = false;
deleteInProgress: boolean;
exportError: any;
parentLabel = '';
access: Access;
constructor(
private resourcesService: MdmResourcesService,
private validator: ValidatorService,
private messageHandler: MessageHandlerService,
private broadcast: BroadcastService,
private stateHandler: StateHandlerService,
private title: Title,
private dialog: MatDialog,
private securityHandler: SecurityHandlerService,
private editingService: EditingService
) {}
ngOnInit() {
this.originalDataClass = Object.assign({}, this.dataClass);
this.dataClassDetails();
}
dataClassDetails(): any {
this.resourcesService.dataModel
.get(this.dataClass.model)
.subscribe((dataClass) => {
this.parentLabel = dataClass.body.label;
});
this.title.setTitle(`Data Class - ${this.dataClass?.label}`);
this.access = this.securityHandler.elementAccess(this.dataClass);
}
askForPermanentDelete() {
this.dialog
.openDoubleConfirmationAsync(
{
data: {
title: 'Permanent deletion',
okBtnTitle: 'Yes, delete',
btnType: 'warn',
message: `<p>Are you sure you want to <span class='warning'>permanently</span> delete this Data Class?</p>
<p class='marginless'><strong>Note:</strong> You are deleting the <strong><i>${this.dataClass.label}</i></strong> Data Class.</p>`
}
},
{
data: {
title: 'Confirm permanent deletion',
okBtnTitle: 'Confirm deletion',
btnType: 'warn',
message:
'<strong>Note: </strong> All its contents will be deleted <span class=\'warning\'>permanently</span>.'
}
}
)
.subscribe(() => this.delete());
}
delete() {
if (!this.dataClass.parentDataClass) {
this.resourcesService.dataClass
.remove(this.dataClass.model, this.dataClass.id)
.subscribe(
() => {
this.messageHandler.showSuccess('Data Class deleted successfully.');
this.broadcast.reloadCatalogueTree();
this.stateHandler.Go(
'appContainer.mainApp.twoSidePanel.catalogue.allDataModel'
);
},
(error) => {
this.deleteInProgress = false;
this.messageHandler.showError(
'There was a problem deleting this Data Class.',
error
);
}
);
} else {
this.resourcesService.dataClass
.removeChildDataClass(
this.dataClass.model,
this.dataClass.parentDataClass,
this.dataClass.id
)
.subscribe(
() => {
this.messageHandler.showSuccess('Data Class deleted successfully.');
this.broadcast.reloadCatalogueTree();
this.stateHandler.Go(
'appContainer.mainApp.twoSidePanel.catalogue.allDataModel'
);
},
(error) => {
this.deleteInProgress = false;
this.messageHandler.showError(
'There was a problem deleting this Data Class.',
error
);
}
);
}
}
save() {
if (
this.validator.validateLabel(this.dataClass.label)) {
const resource: DataClass = {
id: this.dataClass.id,
label: this.dataClass.label,
domainType: this.dataClass.domainType
};
if (!this.dataClass.parentDataClass) {
this.resourcesService.dataClass
.update(this.dataClass.model, this.dataClass.id, resource)
.subscribe(
(dataClass: DataClassDetailResponse) => {
this.messageHandler.showSuccess(
'Data Class updated successfully.'
);
this.originalDataClass = dataClass.body;
this.editMode = false;
this.broadcast.reloadCatalogueTree();
this.editingService.stop();
},
(error) => {
this.messageHandler.showError(
'There was a problem updating the Data Class.',
error
);
}
);
} else {
this.resourcesService.dataClass
.updateChildDataClass(
this.dataClass.model,
this.dataClass.parentDataClass,
this.dataClass.id,
resource
)
.subscribe(
(dataClass: DataClassDetailResponse) => {
this.messageHandler.showSuccess(
'Data Class updated successfully.'
);
this.editMode = false;
this.editingService.stop();
this.dataClass = dataClass.body;
this.broadcast.reloadCatalogueTree();
},
(error) => {
this.messageHandler.showError(
'There was a problem updating the Data Class.',
error
);
}
);
}
}
}
showForm() {
this.editingService.start();
this.editMode = true;
}
cancel() {
this.dataClass = Object.assign({}, this.originalDataClass);
this.editMode = false;
this.editingService.stop();
}
isAdmin() {
return this.securityHandler.isAdmin();
}
}
|
MauroDataMapper/mdm-ui
|
src/app/modals/security-modal/security-modal.model.ts
|
<gh_stars>1-10
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { CatalogueItem, SecurableModel } from '@maurodatamapper/mdm-resources';
export type SecurityAccessResource = 'folder' | 'versionedFolder' | 'classifier' | 'dataModel' | 'codeSet' | 'terminology' | 'referenceDataModel';
export const securityAccessResourceDisplayNames = {
folder: 'Folder',
versionedFolder: 'Versioned Folder',
classifier: 'Classifier',
dataModel: 'Data Model',
codeSet: 'Code Set',
terminology: 'Terminology',
referenceDataModel: 'Reference Data Model'
};
export interface SecurityModalConfiguration {
element: CatalogueItem & SecurableModel;
resource: SecurityAccessResource;
}
|
MauroDataMapper/mdm-ui
|
src/app/admin/api-property/api-property.component.ts
|
<filename>src/app/admin/api-property/api-property.component.ts
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatSelectChange } from '@angular/material/select';
import { Title } from '@angular/platform-browser';
import { ApiProperty, ApiPropertyIndexResponse, ApiPropertyResponse } from '@maurodatamapper/mdm-resources';
import { ApiPropertyEditableState, ApiPropertyEditType, ApiPropertyMetadata, propertyMetadata } from '@mdm/model/api-properties';
import { MdmResourcesService } from '@mdm/modules/resources';
import { BroadcastService, MessageHandlerService, StateHandlerService } from '@mdm/services';
import { EditingService } from '@mdm/services/editing.service';
import { UIRouterGlobals } from '@uirouter/core';
import { catchError, map } from 'rxjs/operators';
@Component({
selector: 'mdm-api-property',
templateUrl: './api-property.component.html',
styleUrls: ['./api-property.component.scss']
})
export class ApiPropertyComponent implements OnInit {
id: string;
isNew: boolean;
editExisting = false;
property: ApiPropertyEditableState;
systemProperties: ApiPropertyMetadata[];
selectedSystemProperty: ApiPropertyMetadata;
formGroup: FormGroup;
get key() {
return this.formGroup.get('key');
}
get category() {
return this.formGroup.get('category');
}
get publiclyVisible() {
return this.formGroup.get('publiclyVisible');
}
get value() {
return this.formGroup.get('value');
}
EditTypes = ApiPropertyEditType;
constructor(
private uiRouterGlobals: UIRouterGlobals,
private resources: MdmResourcesService,
private messageHandler: MessageHandlerService,
private stateHandler: StateHandlerService,
private broadcast: BroadcastService,
private editing: EditingService,
private title: Title) { }
ngOnInit(): void {
this.editing.start();
this.id = this.uiRouterGlobals.params.id;
this.editExisting = this.id !== undefined && this.id !== null;
if (this.editExisting) {
this.title.setTitle('Configuration - Edit Property');
this.loadExistingProperty();
}
else {
this.title.setTitle('Configuration - Add Property');
this.loadAvailableSystemProperties();
}
}
systemPropertyChanged(change: MatSelectChange) {
if (change.value) {
this.property.metadata = propertyMetadata.find(m => m.key === change.value);
}
else {
this.property.metadata = this.getBlankMetadata();
}
this.key.setValue(this.property.metadata.key);
this.category.setValue(this.property.metadata.category);
this.publiclyVisible.setValue(this.property.metadata.isSystem);
if (this.property.metadata.isSystem) {
this.publiclyVisible.disable();
}
else {
this.publiclyVisible.enable();
}
}
htmlValueChanged(value: string) {
this.value.setValue(value);
}
cancel() {
this.editing.confirmCancelAsync().subscribe(confirm => {
if (confirm) {
this.navigateToParent();
}
});
}
save() {
if (this.formGroup.invalid) {
return;
}
if (this.editExisting) {
const updated = Object.assign({}, this.property.original);
updated.key = this.key?.value;
updated.category = this.category?.value;
updated.publiclyVisible = this.publiclyVisible?.value;
updated.value = this.value?.value;
this.resources.apiProperties
.update(this.property.original.id, updated)
.pipe(
catchError(errors => {
this.messageHandler.showError('There was a problem updating the property.', errors);
return [];
})
)
.subscribe(() => {
this.messageHandler.showSuccess('Property was updated successfully.');
this.broadcast.apiPropertyUpdated({
key: this.key.value,
value: this.value.value });
this.navigateToParent();
});
}
else {
const data: ApiProperty = {
key: this.key?.value,
value: this.value?.value,
publiclyVisible: this.publiclyVisible?.value ?? false,
category: this.category?.value
};
this.resources.apiProperties
.save(data)
.pipe(
catchError(errors => {
this.messageHandler.showError('There was a problem saving the property.', errors);
return [];
})
)
.subscribe(() => {
this.messageHandler.showSuccess('Property was saved successfully.');
this.broadcast.apiPropertyUpdated({
key: this.key.value,
value: this.value.value });
this.navigateToParent();
});
}
}
private createFormGroup() {
this.formGroup = new FormGroup({
key: new FormControl(this.property.metadata.key, [Validators.required]), // eslint-disable-line @typescript-eslint/unbound-method
category: new FormControl(this.property.metadata.category, [Validators.required]), // eslint-disable-line @typescript-eslint/unbound-method
publiclyVisible: new FormControl({ value: this.property.metadata.publiclyVisible, disabled: this.property.metadata.isSystem }),
value: new FormControl(this.property.original?.value, [Validators.required]) // eslint-disable-line @typescript-eslint/unbound-method
});
}
private getBlankMetadata() {
return {
key: '',
category: '',
publiclyVisible: false,
editType: ApiPropertyEditType.Value,
isSystem: false
};
}
private loadExistingProperty() {
this.resources.apiProperties
.get(this.id)
.pipe(
map((response: ApiPropertyResponse): ApiPropertyEditableState => {
const original = response.body;
const metadata = propertyMetadata.find(p => p.key === original.key) ?? {
key: original.key,
category: original.category,
isSystem: false,
publiclyVisible: original.publiclyVisible,
editType: ApiPropertyEditType.Value
};
return {
metadata,
original
};
}),
catchError(errors => {
this.messageHandler.showError('There was a problem getting the property.', errors);
return [];
})
)
.subscribe((data: ApiPropertyEditableState) => {
this.property = data;
this.createFormGroup();
});
}
private loadAvailableSystemProperties() {
this.resources.apiProperties
.list()
.pipe(
map((response: ApiPropertyIndexResponse) => {
return response.body.items;
}),
catchError(errors => {
this.messageHandler.showError('There was a problem getting the properties.', errors);
return [];
})
)
.subscribe((data: ApiProperty[]) => {
this.systemProperties = propertyMetadata.filter(m => data.every(p => p.key !== m.key));
this.property = {
metadata: this.getBlankMetadata()
};
this.createFormGroup();
});
}
private navigateToParent() {
this.editing.stop();
this.stateHandler.Go(
'appContainer.adminArea.configuration',
{
tabView: 'properties'
},
{
reload: this.property.metadata.requiresReload,
inherit: false
});
}
}
|
MauroDataMapper/mdm-ui
|
src/app/two-side-panel/two-side-panel.component.ts
|
<reponame>MauroDataMapper/mdm-ui<filename>src/app/two-side-panel/two-side-panel.component.ts
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, ViewChild, Renderer2 } from '@angular/core';
import { trigger, state, transition, animate, style } from '@angular/animations';
@Component({
selector: 'mdm-two-side-panel',
templateUrl: './two-side-panel.component.html',
styleUrls: ['./two-side-panel.component.sass'],
animations: [
trigger('openClose', [
state('closed', style({ height: '0', opacity: '0', display: 'none' })),
state('open', style({ height: '*', opacity: '1', display: 'block' })),
transition('closed => open', animate('30ms ease-in')),
transition('open => closed', animate('30ms ease-out'))
])
]
})
export class TwoSidePanelComponent {
@ViewChild('showHideLeftPane', { static: false }) showHideLeftPane;
@ViewChild('resizableLeft', { static: false }) resizableLeft;
@ViewChild('showHidePaneText', { static: false }) showHidePaneText;
showLeftPane: boolean;
state = 'inactive';
isOpen = true;
constructor(private renderer: Renderer2) { }
toggle() {
this.isOpen = !this.isOpen;
}
hideShowLeftPane() {
this.state = this.state === 'inactive' ? 'active' : 'inactive';
if (this.showHideLeftPane.nativeElement.className.includes('fa-chevron-up')) {
this.renderer.removeClass(this.showHideLeftPane.nativeElement, 'fa-chevron-up');
this.renderer.addClass(this.showHideLeftPane.nativeElement, 'fa-chevron-down');
this.resizableLeft.nativeElement.hidden = true;
} else {
this.renderer.removeClass(this.showHideLeftPane.nativeElement, 'fa-chevron-down');
this.renderer.addClass(this.showHideLeftPane.nativeElement, 'fa-chevron-up');
this.resizableLeft.nativeElement.hidden = false;
}
}
// @HostListener('window:resize', ['$event'])
// onResize() {
// const width = window.innerWidth;
// this.windowSetup(width);
// console.log(width);
// }
// windowSetup = width => {
// if (width > 800) {
// this.resizableLeft.nativeElement.hidden = false;
// this.renderer.removeClass(this.showHideLeftPane.nativeElement, 'fa-chevron-down');
// this.renderer.addClass(this.showHideLeftPane.nativeElement, 'fa-chevron-up' );
// } else {
// this.resizableLeft.nativeElement.hidden = true;
// this.renderer.removeClass(this.showHideLeftPane.nativeElement, 'fa-chevron-up');
// this.renderer.addClass(this.showHideLeftPane.nativeElement, 'fa-chevron-down');
// }
// }
}
|
MauroDataMapper/mdm-ui
|
src/app/userArea/profile/profile.component.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MdmResourcesService } from '@mdm/modules/resources';
import { UserDetailsResult } from '@mdm/model/userDetailsModel';
import { SecurityHandlerService } from '@mdm/services/handlers/security-handler.service';
import { MessageService } from '@mdm/services/message.service';
import { HelpDialogueHandlerService } from '@mdm/services/helpDialogue.service';
import { MessageHandlerService } from '@mdm/services/utility/message-handler.service';
import { DomSanitizer } from '@angular/platform-browser';
import { environment } from '@env/environment';
import { BroadcastService } from '@mdm/services/broadcast.service';
@Component({
selector: 'mdm-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.scss']
})
export class ProfileComponent implements OnInit, AfterViewInit {
@ViewChild('imgCropperComp', { static: true }) imgCropperComp;
user: UserDetailsResult;
currentUser: any;
imageVersion = 1;
imageThumb: any = '';
imageSource: any = '';
isImageLoaded = false;
isChangingProfileImage = false;
profileImagePath: string;
imageChangedEvent: any = '';
trustedUrl: any;
afterSave: (result: { body: { id: any } }) => void;
backendUrl: string = environment.apiEndpoint;
constructor(
private resourcesService: MdmResourcesService,
private securityHandler: SecurityHandlerService,
private messageService: MessageService,
private messageHandler: MessageHandlerService,
private helpDialogueService: HelpDialogueHandlerService,
private sanitizer: DomSanitizer,
private broadcast: BroadcastService
) {
this.currentUser = this.securityHandler.getCurrentUser();
}
ngOnInit() {
this.userDetails();
}
// Get the user details data
userDetails() {
this.resourcesService.catalogueUser.get(this.currentUser.id).subscribe((result: { body: UserDetailsResult }) => {
this.user = result.body;
this.messageService.sendUserDetails(this.user);
this.trustedUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.backendUrl + '/catalogueUsers/' + this.user.id + '/image');
}, err => {
this.messageHandler.showError('There was a problem loading user details.', err);
});
}
sendMessage(): void {
// send message to subscribers via observable subject
this.messageService.sendUserDetails(this.user);
}
ngAfterViewInit() {
this.isImageLoaded = false;
}
// This is emit event in order to know when to display the save button
imageCropped(prm: any) {
this.isImageLoaded = true;
this.imageThumb = prm;
}
// Saves the selected profile picture
public savePicture() {
this.resourcesService.userImage.update(this.user.id, { image: this.imageThumb, type: 'image/png' }).subscribe(() => {
this.messageHandler.showSuccess('User profile image updated successfully.');
this.imageVersion++;
this.isImageLoaded = null;
this.isChangingProfileImage = false;
this.broadcast.dispatch('profileImageUpdated');
this.userDetails();
}, error => {
this.messageHandler.showError('There was a problem updating the User Details.', error);
});
}
// When a file is selected
fileChangeEvent(fileInput: any): void {
this.imgCropperComp.imageChangedEvent = fileInput;
this.readThis(fileInput.target);
this.isImageLoaded = true;
}
// Reads the file and populates imageSource in order to hold the whole file
readThis(inputValue: any): void {
const file: File = inputValue.files[0];
const myReader: FileReader = new FileReader();
myReader.onloadend = () => {
this.isChangingProfileImage = true;
this.imageSource = myReader.result;
};
myReader.readAsDataURL(file);
}
// Remove the profile image
public removeProfileImage() {
this.resourcesService.userImage.remove(this.user.id).subscribe(() => {
this.messageHandler.showSuccess('User profile image removed successfully.');
this.imageVersion++;
this.isImageLoaded = null;
this.userDetails();
this.broadcast.dispatch('profileImageUpdated');
},
error => {
this.messageHandler.showError('There was a problem removing the user profile image.', error);
}
);
}
// Cancel the add image process
public clear() {
this.isImageLoaded = false;
this.isChangingProfileImage = false;
}
public loadHelp() {
this.helpDialogueService.open('User_profile');
}
}
|
MauroDataMapper/mdm-ui
|
src/app/services/grid.service.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Injectable, Output, EventEmitter } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class GridService {
@Output() reloadEvent = new EventEmitter<any>();
constructor() { }
applyFilter = (filters: any[]) => {
const filter = {};
if (filters) {
filters.forEach((x: any) => {
const name = x.nativeElement.name;
const value = x.nativeElement.value;
if (value !== '') {
filter[name] = value;
}
});
this.reloadEvent.emit(filter);
}
};
constructOptions(pageSize? : number, pageIndex? : number, sortBy? : string, sortType? : string, filters? : {}) {
const options = {};
if (pageSize) {
options['max'] = pageSize;
}
if (pageIndex) {
options['offset'] = pageIndex;
}
if (sortBy) {
options['sort'] = sortBy;
}
if (sortType) {
options['order'] = sortType;
}
if (filters) {
Object.keys(filters).map(key => {
options[key] = filters[key];
});
}
return options;
}
}
|
MauroDataMapper/mdm-ui
|
src/app/admin/group-member-table/group-member-table.component.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import {
Component,
Input,
ViewChildren,
ElementRef,
ViewChild,
ChangeDetectorRef,
AfterViewInit,
EventEmitter,
Output,
} from '@angular/core';
import { ROLES } from '@mdm/constants/roles';
import { MdmResourcesService } from '@mdm/modules/resources';
import { MessageHandlerService } from '@mdm/services/utility/message-handler.service';
import { McSelectPagination } from '@mdm/utility/mc-select/mc-select.component';
import { merge } from 'rxjs';
import { GridService } from '@mdm/services/grid.service';
import { catchError, map, startWith, switchMap } from 'rxjs/operators';
import { MatSort } from '@angular/material/sort';
import { MdmPaginatorComponent } from '@mdm/shared/mdm-paginator/mdm-paginator';
import { MatTable } from '@angular/material/table';
import { MatDialog } from '@angular/material/dialog';
@Component({
selector: 'mdm-group-member-table',
templateUrl: './group-member-table.component.html',
styleUrls: ['./group-member-table.component.scss'],
})
export class GroupMemberTableComponent implements AfterViewInit {
@Input() parent: any;
@Output() childEvent = new EventEmitter<any>();
@ViewChildren('filters', { read: ElementRef }) filters: ElementRef[];
@ViewChild(MatSort, { static: false }) sort: MatSort;
@ViewChild(MdmPaginatorComponent, { static: true })
paginator: MdmPaginatorComponent;
@ViewChild(MatTable, { static: false }) table: MatTable<any>;
ROLES = this.roles.map;
errors: any;
displayedColumns = ['fullName', 'emailAddress', 'disabled', 'empty'];
pagination: McSelectPagination;
totalItemCount = 0;
isLoadingResults: boolean;
records: any[] = [];
filter: any = '';
applyFilter : any;
constructor(
private roles: ROLES,
private changeRef: ChangeDetectorRef,
private gridService: GridService,
private messageHandler: MessageHandlerService,
private resources: MdmResourcesService,
private dialog: MatDialog
) { }
ngAfterViewInit() {
this.applyFilter = this.gridService.applyFilter(this.filters);
this.sort.sortChange.subscribe(() => (this.paginator.pageIndex = 0));
this.gridService.reloadEvent.subscribe(
() => (this.paginator.pageIndex = 0)
);
merge(
this.sort.sortChange,
this.paginator.page,
this.gridService.reloadEvent
)
.pipe(
startWith({}),
switchMap(() => {
this.isLoadingResults = true;
return this.groupMembersFetch(
this.paginator.pageSize,
this.paginator.pageOffset,
this.sort.active,
this.sort.direction,
this.filter
);
}),
map((data: any) => {
this.totalItemCount = data.body.count;
this.isLoadingResults = false;
return data.body.items;
}),
catchError(() => {
this.isLoadingResults = false;
return [];
})
)
.subscribe((data) => {
this.records = data;
});
this.changeRef.detectChanges();
}
groupMembersFetch = (pageSize?, pageIndex?, sortBy?, sortType?, filters?) => {
const options = this.gridService.constructOptions(pageSize, pageIndex, sortBy, sortType, filters);
return this.resources.catalogueUser.listInUserGroup(
this.parent.id,
options
);
};
validate = () => {
let isValid = true;
this.errors = [];
if (this.parent.name.trim().length === 0) {
this.errors.name = 'Name can\'t be empty!';
isValid = false;
}
if (isValid) {
delete this.errors;
}
return isValid;
};
add = () => {
const newRecord = {
id: '',
firstName: '',
lastName: '',
organisation: '',
userRole: '',
disabled: false,
isNew: true,
};
this.records = [].concat([newRecord]).concat(this.records);
};
fetchUser = (text, offset, limit) => {
const options = this.gridService.constructOptions(limit, offset, 'emailAddress', 'asc', {searchTerm : text});
this.pagination = {
limit: options['limit'],
offset: options['offset'],
};
return this.resources.catalogueUser.search(options);
};
onUserSelect = (select, record) => {
record.id = select.id;
record.emailAddress = select.emailAddress;
record.firstName = select.firstName;
record.lastName = select.lastName;
record.organisation = select.organisation;
record.userRole = select.userRole;
record.disabled = select.disabled;
};
cancelEdit = (record, index) => {
if (record.isNew) {
this.records.splice(index, 1);
this.table.renderRows();
}
};
confirmAddMember = (record, $index) => {
if (!record.id || !record.emailAddress) {
return;
}
this.resources.userGroups
.updateUserInUserGroup(this.parent.id, record.id, record)
.subscribe(
() => {
this.records[$index] = record;
this.messageHandler.showSuccess('User added successfully.');
this.groupMembersFetch().subscribe((data) => {
this.records.push(data.body.items[data.body.count - 1]);
this.totalItemCount = data.body.count;
this.records = data.body.items;
this.table.renderRows();
this.childEvent.emit(data.body.items);
});
},
(error) => {
this.messageHandler.showError(
'There was a problem adding the user to the group.',
error
);
}
);
};
removeMember = (record) => {
record.deletePending = true;
};
askForDelete = (record: { firstName: string; lastName: string }) => {
this.dialog
.openConfirmationAsync({
data: {
title: 'Are you sure?',
okBtnTitle: 'Yes, remove',
btnType: 'warn',
message: `<p class="marginless"> <strong>Note:</strong> You are removing <strong>${record.firstName} ${record.lastName}</strong> from this group`,
},
})
.subscribe(() => this.confirmRemove(record));
};
confirmRemove = (record) => {
this.resources.userGroups
.removeUserFromUserGroup(this.parent.id, record.id)
.subscribe(
() => {
this.messageHandler.showSuccess('User removed successfully.');
this.groupMembersFetch().subscribe((data) => {
this.totalItemCount = data.body.count;
this.records = data.body.items;
this.table.renderRows();
});
},
(error) => {
this.messageHandler.showError(
'There was a problem removing the user from the group.',
error
);
}
);
};
}
|
MauroDataMapper/mdm-ui
|
src/app/search/advanced-search-bar/advanced-search-bar.component.ts
|
<reponame>MauroDataMapper/mdm-ui
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import {
Component,
OnInit,
Input,
ViewChild,
ElementRef,
EventEmitter
} from '@angular/core';
import { HelpDialogueHandlerService } from '@mdm/services/helpDialogue.service';
import { ContentSearchHandlerService } from '@mdm/services/content-search.handler.service';
import { MdmResourcesService } from '@mdm/modules/resources';
import { Observable, Subject, fromEvent, merge } from 'rxjs';
import {
debounceTime,
map,
filter,
distinctUntilChanged,
switchMap,
catchError,
startWith
} from 'rxjs/operators';
import {
CatalogueItemDomainType,
Classifier,
ClassifierIndexResponse
} from '@maurodatamapper/mdm-resources';
import { MdmPaginatorComponent } from '@mdm/shared/mdm-paginator/mdm-paginator';
import { EMPTY } from 'rxjs';
@Component({
selector: 'mdm-advanced-search-bar',
templateUrl: './advanced-search-bar.component.html',
styleUrls: ['./advanced-search-bar.component.sass']
})
export class AdvancedSearchBarComponent implements OnInit {
@Input() placeholder: string;
@Input() doNotDisplayModelPathStatus: boolean;
@Input() doNotShowDataModelInModelPath: boolean;
@Input() showRestrictTo: boolean;
@Input() parent: any;
@Input() showDomainTypes: string[];
@Input() doNotOpenLinkInNewWindow: boolean;
@ViewChild(MdmPaginatorComponent, { static: true })
paginator: MdmPaginatorComponent;
@ViewChild('searchInputControl', { static: true })
searchInputControl: ElementRef;
displayedColumns: string[] = ['label'];
searchTerm = new Subject<string>();
advancedSearch: boolean;
searchInput: string;
lastDateUpdatedFrom: Date;
lastDateUpdatedTo: Date;
createdFrom: Date;
createdTo: Date;
placeHolderText: string;
totalItemCount = 0;
context: any;
classifications: Classifier[];
searchResults: any[];
searchEvent = new EventEmitter<any>();
hideDM: boolean;
hideDC: boolean;
hideDE: boolean;
hideDT: boolean;
hideEV: boolean;
hideRDM: boolean;
isLoading: boolean;
formData = {
showSearchResult: false,
labelOnly: false,
exactMatch: false,
selectedDomainTypes: {
DataModel: false,
DataClass: false,
DataElement: false,
DataType: false,
EnumerationValue: false,
ReferenceDataModel: false
},
classifiers: [],
lastDateUpdatedFrom: null,
lastDateUpdatedTo: null,
createdFrom: null,
createdTo: null
};
constructor(
private helpDialogueService: HelpDialogueHandlerService,
private contextSearchHandler: ContentSearchHandlerService,
private resources: MdmResourcesService
) {}
ngOnInit() {
this.advancedSearch = false;
this.resources.classifier
.list()
.subscribe((result: ClassifierIndexResponse) => {
this.classifications = result.body.items;
});
this.context = this.parent;
if (this.showDomainTypes) {
this.hideDM = this.showDomainTypes.indexOf(CatalogueItemDomainType.DataModel) === -1;
this.hideDC = this.showDomainTypes.indexOf(CatalogueItemDomainType.DataClass) === -1;
this.hideDE = this.showDomainTypes.indexOf(CatalogueItemDomainType.DataElement) === -1;
this.hideDT = this.showDomainTypes.indexOf('DataType') === -1;
this.hideEV = this.showDomainTypes.indexOf('EnumerationValue') === -1;
this.hideRDM = this.showDomainTypes.indexOf(CatalogueItemDomainType.ReferenceDataModel) === -1;
}
this.placeHolderText = this.placeholder
? this.placeholder
: 'Search for...';
merge(this.searchEvent, this.paginator.page)
.pipe(
startWith({}),
switchMap(() => {
this.isLoading = true;
return this.fetch(this.paginator.pageSize, this.paginator.pageOffset);
}),
map((res: any) => {
this.totalItemCount = res.body.count;
this.isLoading = false;
return res.body.items;
}),
catchError(() => {
this.isLoading = false;
return EMPTY;
})
)
.subscribe((data: any) => {
this.searchResults = data;
});
fromEvent(this.searchInputControl.nativeElement, 'keyup')
.pipe(
map((event: any) => {
return event.target.value;
}),
filter((res: any) => res.length >= 0),
debounceTime(500),
distinctUntilChanged()
)
.subscribe((text: string) => {
if (text.length === 0) {
this.formData.showSearchResult = false;
this.searchResults = [];
this.isLoading = false;
} else {
this.formData.showSearchResult = true;
this.searchEvent.emit();
}
});
}
loadHelp = () => {
this.helpDialogueService.open('Search_Help');
};
toggleAdvancedSearch() {
this.advancedSearch = !this.advancedSearch;
}
fetch(pageSize: number, offset: number): Observable<any> {
this.isLoading = true;
if (!this.formData.showSearchResult) {
return new Observable();
}
const filterDataTypes = [];
if (this.formData.selectedDomainTypes.DataModel) {
filterDataTypes.push(CatalogueItemDomainType.DataModel);
}
if (this.formData.selectedDomainTypes.ReferenceDataModel) {
filterDataTypes.push(CatalogueItemDomainType.ReferenceDataModel);
}
if (this.formData.selectedDomainTypes.DataClass) {
filterDataTypes.push(CatalogueItemDomainType.DataClass);
}
if (this.formData.selectedDomainTypes.DataElement) {
filterDataTypes.push(CatalogueItemDomainType.DataElement);
}
if (this.formData.selectedDomainTypes.DataType) {
filterDataTypes.push('DataType');
}
if (this.formData.selectedDomainTypes.EnumerationValue) {
filterDataTypes.push('EnumerationValue');
}
let searchText = this.searchInput;
if (this.formData.exactMatch) {
if (searchText[0] !== '"') {
searchText = '"' + searchText;
}
if (searchText[searchText.length - 1] !== '"') {
searchText = searchText + '"';
}
}
const classifiersNames = [];
this.formData.classifiers.forEach((classifier) => {
classifiersNames.push(classifier.label);
});
return this.contextSearchHandler.search(
this.context,
searchText,
pageSize,
offset,
filterDataTypes,
this.formData.labelOnly,
null,
classifiersNames,
null,
this.lastDateUpdatedFrom,
this.lastDateUpdatedTo,
this.createdFrom,
this.createdTo
);
}
search(resetPageIndex?: boolean) {
if (this.searchInput !== undefined) {
if (this.searchInput.trim().length !== 0) {
if (resetPageIndex) {
this.paginator.pageIndex = 0;
}
this.searchEvent.emit();
}
}
}
onClassifierChange(): void {
this.search(true);
}
onLastUpdatedSelect($event): void {
this.lastDateUpdatedFrom = $event.from;
this.lastDateUpdatedTo = $event.to;
this.search(true);
}
onCreatedSelect($event): void {
this.createdFrom = $event.from;
this.createdTo = $event.to;
this.search(true);
}
onContextSelected = (selected) => {
this.context = null;
if (selected && selected.length > 0) {
this.context = selected[0];
}
this.search(true);
};
}
|
MauroDataMapper/mdm-ui
|
src/app/modules/resources/mdm-resources.models.ts
|
<filename>src/app/modules/resources/mdm-resources.models.ts
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { RequestSettings } from '@maurodatamapper/mdm-resources';
import { HttpErrorResponse } from '@angular/common/http';
/**
* Interface to define standard properties/options for the `MdmRestHandlerService`.
*
* @see MdmRestHandlerService
*/
export interface MdmHttpHandlerOptions {
/**
* Determine if the `MdmRestHandlerService` should automatically handle `GET` request errors.
*
* If `true`, any `GET` request that returns a status code in the 4XX range will be automatically handled by the `MdmRestHandlerService`.
* Provide a `false` value to override this behaviour and handle any HTTP error yourself.
*
* If no value is provided or is undefined, the default value is considered to be `true`.
*/
handleGetErrors?: boolean;
}
export type MdmRestHandlerOptions = RequestSettings & MdmHttpHandlerOptions;
/**
* Represents a generic error from an `mdm-resources` operation.
*/
export class MdmResourcesError {
constructor(public response: HttpErrorResponse) { }
}
|
MauroDataMapper/mdm-ui
|
src/app/shared/mdm-paginator/mdm-paginator.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, OnInit } from '@angular/core';
import { MatPaginator, PageEvent } from '@angular/material/paginator';
@Component({
selector: 'mdm-paginator',
template: '<mat-paginator [pageSizeOptions]="pageSizeOptions" [pageSize]="pageSize" [length]="length" showFirstLastButtons (page)="changed($event)"></mat-paginator>'
})
export class MdmPaginatorComponent extends MatPaginator implements OnInit {
ngOnInit(): void {
super.ngOnInit();
this.pageSize = 20;
this.pageSizeOptions = [5, 10, 20, 50];
const settings = JSON.parse(localStorage.getItem('userSettings'));
if (settings) {
this.pageSize = settings.countPerTable;
this.pageSizeOptions = settings.counts;
}
}
get pageOffset() {
return this.pageSize * this.pageIndex;
}
changed(value: PageEvent) {
this.pageSize = value.pageSize;
this.pageIndex = value.pageIndex;
this.page.emit(value);
}
}
|
MauroDataMapper/mdm-ui
|
src/app/modules/admin-routes/admin-routes.module.ts
|
<gh_stars>1-10
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { NgModule } from '@angular/core';
import { AdminAppContainerComponent } from '@mdm/admin/app-container/app-container.component';
import { DashboardComponent } from '@mdm/admin/home/home.component';
import { EmailsComponent } from '@mdm/admin/emails/emails.component';
import { ModelManagementComponent } from '@mdm/admin/model-management/model-management.component';
import { UsersComponent } from '@mdm/admin/users/users.component';
import { UserComponent } from '@mdm/admin/user/user.component';
import { GroupsComponent } from '@mdm/admin/groups/groups.component';
import { PendingUsersComponent } from '@mdm/admin/pending-users/pending-users.component';
import { ConfigurationComponent } from '@mdm/admin/configuration/configuration.component';
import { Ng2StateDeclaration, UIRouterModule } from '@uirouter/angular';
import { GroupComponent } from '@mdm/admin/group/group.component';
import { ApiPropertyComponent } from '@mdm/admin/api-property/api-property.component';
import { SubscribedCataloguesComponent } from '@mdm/admin/subscribed-catalogues/subscribed-catalogues.component';
import { SubscribedCatalogueComponent } from '@mdm/admin/subscribed-catalogue/subscribed-catalogue.component';
import { OpenidConnectProviderTableComponent } from '@mdm/admin/openid-connect-provider-table/openid-connect-provider-table.component';
import { OpenidConnectProviderComponent } from '@mdm/admin/openid-connect-provider/openid-connect-provider.component';
export const pageRoutes: { states: Ng2StateDeclaration[] } = {
states: [
{
name: 'appContainer.adminArea',
url: '/admin',
component: AdminAppContainerComponent,
},
{
name: 'appContainer.adminArea.home',
url: '/home',
component: DashboardComponent
},
{
name: 'appContainer.adminArea.emails',
url: '/emails',
component: EmailsComponent
},
{
name: 'appContainer.adminArea.modelManagement',
url: '/modelManagement',
component: ModelManagementComponent
},
{
name: 'appContainer.adminArea.subscribedCatalogues',
url: '/subscribedCatalogues',
component: SubscribedCataloguesComponent
},
{
name: 'appContainer.adminArea.subscribedCatalogue',
url: '/subscribedCatalogue/{id}',
params: { id: { value: null, squash: true} },
component: SubscribedCatalogueComponent
},
{
name: 'appContainer.adminArea.openIdConnectProviders',
url: '/openidConnectProviders',
component: OpenidConnectProviderTableComponent
},
{
name: 'appContainer.adminArea.openIdConnectProvider',
url: '/openidConnectProvider/:id',
component: OpenidConnectProviderComponent,
params: {
id: { value: null, squash: true }
}
},
{
name: 'appContainer.adminArea.users',
url: '/users',
component: UsersComponent
},
{
name: 'appContainer.adminArea.user',
url: '/user/{id}',
params: { id: { value: null, squash: true } },
component: UserComponent
},
{
name: 'appContainer.adminArea.groups',
url: '/groups',
component: GroupsComponent
},
{
name: 'appContainer.adminArea.group',
url: '/group/{id}',
params: { id: { value: null, squash: true } },
component: GroupComponent
},
{
name: 'appContainer.adminArea.pendingUsers',
url: '/pendingUsers',
component: PendingUsersComponent
},
{
name: 'appContainer.adminArea.configuration',
url: '/configuration/{tabView:string}',
component: ConfigurationComponent,
params: {
tabView: { dynamic: true, value: null, squash: true}
}
},
{
name: 'appContainer.adminArea.apiPropertyAdd',
url: '/property/add',
component: ApiPropertyComponent
},
{
name: 'appContainer.adminArea.apiPropertyEdit',
url: '/property/edit/:id',
component: ApiPropertyComponent
}
]
};
@NgModule({
declarations: [],
imports: [UIRouterModule.forChild({ states: pageRoutes.states })]
})
export class AdminRoutesModule { }
|
MauroDataMapper/mdm-ui
|
src/app/modals/add-rule-modal/add-rule-modal.component.ts
|
<reponame>MauroDataMapper/mdm-ui
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, Inject, OnInit } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
@Component({
selector: 'mdm-add-rule-modal',
templateUrl: './add-rule-modal.component.html',
styleUrls: ['./add-rule-modal.component.scss']
})
export class AddRuleModalComponent implements OnInit {
okBtn: string;
cancelBtn: string;
btnType: string;
inputValue: { label: string; groups: any[]};
modalTitle: string;
message: string;
inputLabel: string;
allGroups = [];
selectedGroups = [];
constructor( private dialogRef: MatDialogRef<AddRuleModalComponent>,
@Inject(MAT_DIALOG_DATA) public data: any)
{ }
ngOnInit(): void {
this.okBtn = this.data.okBtn ? this.data.okBtn : 'Save';
this.btnType = this.data.btnType ? this.data.btnType : 'primary';
this.cancelBtn = this.data.cancelBtn ? this.data.cancelBtn : 'Cancel';
this.inputLabel = this.data.inputLabel ? this.data.inputLabel : '';
this.modalTitle = this.data.modalTitle ? this.data.modalTitle : '';
this.message = this.data.message;
this.inputValue = {
label: '',
groups: []
};
}
}
|
MauroDataMapper/mdm-ui
|
src/app/admin/group/group.component.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { StateHandlerService } from '@mdm/services/handlers/state-handler.service';
import { MdmResourcesService } from '@mdm/modules/resources';
import { StateService } from '@uirouter/core';
import { MessageHandlerService } from '@mdm/services/utility/message-handler.service';
import { EditingService } from '@mdm/services/editing.service';
import { Uuid } from '@maurodatamapper/mdm-resources';
@Component({
selector: 'mdm-group',
templateUrl: './group.component.html',
styleUrls: ['./group.component.scss']
})
export class GroupComponent implements OnInit {
errors: any;
group = {
name: '',
description: '',
groupMembers: [],
id: ''
};
groupId: Uuid;
constructor(
private messageHandler: MessageHandlerService,
private title: Title,
private stateHandler: StateHandlerService,
private stateService: StateService,
private resources: MdmResourcesService,
private editingService: EditingService) { }
ngOnInit() {
this.editingService.start();
// tslint:disable-next-line: deprecation
this.groupId = this.stateService.params.id;
if (this.groupId) {
this.title.setTitle('Group - Edit Group');
this.resources.userGroups.get(this.groupId).subscribe(result => {
this.group = result.body;
});
this.resources.catalogueUser.listInUserGroup(this.groupId).subscribe(result => {
this.group.groupMembers = result.body.items || [];
});
} else {
this.title.setTitle('Group - Add Group');
}
}
onUpdateGroupMembers = groupMembers => { // triggered when the Members table is updated
this.group.groupMembers = groupMembers;
};
validate = () => {
let isValid = true;
this.errors = [];
if (this.group.name.trim().length === 0) {
this.errors.name = 'Name can\'t be empty!';
isValid = false;
}
if (isValid) {
delete this.errors;
}
return isValid;
};
save = () => {
if (!this.validate()) {
return;
}
if (this.group.id) { // it's in edit mode (update)
this.resources.userGroups.update(this.group.id, this.group).subscribe(() => {
this.messageHandler.showSuccess('Group updated successfully.');
this.navigateToParent();
}, error => {
this.messageHandler.showError('There was a problem updating the group.', error);
});
} else { // it's in new mode (create)
this.resources.userGroups.save(this.group).subscribe(() => {
this.messageHandler.showSuccess('Group saved successfully.');
this.navigateToParent();
}, error => {
this.messageHandler.showError('There was a problem saving the group.', error);
});
}
};
cancel = () => {
this.editingService.confirmCancelAsync().subscribe(confirm => {
if (confirm) {
this.navigateToParent();
}
});
};
private navigateToParent() {
this.editingService.stop();
this.stateHandler.Go('admin.groups');
}
}
|
MauroDataMapper/mdm-ui
|
src/app/services/model-tree.service.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Injectable, OnDestroy } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { CatalogueItemDomainType, ClassifierDetailResponse, ContainerDomainType, FolderDetailResponse, MdmTreeItem, MdmTreeItemListResponse, Modelable, SubscribedCatalogue, SubscribedCatalogueIndexResponse, Uuid, VersionedFolderDetailResponse } from '@maurodatamapper/mdm-resources';
import { ModalDialogStatus } from '@mdm/constants/modal-dialog-status';
import { FlatNode } from '@mdm/folders-tree/flat-node';
import { NewFolderModalComponent } from '@mdm/modals/new-folder-modal/new-folder-modal.component';
import { NewFolderModalConfiguration, NewFolderModalResponse } from '@mdm/modals/new-folder-modal/new-folder-modal.model';
import { MdmResourcesService, MdmRestHandlerOptions } from '@mdm/modules/resources';
import { SubscribedCataloguesService } from '@mdm/subscribed-catalogues/subscribed-catalogues.service';
import { EMPTY, Observable, of, Subject, throwError } from 'rxjs';
import { catchError, filter, map, switchMap, takeUntil } from 'rxjs/operators';
import { BroadcastService } from './broadcast.service';
import { EditingService } from './editing.service';
import { ElementTypesService } from './element-types.service';
import { SecurityHandlerService } from './handlers/security-handler.service';
import { SharedService } from './shared.service';
import { MessageHandlerService } from './utility/message-handler.service';
import { UserSettingsHandlerService } from './utility/user-settings-handler.service';
@Injectable({
providedIn: 'root'
})
export class ModelTreeService implements OnDestroy {
currentNode?: FlatNode;
private unsubscribe$ = new Subject();
constructor(
private resources: MdmResourcesService,
private sharedService: SharedService,
private userSettingsHandler: UserSettingsHandlerService,
private subscribedCatalogues: SubscribedCataloguesService,
private messageHandler: MessageHandlerService,
private securityHandler: SecurityHandlerService,
private elementTypes: ElementTypesService,
private broadcast: BroadcastService,
private dialog: MatDialog,
private editing: EditingService) {
this.broadcast
.onCatalogueTreeNodeSelected()
.pipe(takeUntil(this.unsubscribe$))
.subscribe(data => this.currentNode = data.node);
}
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
getLocalCatalogueTreeNodes(noCache?: boolean): Observable<MdmTreeItem[]> {
let options: any = {};
if (this.sharedService.isLoggedIn()) {
options = {
queryStringParams: {
includeDocumentSuperseded: this.userSettingsHandler.get('includeDocumentSuperseded') || false,
// includeModelSuperseded: this.userSettingsHandler.get('includeModelSuperseded') || false,
includeModelSuperseded: true,
includeDeleted: this.userSettingsHandler.get('includeDeleted') || false
}
};
}
if (noCache) {
options.queryStringParams.noCache = true;
}
return this.resources.tree
.list(ContainerDomainType.Folders, options.queryStringParams)
.pipe(
map((response: MdmTreeItemListResponse) => response.body)
);
}
getSubscribedCatalogueTreeNodes(): Observable<MdmTreeItem[]> {
if (!this.sharedService.isLoggedIn(true) || !this.sharedService.features.useSubscribedCatalogues) {
return of([]);
}
const queryParams = {
sort: 'label',
order: 'asc'
};
// Handle any HTTP errors manually. This covers the scenario where this is unable to
// get available subscribed catalogues e.g. the subscribed catalogue instance is not
// available/offline
const restOptions: MdmRestHandlerOptions = {
handleGetErrors: false
};
return this.resources.subscribedCatalogues
.list(queryParams, restOptions)
.pipe(
map((response: SubscribedCatalogueIndexResponse) => response.body.items ?? []),
map((catalogues: SubscribedCatalogue[]) => catalogues.map(item => Object.assign<{}, MdmTreeItem>({}, {
id: item.id,
domainType: CatalogueItemDomainType.SubscribedCatalogue,
hasChildren: true,
label: item.label,
availableActions: []
}))),
catchError(error => {
this.messageHandler.showError('There was a problem getting the Subscribed Catalogues.', error);
return EMPTY;
}),
);
}
createRootNode(children?: MdmTreeItem[]): MdmTreeItem {
return Object.assign<{}, MdmTreeItem>({}, {
id: '',
domainType: CatalogueItemDomainType.Root,
children,
hasChildren: true,
isRoot: true,
availableActions: []
});
}
createLocalCatalogueNode(children?: MdmTreeItem[]): MdmTreeItem {
return Object.assign<{}, MdmTreeItem>({}, {
id: '4aa2444c-ed08-471b-84dd-96f6b3b4a00a',
domainType: CatalogueItemDomainType.LocalCatalogue,
label: 'This catalogue',
hasChildren: true,
children,
availableActions: []
});
}
createExternalCataloguesNode(children?: MdmTreeItem[]): MdmTreeItem {
return Object.assign<{}, MdmTreeItem>({}, {
id: '30dca3f9-5cf5-41a8-97eb-fd2dab2d4c20',
domainType: CatalogueItemDomainType.ExternalCatalogues,
label: 'External catalogues',
hasChildren: true,
children,
availableActions: []
});
}
/**
* Gets all external, federated data models available and returns them as `Node` objects for the model tree.
*
* @param catalogueId The UUID of the subscribed catalogue to search under.
*
* Each returned `Node` object will contain a `FederatedDataModel` inside the `Node.dataModel` property. It is
* required that the model tree pass this on to the detail component views during UI state transitions because
* there is no endpoint available for getting a single `FederatedDataModel` - this assignment will reduce
* roundtrips back to the server.
*
* @see FederatedDataModel
*/
getFederatedDataModelNodes(catalogueId: string): Observable<MdmTreeItem[]> {
return this.subscribedCatalogues
.getFederatedDataModels(catalogueId)
.pipe(
catchError(error => {
this.messageHandler.showError('There was a problem getting federated data models from a subscribed catalogue.', error);
return EMPTY;
}),
map(models => models.map(item => Object.assign<{}, MdmTreeItem>({}, {
id: item.modelId,
domainType: CatalogueItemDomainType.FederatedDataModel,
hasChildren: false,
label: item.label,
modelVersion: item.version,
parentId: item.catalogueId,
availableActions: []
})))
);
}
/**
* Display a dialog to create a new folder, then save the new folder to the model tree.
*
* @param parentFolderId The unique identifier of the parent folder to add the new folder to.
* If no parent is required, ignore this parameter or pass `null` or `undefined`.
* @returns An `Observable` containing either a `FolderDetailResponse` or `VersionedFolderDetailResponse`,
* depending on the options selected in the dialog.
*/
createNewFolder(settings: { allowVersioning?: boolean; parentFolderId?: Uuid }): Observable<FolderDetailResponse | VersionedFolderDetailResponse> {
return this.editing
.openDialog<NewFolderModalComponent, NewFolderModalConfiguration, NewFolderModalResponse>(
NewFolderModalComponent,
{
data: {
modalTitle: 'Create a new Folder',
okBtn: 'Add folder',
btnType: 'primary',
inputLabel: 'Folder name',
message: 'Please enter the name of your Folder.',
createRootFolder: !(settings?.parentFolderId),
canVersion: settings?.allowVersioning
}
})
.afterClosed()
.pipe(
filter(response => response?.status === ModalDialogStatus.Ok),
switchMap(modal => {
if (modal.useVersionedFolders && modal.isVersioned) {
return this.saveVersionedFolder(modal.label, settings?.parentFolderId);
}
return this.saveFolder(modal.label, settings?.parentFolderId);
})
);
}
/**
* Display a dialog to create a new classifier, then save the new classifier to the model tree.
*
* @returns An `Observable` containing a `ClassifierDetailResponse`.
*/
createNewClassifier(): Observable<ClassifierDetailResponse> {
return this.editing
.openDialog<NewFolderModalComponent, NewFolderModalConfiguration, NewFolderModalResponse>(
NewFolderModalComponent,
{
data: {
modalTitle: 'Create a new Classifier',
okBtn: 'Add Classifier',
btnType: 'primary',
inputLabel: 'Classifier name',
message: 'Please enter the name of your Classifier.'
}
})
.afterClosed()
.pipe(
filter(response => response?.status === ModalDialogStatus.Ok),
switchMap(modal => this.saveClassifier(modal.label))
);
}
saveFolder(label: string, parentFolderId?: Uuid): Observable<FolderDetailResponse> {
if (parentFolderId) {
return this.resources.folder.saveChildrenOf(parentFolderId, { label });
}
return this.resources.folder.save({ label });
}
saveVersionedFolder(label: string, parentFolderId?: Uuid): Observable<VersionedFolderDetailResponse> {
if (parentFolderId) {
return this.resources.versionedFolder.saveToFolder(parentFolderId, { label });
}
return this.resources.versionedFolder.save({ label });
}
saveClassifier(label: string): Observable<ClassifierDetailResponse> {
return this.resources.classifier.save({ label });
}
deleteCatalogueItemSoft(item: Modelable): Observable<void> {
return this.dialog
.openConfirmationAsync({
data: {
title: `Are you sure you want to delete '${item.label}'?`,
okBtnTitle: 'Yes, delete',
btnType: 'warn',
message: `<p class="marginless">This item will be marked as deleted and will not be viewable by users </p>
<p class="marginless">except Administrators.</p>`
}
})
.pipe(
switchMap(() => this.deleteCatalogueItem(item, false))
);
}
deleteCatalogueItemPermanent(item: Modelable): Observable<void> {
if (!this.securityHandler.isAdmin()) {
this.messageHandler.showWarning('Only administrators may permanently delete catalogue items.');
return of();
}
return this.dialog
.openDoubleConfirmationAsync({
data: {
title: 'Permanent deletion',
okBtnTitle: 'Yes, delete',
btnType: 'warn',
message: `Are you sure you want to <span class=\'warning\'>permanently</span> delete '${item.label}'?`
}
}, {
data: {
title: 'Confirm permanent deletion',
okBtnTitle: 'Confirm deletion',
btnType: 'warn',
message: '<strong>Note: </strong> This item and all its contents will be deleted <span class=\'warning\'>permanently</span>.'
}
})
.pipe(
switchMap(() => this.deleteCatalogueItem(item, true))
);
}
private deleteCatalogueItem(item: Modelable, permanent: boolean): Observable<void> {
const baseTypes = this.elementTypes.getBaseTypes();
const type = baseTypes[item.domainType];
if (!type) {
return throwError(`Cannot find resource name for domain type '${item.domainType}'`);
}
return this.resources[type.resourceName]
.remove(item.id, { permanent })
.pipe(
map(() => this.messageHandler.showSuccess(`Successfully deleted '${item.label}'`)),
catchError(error => {
this.messageHandler.showError(`There was a problem deleting '${item.label}'.`, error);
return EMPTY;
})
);
}
}
|
MauroDataMapper/mdm-ui
|
src/app/term/relationship-list/term-relationship-list.component.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, EventEmitter, Input, OnChanges, OnInit, Output } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { CatalogueItemDomainType, TermDetail, TerminologyDetail, TermRelationship, TermRelationshipType } from '@maurodatamapper/mdm-resources';
import { MdmResourcesService } from '@mdm/modules/resources';
import { BehaviorSubject } from 'rxjs';
import { CreateTermRelationshipDialogComponent } from '../create-term-relationship-dialog/create-term-relationship-dialog.component';
class CreateTermRelationshipForm {
targetTerm: TermDetail;
relationshipType: TermRelationshipType;
constructor(readonly terminology: TerminologyDetail, readonly sourceTerm: TermDetail) {}
}
@Component({
selector: 'mdm-term-relationship-list',
templateUrl: './term-relationship-list.component.html',
styleUrls: ['./term-relationship-list.component.scss']
})
export class TermRelationshipListComponent implements OnInit, OnChanges {
@Input() term: TermDetail;
@Input() canEdit = false;
@Input() canDelete = false;
@Output() selectedTerm = new EventEmitter<TermDetail>();
@Output() totalCount = new EventEmitter<number>();
totalItemCount = 0;
private _relationships = new BehaviorSubject<TermRelationship[]>([]);
private _relationshipTypes = new BehaviorSubject<TermRelationshipType[]>([]);
constructor(private resources: MdmResourcesService, private dialog: MatDialog) {}
ngOnInit() {
}
ngOnChanges(changes) {
if (changes.term) {
this.fetchRelationships();
}
}
fetchRelationships() {
if (this.term) {
this.resources.term.termRelationships(this.term.terminology.id, this.term.id, {
sort: 'label',
order: 'asc'
}).subscribe(
data => {
this.relationships = data.body.items.filter(i => (i.sourceTerm.id === this.term.id) && i.targetTerm.domainType !== CatalogueItemDomainType.Terminology);
const relationshipTypes = [];
this.relationships.forEach(r => {
if (!relationshipTypes.map(rt => rt.id).includes(r.relationshipType.id)) {
relationshipTypes.push(r.relationshipType);
}
});
this.relationshipTypes = relationshipTypes;
this.totalItemCount = this.relationships.length;
this.totalCount.emit(this.totalItemCount);
},
error => console.error(error)
);
}
}
get relationships() {
return this._relationships.value;
}
set relationships(relationships: TermRelationship[]) {
this._relationships.next(relationships);
}
get relationshipTypes() {
return this._relationshipTypes.value;
}
set relationshipTypes(relationshipTypes: TermRelationshipType[]) {
this._relationshipTypes.next(relationshipTypes);
}
filterByRelationshipType(relationshipType: TermRelationshipType) {
return this.relationships.filter(r => r.relationshipType.id === relationshipType.id);
}
deleteRelationship(termRelationship: TermRelationship) {
this.resources.terms.removeTermRelationship(this.term.terminology.id, termRelationship.sourceTerm.id, termRelationship.id).subscribe(() => {
this.fetchRelationships();
});
}
openAddRelationshipDialog(): void {
const dialogRef = this.dialog.open(CreateTermRelationshipDialogComponent, {
data: new CreateTermRelationshipForm(this.term.terminology, this.term)
});
dialogRef.afterClosed().subscribe(data => {
if (data) {
this.fetchRelationships();
}
});
}
}
|
MauroDataMapper/mdm-ui
|
src/app/userArea/settings/settings.component.ts
|
/*
Copyright 2020-2021 University of Oxford
and Health and Social Care Information Centre, also known as NHS Digital
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
*/
import { Component, OnInit } from '@angular/core';
import { HelpDialogueHandlerService } from '@mdm/services/helpDialogue.service';
import { MessageHandlerService } from '@mdm/services/utility/message-handler.service';
import { UserSettingsHandlerService } from '@mdm/services/utility/user-settings-handler.service';
import { Title } from '@angular/platform-browser';
import { SecurityHandlerService } from '@mdm/services/handlers/security-handler.service';
@Component({
selector: 'mdm-settings',
templateUrl: './settings.component.html',
styleUrls: ['./settings.component.scss']
})
export class SettingsComponent implements OnInit {
countPerTable = this.userSettingsHandler.defaultSettings.countPerTable;
expandMoreDescription = this.userSettingsHandler.defaultSettings.expandMoreDescription;
includeModelSuperseded = this.userSettingsHandler.defaultSettings.includeModelSuperseded;
includeDocumentSuperseded = this.userSettingsHandler.defaultSettings.includeDocumentSuperseded;
includeDeleted = this.userSettingsHandler.defaultSettings.includeDeleted;
constructor(
private messageHandler: MessageHandlerService,
private helpDialogueService: HelpDialogueHandlerService,
private userSettingsHandler: UserSettingsHandlerService,
private title: Title,
private securityHandler: SecurityHandlerService
) { }
ngOnInit() {
this.loadSettings();
this.title.setTitle('Preferences');
}
loadSettings = () => {
this.countPerTable = this.userSettingsHandler.get('countPerTable') || this.countPerTable;
this.expandMoreDescription = this.userSettingsHandler.get('expandMoreDescription') || this.expandMoreDescription;
this.includeModelSuperseded = this.userSettingsHandler.get('includeModelSuperseded') || this.includeModelSuperseded;
this.includeDocumentSuperseded = this.userSettingsHandler.get('includeDocumentSuperseded') || this.includeDocumentSuperseded;
if (this.isAdmin()) {
this.includeDeleted = this.userSettingsHandler.get('includeDeleted') || this.includeDeleted;
}
};
isAdmin = () => {
return this.securityHandler.isAdmin();
};
saveSettings = () => {
this.userSettingsHandler.update('countPerTable', this.countPerTable);
this.userSettingsHandler.update('expandMoreDescription', this.expandMoreDescription);
this.userSettingsHandler.update('includeModelSuperseded', this.includeModelSuperseded);
this.userSettingsHandler.update('includeDocumentSuperseded', this.includeDocumentSuperseded);
if (this.isAdmin()) {
this.userSettingsHandler.update('includeDeleted', this.includeDeleted);
}
this.userSettingsHandler.saveOnServer().subscribe(() => {
this.messageHandler.showSuccess('User preferences saved successfully.');
}, error => {
this.messageHandler.showError('Failed to save user preferences.', error);
}
);
};
loadHelp = () => {
this.helpDialogueService.open('Preferences');
};
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.