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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ The component is the default export of `@opencor/plot`, and is also exported as
| `PlotCsvExportProgressEvent` | `{ type: 'progress'; percent: number }` | An export to CSV has made some progress: `percent` goes from 0 to 100 (an integer). |
| `PlotCsvExportFinishedEvent` | `{ type: 'finished'; success: boolean }` | An export to CSV has finished, whether successfully (and the file was downloaded) or not. |
| `PlotImageExportEvent` | `{ action: 'copy' \| 'export'; format: 'jpeg' \| 'png' \| 'svg' \| 'webp'; success: boolean }` | The payload of the [`imageExport`](#events) event: whether the plot was copied to the clipboard (always as PNG) or exported to an image file, in which format, and whether it worked. |
| `PlotContextMenuEvent` | `{ clientX: number; clientY: number; usingKeyboard: boolean; items: ContextMenuItem[] }` | The payload of the [`contextMenu`](#events) event: where the context menu was requested (in client coordinates), whether it was requested using the keyboard (in which case the custom menu should take the keyboard focus), and the items that our context menu would have shown. |
| `PlotContextMenuEvent` | `{ clientX: number; clientY: number; usingKeyboard: boolean; items: ContextMenuItem[] }` | The payload of the [`contextMenu`](#events) event: where the context menu was requested (in client coordinates), whether it was requested using the keyboard (in which case the custom menu should take the keyboard focus), and the items that our context menu would have shown. These items reflect the plot as it was when the context menu was requested and don't get updated if the data changes while the custom context menu is shown, but their commands always act on the plot as it is when they are chosen. |
| `ContextMenuItem` | `ContextMenuAction \| ContextMenuSeparator` | An item of a context menu. |
| `ContextMenuAction` | `{ label: string; icon?: IconName; checked?: boolean; command?: () => void; items?: ContextMenuItem[] }` | An action: its `label`, its `icon`, whether it is checked (only for a checkable action, e.g. to make an axis logarithmic), the `command` to call when it is chosen, and its submenu `items`, if any. |
| `ContextMenuSeparator` | `{ separator: true }` | A separator. |
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
],
"type": "module",
"types": "dist/index.d.ts",
"version": "0.20261125.4",
"version": "0.20261125.5",
"exports": {
".": {
"types": "./dist/index.d.ts",
Expand Down
97 changes: 93 additions & 4 deletions src/widgets/ContextMenuWidget.vue
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,9 @@ const onWindowBlurOrResize = (): void => {

const CONTEXT_MENU_SHOW_EVENT = 'opencor-context-menu-show';

let anchorX = 0;
let anchorY = 0;

const contextMenuId = Symbol('ContextMenuWidget');

const show = async (event: MouseEvent, usingKeyboard: boolean = false): Promise<void> => {
Expand All @@ -434,12 +437,15 @@ const show = async (event: MouseEvent, usingKeyboard: boolean = false): Promise<
window.addEventListener('resize', onWindowBlurOrResize);
}

anchorX = event.clientX;
anchorY = event.clientY;

const level: Level = {
items: props.items,
parentIndex: -1,
focusedIndex: -1,
left: event.clientX,
top: event.clientY
left: anchorX,
top: anchorY
};

if (usingKeyboard) {
Expand All @@ -450,10 +456,93 @@ const show = async (event: MouseEvent, usingKeyboard: boolean = false): Promise<

await vue.nextTick();

positionLevel(0, event.clientX, event.clientY);
positionLevel(0, anchorX, anchorY);
focusLevel(0);
};

// Updating of our context menu while it is shown.
// Note: our items may change while our context menu is shown (e.g., the label of an item may depend on some data that
// gets updated in the meantime), in which case we update our levels. Our items may get recreated, so we identify
// an item by its label, but only if no other item of its level has the same label, both before and after the
// update: the focused item of a level remains focused (even if it has moved) as long as it can be identified, and
// so does an open submenu as long as its parent item can be identified and still has a submenu. Otherwise, that
// item is no longer focused (so that choosing the focused item can never run another action than the one that was
// focused) and that submenu gets closed. We then position our levels again since their size may have changed.

const actionIndexes = (items: ContextMenuItem[], label: string): number[] => {
// Return the indexes of the actions with the given label in the given items.

return items.flatMap((item: ContextMenuItem, index: number) =>
!isSeparator(item) && item.label === label ? [index] : []
);
};

const matchingActionIndex = (items: ContextMenuItem[], oldItems: ContextMenuItem[], oldIndex: number): number => {
// Return the index, in the given items, of the action that has the same label as the action at the given index in the
// given old items, or -1 if there is no such action or if that label is not unique in the given items or old items
// (in which case we can't tell which action is which).

const oldItem = oldItems[oldIndex];

if (!oldItem || isSeparator(oldItem) || actionIndexes(oldItems, oldItem.label).length !== 1) {
return -1;
}

const indexes = actionIndexes(items, oldItem.label);

return indexes.length === 1 ? (indexes[0] as number) : -1;
};

const updateLevels = async (items: ContextMenuItem[]): Promise<void> => {
if (!levels.value.length) {
return;
}

const newLevels: Level[] = [];
let levelItems: ContextMenuItem[] = items;
let parentIndex = -1;

for (const [levelIndex, level] of levels.value.entries()) {
newLevels.push({
...level,
items: levelItems,
parentIndex,
focusedIndex: matchingActionIndex(levelItems, level.items, level.focusedIndex)
});

const nextLevel = levels.value[levelIndex + 1];

if (!nextLevel) {
break;
}

parentIndex = matchingActionIndex(levelItems, level.items, nextLevel.parentIndex);

const parentItem: ContextMenuItem | undefined = levelItems[parentIndex];

if (!parentItem || isSeparator(parentItem) || !parentItem.items) {
break;
}

levelItems = parentItem.items;
}

levels.value = newLevels;

await vue.nextTick();

newLevels.forEach((_level: Level, levelIndex: number) => {
positionLevel(levelIndex, anchorX, anchorY);
});
};

vue.watch(
() => props.items,
(items: ContextMenuItem[]) => {
void updateLevels(items);
}
);

const hide = (): void => {
if (!levels.value.length) {
return;
Expand Down Expand Up @@ -487,7 +576,7 @@ vue.onUnmounted(() => {
hide();
});

defineExpose({ show });
defineExpose({ show, hide });
</script>

<style scoped>
Expand Down
66 changes: 54 additions & 12 deletions src/widgets/PlotWidget.vue
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,9 @@ export interface PlotContextMenuEvent {
usingKeyboard: boolean;
/**
* The items of our context menu, including their state (e.g., whether an axis is logarithmic) and their command
* (e.g., to zoom in around where the context menu was requested).
* (e.g., to zoom in around where the context menu was requested). They reflect the plot as it was when the context
* menu was requested and don't get updated if the data changes while the custom context menu is shown, but their
* commands always act on the plot as it is when they are chosen.
*/
items: ContextMenuItem[];
}
Expand Down Expand Up @@ -1136,34 +1138,74 @@ const onLegendKeyDown = (event: KeyboardEvent, index: number): void => {
// (see legendTraceAction()).
// Note #2: our range editor is opened once our context menu has been hidden (and has given the keyboard focus back), so
// that it gets (and keeps) the keyboard focus, since it gets closed when it loses it.
// Note #3: we keep track of the trace of the legend item from which our context menu was requested using its key (see
// traceVisibilityKeys()) rather than its index, since our data may get updated while our context menu is
// shown, in which case the index of that trace may change (e.g., if a trace that comes before it gets removed)
// or that trace may get removed, in which case we hide our context menu (rather than remove the item for that
// trace, which would shift our other items and might result in the wrong item being chosen using the
// keyboard).

const contextMenuLegendIndex = vue.shallowRef<number | null>(null);
const contextMenuLegendKey = vue.shallowRef<string | null>(null);

const legendKey = (index: number | undefined): string | null => {
// Return the key of the trace of the given legend item, if any.

return index === undefined ? null : (traceVisibilityKeys(props.data.traces)[index] ?? null);
};

const legendTraceIndex = (key: string | null): number => {
// Return the current index of the trace with the given key, or -1 if there is no such trace (anymore).

return key === null ? -1 : traceVisibilityKeys(props.data.traces).indexOf(key);
};

const contextMenuLegendTraceIndex = vue.computed<number>(() => legendTraceIndex(contextMenuLegendKey.value));

vue.watch(contextMenuLegendTraceIndex, (index: number) => {
// Hide our context menu if the trace of the legend item from which it was requested has been removed, giving the
// keyboard focus back to our plot rather than to that legend item, which may now be the legend item of another trace.

if (index === -1 && contextMenuLegendKey.value !== null) {
contextMenuFocusTarget = null;

contextMenuRef.value?.hide();
}
});

const openRangeEditorLater = (type: AxisEnd): void => {
window.setTimeout(() => {
openRangeEditor(type);
});
};

const legendTraceMenuItem = (index: number): ContextMenuItem => {
// Return the item that our context menu starts with when it is requested from the given legend item.

const action = legendTraceAction(traceVisibilities.value, props.data.traces.length, index);
const legendTraceMenuItem = (key: string, index: number): ContextMenuItem => {
// Return the item that our context menu starts with when it is requested from the legend item of the trace with the
// given key, which is currently at the given index.
// Note: our data may get updated while our context menu is shown (see Note #3). Our context menu then gets our new
// items (see ContextMenuWidget's updateLevels()), but a custom context menu keeps the items that it was given,
// so the action of our item is determined again when our item is chosen, so that it applies to our trace (if it
// still exists) and to the visibility of our traces at that time.

return {
icon: 'eye',
label: action.label,
label: legendTraceAction(traceVisibilities.value, props.data.traces.length, index).label,
Comment thread
agarny marked this conversation as resolved.
Resolved
command: () => {
setTraceVisibilities(action.visibilities);
const currentIndex = legendTraceIndex(key);

if (currentIndex !== -1) {
setTraceVisibilities(
legendTraceAction(traceVisibilities.value, props.data.traces.length, currentIndex).visibilities
);
}
}
};
};

const contextMenuItems = vue.computed<ContextMenuItem[]>(() => [
...(contextMenuLegendIndex.value === null
...(contextMenuLegendKey.value === null || contextMenuLegendTraceIndex.value === -1
? []
: [
legendTraceMenuItem(contextMenuLegendIndex.value),
legendTraceMenuItem(contextMenuLegendKey.value, contextMenuLegendTraceIndex.value),
{
separator: true as const
}
Expand Down Expand Up @@ -1317,7 +1359,7 @@ const onContextMenu = (event: MouseEvent): void => {
const legendItemElement =
event.target instanceof Element ? event.target.closest<HTMLElement>('[data-legend-index]') : null;

contextMenuLegendIndex.value = legendItemElement ? Number(legendItemElement.dataset.legendIndex) : null;
contextMenuLegendKey.value = legendKey(legendItemElement ? Number(legendItemElement.dataset.legendIndex) : undefined);
contextMenuFocusTarget = legendItemElement;

// Keep track of where our context menu was requested, so that we can zoom in/out around that position (see zoomIn()
Expand Down Expand Up @@ -1369,7 +1411,7 @@ const showContextMenuUsingKeyboard = (legendItemElement?: HTMLElement, legendInd
hover.value = null;
contextMenuCenterFractions = {};
contextMenuShownUsingKeyboard = true;
contextMenuLegendIndex.value = legendIndex ?? null;
contextMenuLegendKey.value = legendKey(legendIndex);
contextMenuFocusTarget = legendItemElement ?? null;

showContextMenu(
Expand Down