Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "liquid-java",
"displayName": "LiquidJava",
"description": "Extending Java with Liquid Types",
"version": "0.1.3",
"version": "0.1.4",
"publisher": "AlcidesFonseca",
"repository": {
"type": "git",
Expand Down
59 changes: 45 additions & 14 deletions client/src/webview/diagram-focus.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ function lines(diagram: string): string[] {
}

const dimmedTransitions = (diagram: string) => lines(diagram).filter(line => line.startsWith('%% lj-dimmed-transitions:'));
const calledMethod = (label: string) => `<span class="lj-state-error-method">${label}</span>`;
const selfLoops = (diagram: string) => lines(diagram).filter(line => line.startsWith('%% lj-self-loops:'));
const allowedCall = (label: string) => `<span class="lj-call-allowed">${label}</span>`;
const rejectedCall = (label: string) => `<span class="lj-call-rejected">✕ ${label}</span>`;
const dimmedMethod = (label: string) => `<span class="lj-dimmed-method">${label}</span>`;
const collapsedMethods = (labels: string[], count: string) =>
`<span class="lj-dimmed-method lj-collapsed-methods">${count}<span class="lj-collapsed-list">${labels.map(label => `<span class="lj-collapsed-item">${label}</span>`).join('')}</span></span>`;
Expand All @@ -81,7 +83,7 @@ describe('state error focus', () => {
expect(getRelatedStates(getStateErrorFocus(datagramSocket())!)).toEqual(['bound', 'closed', 'unbound', 'connected']);
});

it('marks valid and invalid states and colours every edge of the called method', () => {
it('marks valid and invalid states, the allowed transitions of the called method, and the rejected call', () => {
for (const focusOnError of [true, false]) {
const diagram = lines(createMermaidDiagram(datagramSocket(), 'TB', false, focusOnError));

Expand All @@ -90,11 +92,14 @@ describe('state error focus', () => {
'state "✕ closed" as closed',
'class bound ljStateValid',
'class closed ljStateInvalid',
// the spec has no receive from closed, so the rejected call is a loop on it, drawn round like the others
`closed --> closed : ${rejectedCall('receive')}`,
'%% lj-self-loops: edge5 edge6 edge7 edge11 edge13',
]));
const send = focusOnError ? dimmedMethod('send') : 'send';
// a single dimmed method keeps its name
for (const state of ['unbound', 'bound', 'connected']) {
expect(diagram).toContain(`${state} --> ${state} : ${calledMethod('receive')}<br/>${send}`);
expect(diagram).toContain(`${state} --> ${state} : ${allowedCall('receive')}<br/>${send}`);
}
// accepted states that are not possible get only a class, without a mark in their name
expect(diagram.filter(line => /^(state|class) .*\b(unbound|connected)\b/.test(line)))
Expand Down Expand Up @@ -157,7 +162,7 @@ describe('state error focus', () => {
);

expect(lines(createMermaidDiagram(sm, 'TB', false, true))).toEqual(expect.arrayContaining([
`bound --> bound : ${calledMethod('receive')}<br/>${collapsedMethods(['send', 'getPort', 'getOption'], '+3 more')}`,
`bound --> bound : ${allowedCall('receive')}<br/>${collapsedMethods(['send', 'getPort', 'getOption'], '+3 more')}`,
`unbound --> bound : ${collapsedMethods(['bind', 'bindAll'], '2 methods')}`,
]));
});
Expand All @@ -184,7 +189,26 @@ describe('state error focus', () => {
sm.transitions.push({ from: 'bound', to: 'bound', label: 'receiveAll' });

expect(lines(createMermaidDiagram(sm, 'TB', false, true)))
.toContain(`bound --> bound : ${calledMethod('receive')}<br/>${collapsedMethods(['send', 'receiveAll'], '+2 more')}`);
.toContain(`bound --> bound : ${allowedCall('receive')}<br/>${collapsedMethods(['send', 'receiveAll'], '+2 more')}`);
});

it('draws a transition of the called method from a rejecting state as the rejected call, without a loop', () => {
const sm = datagramSocket();
sm.transitions.push({ from: 'closed', to: 'closed', label: 'receive', fromCondition: 'retries(this) > 0' });

const diagram = createMermaidDiagram(sm, 'TB', true, true);
expect(lines(diagram)).toContain(`closed --> closed : <span class="state-cond state-cond-pre">[retries(this) &gt; 0]</span> ${rejectedCall('receive')}`);
expect(diagram.match(/closed --> closed/g)).toHaveLength(1);
});

it('puts the rejected call on the loop a rejecting state already has, first and never dimmed', () => {
const sm = datagramSocket();
sm.transitions.push({ from: 'closed', to: 'closed', label: 'close' });

expect(lines(createMermaidDiagram(sm, 'TB', false, true))).toContain(`closed --> closed : ${rejectedCall('receive')}<br/>${dimmedMethod('close')}`);
const shown = createMermaidDiagram(sm, 'TB', false, false);
expect(lines(shown)).toContain(`closed --> closed : ${rejectedCall('receive')}<br/>close`);
expect(shown.match(/closed --> closed/g)).toHaveLength(1);
});

it('does not focus without accepted states', () => {
Expand All @@ -207,7 +231,7 @@ describe('state error focus', () => {
expect(focus).toMatchObject({ unknownState: true, validStates: [], invalidStates: [] });
const diagram = createMermaidDiagram(sm, 'TB', false, true);
expect(lines(diagram)).toContain('class unbound,bound,connected ljStateAccepted');
expect(diagram).not.toMatch(/ljStateValid|ljStateInvalid|ljStateDimmed|" as /);
expect(diagram).not.toMatch(/ljStateValid|ljStateInvalid|ljStateDimmed|" as |lj-call-rejected/);
// only the failed method stays bright
expect(lines(diagram)).toEqual(expect.arrayContaining([`unbound --> bound : ${dimmedMethod('bind')}`, `broken --> broken : ${dimmedMethod('repair')}`]));
});
Expand All @@ -219,13 +243,15 @@ describe('state error focus', () => {
'state "✕ childrenAllowed" as childrenAllowed',
'class childrenAllowed ljStateInvalid',
'class maybeHasChildren ljStateAccepted',
`maybeHasChildren --> maybeHasChildren : ${calledMethod('getFirstChild')}`,
`maybeHasChildren --> maybeHasChildren : ${allowedCall('getFirstChild')}`,
`childrenAllowed --> maybeHasChildren : ${dimmedMethod('add')}`,
`maybeHasChildren --> childrenAllowed : ${dimmedMethod('removeAllChildren')}`,
`childrenAllowed --> childrenAllowed : ${rejectedCall('getFirstChild')}`,
]));
expect(diagram.join('\n')).not.toMatch(/maybeHasChildren" as|ljStateValid|ljStateDimmed/);
// the constructor is dimmed although it leads to a possible state
// the constructor is dimmed although it leads to a possible state, the rejected call never is
expect(dimmedTransitions(diagram.join('\n'))).toEqual(['%% lj-dimmed-transitions: edge0 edge1 edge2']);
expect(selfLoops(diagram.join('\n'))).toEqual(['%% lj-self-loops: edge3 edge4']);
});

it('only highlights the possible states when the accepted states are unknown', () => {
Expand All @@ -234,7 +260,9 @@ describe('state error focus', () => {
expect(getStateErrorFocus(sm)).toBeNull();
const diagram = createMermaidDiagram(sm, 'TB', false, true);
expect(diagram).toBe(createMermaidDiagram(sm, 'TB', false, false));
expect(diagram).toContain(`maybeHasChildren --> maybeHasChildren : ${calledMethod('getFirstChild')}`);
// nothing says where the call is allowed, so the called method is not coloured
expect(lines(diagram)).toContain('maybeHasChildren --> maybeHasChildren : getFirstChild');
expect(diagram).not.toContain('lj-call');
expect(diagram).toContain('class childrenAllowed ljStateErrorActual');
expect(diagram).not.toMatch(/ljStateValid|ljStateInvalid|ljStateAccepted|ljStateDimmed|" as /);
});
Expand Down Expand Up @@ -432,19 +460,22 @@ describe('a state error on several state sets', () => {
const sms = door();
const [doorState, lockState] = sms.map(sm => lines(createMermaidDiagram(sm, 'TB', true, false, sms)));

expect(lockState).toContain(`unlocked --> unlocked : ${guard('doorState(this) == closed')} ${calledMethod('open')}`);
expect(doorState).toContain(`closed --> opened : ${guard(unmet('lockState(this) == unlocked'))} open`);
expect(lockState).toContain(`unlocked --> unlocked : ${guard('doorState(this) == closed')} ${allowedCall('open')}`);
expect(lockState).toContain(`locked --> locked : ${rejectedCall('open')}`);
// the call is allowed from closed, only its condition on the other state set is unmet
expect(doorState).toContain(`closed --> opened : ${guard(unmet('lockState(this) == unlocked'))} ${allowedCall('open')}`);
expect(doorState).toContain(`closed --> closed : ${guard('lockState(this) != locked')} lock`);
expect(doorState.join('\n')).not.toContain('lj-call-rejected');
// the unmet condition stays when conditions are collapsed
expect(lines(createMermaidDiagram(sms[0], 'TB', false, false, sms)))
.toEqual(expect.arrayContaining([`closed --> opened : ${guard(unmet('lockState(this) == unlocked'))} open`, 'closed --> closed : lock']));
.toEqual(expect.arrayContaining([`closed --> opened : ${guard(unmet('lockState(this) == unlocked'))} ${allowedCall('open')}`, 'closed --> closed : lock']));
// only the clauses the actual state does not meet are marked
sms[0].transitions[0].fromCondition = 'lockState(this) == unlocked && (size(this) > 0 || ready(this))';
expect(lines(createMermaidDiagram(sms[0], 'TB', true, false, sms)))
.toContain(`closed --> opened : ${guard(`${unmet('lockState(this) == unlocked')} &amp;&amp; (size(this) &gt; 0 || ready(this))`)} open`);
.toContain(`closed --> opened : ${guard(`${unmet('lockState(this) == unlocked')} &amp;&amp; (size(this) &gt; 0 || ready(this))`)} ${allowedCall('open')}`);
// without a condition on the state set in a wrong state, the call stays marked
sms[0].transitions[0].fromCondition = 'size(this) > 0';
expect(lines(createMermaidDiagram(sms[0], 'TB', false, false, sms))).toContain(`closed --> opened : ${calledMethod('open')}`);
expect(lines(createMermaidDiagram(sms[0], 'TB', false, false, sms))).toContain(`closed --> opened : ${allowedCall('open')}`);
});

it('draws a transition that keeps its state as a round loop', async () => {
Expand Down
78 changes: 52 additions & 26 deletions client/src/webview/diagram.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,18 +111,23 @@ export function createMermaidDiagram(

// group transitions by from/to states and merge labels
const transitionMap = new Map<string, { bright: string[], dimmed: CollapsibleLabel[] }>();
// the possible states that reject the call and have a transition of the called method, drawn as the rejected call
const rejectedFrom = new Set<string>();
sm.transitions.forEach(transition => {
const key = `${transition.from}|${transition.to}`;
const isCalledMethod = transition.label === sm.errorContext?.calledMethod;
// in focus mode, only the failed method stays bright
const dimmed = collapse && !isCalledMethod;
const unmet = hasUnmetCondition(transition, sm, stateSets, rejectingStateSets);
const rejected = isCalledMethod && !!errorFocus?.invalidStates.includes(transition.from);
if (rejected) rejectedFrom.add(transition.from);
// without the accepted states, nothing says where the call is allowed, and there is no legend to explain a colour
const label = getTransitionLabel(
transition.label,
getFromConditionLabel(transition.fromCondition, stateSets, unmet ? rejectingStateSets : null, showConditions),
transition.toCondition,
showConditions,
isCalledMethod && !unmet,
rejected ? 'rejected' : isCalledMethod && errorFocus ? 'allowed' : null,
);
if (!transitionMap.has(key)) transitionMap.set(key, { bright: [], dimmed: [] });
const group = transitionMap.get(key)!;
Expand All @@ -132,6 +137,18 @@ export function createMermaidDiagram(
else if (!group.dimmed.some(method => method.name === name)) group.dimmed.push({ name, label });
});

// the spec has no transition of the call from a state that rejects it, so the rejected call is drawn as a loop
// on each such state, on the loop the state already has since the layout nests a second one around the first;
// it is no spec transition, so it is never dimmed, collapsed, or counted
if (errorFocus?.calledMethod) {
const rejectedCall = getCallLabel(escapeMermaidLabel(errorFocus.calledMethod), 'rejected');
errorFocus.invalidStates.filter(state => !rejectedFrom.has(state)).forEach(state => {
const key = `${state}|${state}`;
if (!transitionMap.has(key)) transitionMap.set(key, { bright: [], dimmed: [] });
transitionMap.get(key)!.bright.unshift(rejectedCall);
});
}

// add transitions, dimming those whose methods are all dimmed
transitionMap.forEach(({ bright, dimmed }, key) => {
const [from, to] = key.split('|');
Expand Down Expand Up @@ -185,26 +202,31 @@ function getCollapsedLabel(bright: string[], dimmed: CollapsibleLabel[], noun: '
* Gets the label of a transition: the condition it needs before its method, and the one it sets after,
* e.g. [lockState(this) == unlocked] open [doorState(this) == opened]
* @param fromCondition the condition before, from getFromConditionLabel
* @param isFailedCall whether to mark the method as the rejected call
* @param call whether the method is the called one, allowed from the transition's state or rejected there
*/
function getTransitionLabel(
label: string,
fromCondition: string | null,
toCondition?: string | null,
showConditions = false,
isFailedCall = false,
call: CallKind | null = null,
): string {
const escapedLabel = escapeMermaidLabel(label);
const methodLabel = isFailedCall
? `<span class="lj-state-error-method">${escapedLabel}</span>`
: escapedLabel;
return [
fromCondition,
methodLabel,
call ? getCallLabel(escapedLabel, call) : escapedLabel,
showConditions ? getConditionLabel('post', toCondition) : '',
].filter(Boolean).join(' ');
}

// how a transition of the called method is drawn: green where the spec allows the call, red and crossed where it rejects it
type CallKind = 'allowed' | 'rejected';

// the called method, coloured once rendered with its transition
function getCallLabel(escapedMethod: string, call: CallKind): string {
return `<span class="lj-call-${call}">${call === 'rejected' ? `${INVALID_STATE_ICON} ` : ''}${escapedMethod}</span>`;
}

/**
* Whether a transition of the rejected call, from a possible state, needs a state of a state set whose state rejects it
*/
Expand Down Expand Up @@ -272,7 +294,7 @@ export async function renderMermaidDiagram(document: any, window: any) {
const dimmedTransitions = Array.from(mermaidElements, (element: any) => getListedTransitions(element.textContent, DIMMED_TRANSITIONS_COMMENT));
const selfLoops = Array.from(mermaidElements, (element: any) => getListedTransitions(element.textContent, SELF_LOOPS_COMMENT));
await mermaid.run({ nodes: mermaidElements });
highlightErrorTransitions(document);
colourCallTransitions(document);
mermaidElements.forEach((element: any, index: number) => {
markTransitions(element, dimmedTransitions[index], 'lj-dimmed');
roundSelfLoops(element, selfLoops[index]);
Expand All @@ -288,17 +310,20 @@ export async function renderMermaidDiagram(document: any, window: any) {
}
}

function highlightErrorTransitions(document: any) {
document.querySelectorAll('.lj-state-error-method').forEach((methodLabel: any) => {
const label = methodLabel.closest('g.label[data-id]');
const edgeId = label?.getAttribute('data-id');
const svg = label?.ownerSVGElement;
if (!edgeId || !svg) return;

const transition = svg.querySelector(`path.transition[data-id="${edgeId}"]`);
if (!transition || transition.classList.contains('lj-state-error-transition')) return;
transition.classList.add('lj-state-error-transition');
highlightTransitionMarker(svg, transition, edgeId);
// colours the line and arrowhead of each transition of the called method like its label
function colourCallTransitions(document: any) {
(['allowed', 'rejected'] as CallKind[]).forEach(call => {
document.querySelectorAll(`.lj-call-${call}`).forEach((methodLabel: any) => {
const label = methodLabel.closest('g.label[data-id]');
const edgeId = label?.getAttribute('data-id');
const svg = label?.ownerSVGElement;
if (!edgeId || !svg) return;

const transition = svg.querySelector(`path.transition[data-id="${edgeId}"]`);
if (!transition || transition.classList.contains(`lj-call-${call}-transition`)) return;
transition.classList.add(`lj-call-${call}-transition`);
colourTransitionMarker(svg, transition, edgeId, call);
});
});
}

Expand Down Expand Up @@ -454,20 +479,21 @@ function getLinePoints(svg: Element): Point[] {
});
}

function highlightTransitionMarker(svg: any, transition: any, edgeId: string) {
// the arrowhead is shared by every transition, so the coloured one gets a copy of its own
function colourTransitionMarker(svg: any, transition: any, edgeId: string, call: CallKind) {
const markerReference = transition.getAttribute('marker-end');
const markerId = markerReference?.match(/^url\(#(.+)\)$/)?.[1];
if (!markerId) return;

const marker = svg.querySelector(`#${markerId}`);
if (!marker?.parentNode) return;

const highlightedMarker = marker.cloneNode(true);
const highlightedMarkerId = `${markerId}-lj-error-${edgeId}`;
highlightedMarker.setAttribute('id', highlightedMarkerId);
highlightedMarker.classList.add('lj-state-error-marker');
marker.parentNode.appendChild(highlightedMarker);
transition.setAttribute('marker-end', `url(#${highlightedMarkerId})`);
const colouredMarker = marker.cloneNode(true);
const colouredMarkerId = `${markerId}-lj-${call}-${edgeId}`;
colouredMarker.setAttribute('id', colouredMarkerId);
colouredMarker.classList.add(`lj-call-${call}-marker`);
marker.parentNode.appendChild(colouredMarker);
transition.setAttribute('marker-end', `url(#${colouredMarkerId})`);
}

/**
Expand Down
4 changes: 2 additions & 2 deletions client/src/webview/script.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ describe('webview script', () => {
const copied: string = writeText.mock.calls[0][0];
expect(copied.match(/stateDiagram-v2/g)).toHaveLength(2);
expect(copied).toContain('Idle --> Busy');
expect(copied).not.toMatch(/ljState|lj-dimmed|lj-state-error-method/);
expect(copied).not.toMatch(/ljState|lj-dimmed|lj-call-/);
});

it('copies the Mermaid source without the error overlay', async () => {
Expand All @@ -330,7 +330,7 @@ describe('webview script', () => {

expect(root.querySelector('.mermaid')?.textContent).toContain('ljStateDimmed');
expect(writeText.mock.calls[1][0]).toBe(plain);
expect(plain).not.toMatch(/ljState|lj-dimmed|lj-state-error-method/);
expect(plain).not.toMatch(/ljState|lj-dimmed|lj-call-/);
});

it('opens another state error focused after showing the full diagram of the previous one', () => {
Expand Down
Loading
Loading