Skip to content

Commit

Permalink
[Lens] Enable report sharing (#153429)
Browse files Browse the repository at this point in the history
## Summary

Fixes #130438

This PR introduces the PNG/PDF reporting feature within Lens editor.
**Note** each reporting tasks is generating a shortURL SO in addition of
the reporting job SO. There's a reusing mechanism but it applies only to
the same config within the same session.

* [x] Enable reporting for ~~`lens_visualization` type~~ `lens` type
  * [x] Introduce disabled state within the reporter logic
  * [x] Extends the logic to support the custom URL types in Lens
* [x] Make reporting list page to support `lens_visualization` object
type
    * migrated `lens_visualization` to `lens` and used the app icon
* [x] Extends the custom CSS styling to handle specific Lens editor
layout
* [x] Introduce logic for `renderComplete` within the Lens editor
  * [x] Loading logic
  * [x] Trigger `renderComplete` event for the right node
* [x] Add `.hide-for-sharing` class where needed
  * [x] Add the `.stretch-for-sharing` where needed
* Improve layout settings to have a better fit of some charts
  * Maybe this can be addressed as separate issue? 
* Check the `renderComplete` for the RegionMap external plugin =>
separate issue
* Write tests
  * [x] Functional tests

Reporting page:
<img width="1255" alt="Screenshot 2023-03-24 at 15 25 12"
src="https://user-images.githubusercontent.com/924948/227552385-1b52a0ae-8902-4972-acf3-323093a7b840.png">



**Note**: at the moment the reporting name follows the CSV naming
convention of `unsaved` for unsaved Lens visualizations. The legacy
Agg-based editor uses instead a namming pattern as follow:
`Visualization <timestamp>.png`.

Final results:
| Chart type | PNG result |
| ------ | ----- |
| Stacked bar chart |
![unsaved](https://user-images.githubusercontent.com/924948/226881443-05b862c0-6637-4b7f-a461-160a69f2bb6c.PNG)
|
| Vertical bar chart | ![unsaved
(1)](https://user-images.githubusercontent.com/924948/226881523-10c0e91a-6ca3-4161-bd11-738d5f6465db.PNG)
|
| Horizontal stacked bar chart | ![unsaved
(2)](https://user-images.githubusercontent.com/924948/226881585-06fe2904-cba1-402f-a67c-549ce09cd83e.PNG)
|
| Horizontal bar chart | ![unsaved
(3)](https://user-images.githubusercontent.com/924948/226881619-0d135b19-d401-4b13-934e-b7aa23ab2792.PNG)
|
| Datatable | ![unsaved
(4)](https://user-images.githubusercontent.com/924948/226881716-f7543803-bd00-433a-85bc-09b0a2c2c7c5.PNG)
|
| Horizontal gauge | ![unsaved
(5)](https://user-images.githubusercontent.com/924948/226881766-54fccf0c-3266-411b-ac43-8c37855a44eb.PNG)
|
| Vertical gauge | ![unsaved
(6)](https://user-images.githubusercontent.com/924948/226881981-f3b5e007-2637-476a-ab43-1c5efa5e44e5.PNG)
|
| Legacy metric | ![unsaved
(7)](https://user-images.githubusercontent.com/924948/226882220-0c456c2d-8fc7-470e-94e1-f22e5ddcb052.PNG)
|
| Metric | ![unsaved
(8)](https://user-images.githubusercontent.com/924948/226882283-03f10b5b-fa36-402b-a3e0-70f49b2b5968.PNG)
|
| Metric with breakdown | ![unsaved
(9)](https://user-images.githubusercontent.com/924948/226882347-a4f53dfd-8c43-4432-b4c8-eea879c897d3.PNG)
|
| Area chart | ![unsaved
(10)](https://user-images.githubusercontent.com/924948/226882381-b7a81a05-9163-4582-8892-ef25bd803778.PNG)
|
| Line chart | ![unsaved
(11)](https://user-images.githubusercontent.com/924948/226882736-8ce49e82-31a1-435b-9ef9-19ea8e885993.PNG)
|
| Bar chart with annotation + reference lines | ![unsaved
(13)](https://user-images.githubusercontent.com/924948/226882841-0aeb5863-4ccb-426d-aae3-9e0afe19e599.PNG)
|
| Heatmap | ![unsaved
(14)](https://user-images.githubusercontent.com/924948/226883059-31ab11a2-7d9a-461c-a38c-158b03e916e1.PNG)
|
| Donut chart | ![unsaved
(15)](https://user-images.githubusercontent.com/924948/226883107-e7cd922e-a488-4ab5-add6-6aac8657f295.PNG)
|
| Pie chart | ![unsaved
(17)](https://user-images.githubusercontent.com/924948/226883158-d7f285a6-63e7-4bf5-9839-ee5c48b25e22.PNG)
|
| Treemap | ![unsaved
(18)](https://user-images.githubusercontent.com/924948/226883250-2b770885-6275-4f07-8eee-1a4d98aef974.PNG)
|
| Mosaic | ![unsaved
(16)](https://user-images.githubusercontent.com/924948/226883328-96cd2461-06e5-4995-8d38-1235b8774781.PNG)
|
| Waffle | ![unsaved
(19)](https://user-images.githubusercontent.com/924948/226883373-c2f7e041-f45d-44ac-982c-8355b44e5fbf.PNG)
|
| Region Map | ![Lens Visualization 2023-03-31T12_47_48
392+02_00](https://user-images.githubusercontent.com/924948/229101825-dc54a9e8-f89b-4901-b7e7-76a983bc3bd0.PNG)
|

### Checklist

Delete any items that are not applicable to this PR.

- [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [ ] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [ ] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [ ] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [ ] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [ ] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)


### Risk Matrix

Delete this section if it is not applicable to this PR.

Before closing this PR, invite QA, stakeholders, and other developers to
identify risks that should be tested prior to the change/feature
release.

When forming the risk matrix, consider some of the following examples
and how they may potentially impact the change:

| Risk | Probability | Severity | Mitigation/Notes |

|---------------------------|-------------|----------|-------------------------|
| Multiple Spaces&mdash;unexpected behavior in non-default Kibana Space.
| Low | High | Integration tests will verify that all features are still
supported in non-default Kibana Space and when user switches between
spaces. |
| Multiple nodes&mdash;Elasticsearch polling might have race conditions
when multiple Kibana nodes are polling for the same tasks. | High | Low
| Tasks are idempotent, so executing them multiple times will not result
in logical error, but will degrade performance. To test for this case we
add plenty of unit tests around this logic and document manual testing
procedure. |
| Code should gracefully handle cases when feature X or plugin Y are
disabled. | Medium | High | Unit tests will verify that any feature flag
or plugin combination still results in our service operational. |
| [See more potential risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |


### For maintainers

- [ ] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)

---------

Co-authored-by: Stratoula Kalafateli <efstratia.kalafateli@elastic.co>
Co-authored-by: Tim Sullivan <tsullivan@users.noreply.github.com>
Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com>
  • Loading branch information
4 people committed Apr 12, 2023
1 parent 6365d54 commit 41170fe
Show file tree
Hide file tree
Showing 25 changed files with 361 additions and 124 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export const downloadCsvShareProvider = ({
formatFactoryFn,
}: DownloadPanelShareOpts): ShareMenuProvider => {
const getShareMenuItems = ({ objectType, sharingData, onClose }: ShareContext) => {
if ('lens_visualization' !== objectType) {
if ('lens' !== objectType) {
return [];
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ describe('application-level user messages', () => {
activeDatasource: {
checkIntegrity: jest.fn(() => ['missing_pattern']),
} as unknown as Datasource,
activeDatasourceState: { state: {} },
activeDatasourceState: { isLoading: false, state: {} },
core: createCoreStartWithPermissions(),
...irrelevantProps,
})
Expand All @@ -166,7 +166,7 @@ describe('application-level user messages', () => {
activeDatasource: {
checkIntegrity: jest.fn(() => ['missing_pattern']),
} as unknown as Datasource,
activeDatasourceState: { state: {} },
activeDatasourceState: { isLoading: false, state: {} },
// user can go to management, but indexPatterns management is not accessible
core: createCoreStartWithPermissions({
navLinks: { management: true },
Expand All @@ -188,7 +188,7 @@ describe('application-level user messages', () => {
activeDatasource: {
checkIntegrity: jest.fn(() => ['missing_pattern']),
} as unknown as Datasource,
activeDatasourceState: { state: {} },
activeDatasourceState: { isLoading: false, state: {} },
// user can't go to management at all
core: createCoreStartWithPermissions({
navLinks: { management: false },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export const getApplicationUserMessages = ({
visualization: VisualizationState | undefined;
visualizationMap: VisualizationMap;
activeDatasource: Datasource | null | undefined;
activeDatasourceState: { state: unknown } | null;
activeDatasourceState: { isLoading: boolean; state: unknown } | null;
dataViews: DataViewsState;
core: CoreStart;
}): UserMessage[] => {
Expand Down
41 changes: 28 additions & 13 deletions x-pack/plugins/lens/public/app_plugin/lens_top_nav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import { getEsQueryConfig } from '@kbn/data-plugin/public';
import type { DataView } from '@kbn/data-views-plugin/public';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import { DataViewPickerProps } from '@kbn/unified-search-plugin/public';
import moment from 'moment';
import { LENS_APP_LOCATOR } from '../../common/locator/locator';
import { ENABLE_SQL } from '../../common/constants';
import { LensAppServices, LensTopNavActions, LensTopNavMenuProps } from './types';
import { toggleSettingsMenuOpen } from './settings_menu';
Expand Down Expand Up @@ -457,8 +459,9 @@ export const LensTopNavMenu = ({
isSaveable && application.capabilities.dashboard?.showWriteControls
);

const unsavedTitle = i18n.translate('xpack.lens.app.unsavedFilename', {
defaultMessage: 'unsaved',
const defaultLensTitle = i18n.translate('xpack.lens.app.share.defaultDashboardTitle', {
defaultMessage: 'Lens Visualization [{date}]',
values: { date: moment().toISOString(true) },
});
const additionalMenuEntries = useMemo(() => {
if (!visualization.activeId) return undefined;
Expand Down Expand Up @@ -574,13 +577,12 @@ export const LensTopNavMenu = ({
if (!share) {
return;
}
const sharingData = {
activeData,
csvEnabled,
title: title || unsavedTitle,
};

const { shareableUrl, savedObjectURL } = await getShareURL(
const {
shareableUrl,
savedObjectURL,
reportingLocatorParams: locatorParams,
} = await getShareURL(
shortUrlService,
{ application, data },
{
Expand All @@ -593,8 +595,20 @@ export const LensTopNavMenu = ({
visualization,
currentDoc,
adHocDataViews: adHocDataViews.map((dataView) => dataView.toSpec()),
}
},
shareUrlEnabled,
isCurrentStateDirty
);
const sharingData = {
activeData,
csvEnabled,
reportingDisabled: !csvEnabled,
title: title || defaultLensTitle,
locatorParams: {
id: LENS_APP_LOCATOR,
params: locatorParams,
},
};

share.toggleShareContextMenu({
anchorElement,
Expand All @@ -603,7 +617,7 @@ export const LensTopNavMenu = ({
shareableUrl: shareableUrl || '',
shareableUrlForSavedObject: savedObjectURL.href,
objectId: currentDoc?.savedObjectId,
objectType: 'lens_visualization',
objectType: 'lens',
objectTypeTitle: i18n.translate('xpack.lens.app.share.panelTitle', {
defaultMessage: 'visualization',
}),
Expand Down Expand Up @@ -735,7 +749,6 @@ export const LensTopNavMenu = ({
initialContextIsEmbedded,
activeData,
isSaveable,
shortUrlService,
application,
getIsByValueMode,
savingToLibraryPermitted,
Expand All @@ -746,7 +759,7 @@ export const LensTopNavMenu = ({
lensInspector,
title,
share,
unsavedTitle,
shortUrlService,
data,
filters,
query,
Expand All @@ -756,6 +769,8 @@ export const LensTopNavMenu = ({
visualizationMap,
visualization,
currentDoc,
adHocDataViews,
defaultLensTitle,
isCurrentStateDirty,
onAppLeave,
runSave,
Expand All @@ -770,7 +785,6 @@ export const LensTopNavMenu = ({
isOnTextBasedMode,
lensStore,
theme$,
adHocDataViews,
]);

const onQuerySubmitWrapped = useCallback(
Expand Down Expand Up @@ -1072,6 +1086,7 @@ export const LensTopNavMenu = ({
screenTitle={'lens'}
appName={'lens'}
displayStyle="detached"
className="hide-for-sharing"
/>
);
};
37 changes: 30 additions & 7 deletions x-pack/plugins/lens/public/app_plugin/share_action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@ function getShareURLForSavedObject(
);
}

function getShortShareableURL(
shortUrlService: (params: LensAppLocatorParams) => Promise<string>,
export function getLocatorParams(
data: LensAppServices['data'],
{
filters,
Expand All @@ -57,7 +56,9 @@ function getShortShareableURL(
visualizationMap,
visualization,
adHocDataViews,
}: ShareableConfiguration
currentDoc,
}: ShareableConfiguration,
isDirty: boolean
) {
const references = extractReferencesFromState({
activeDatasources: Object.keys(datasourceStates).reduce(
Expand All @@ -80,7 +81,7 @@ function getShortShareableURL(
const serializableDatasourceStates = datasourceStates as LensAppState['datasourceStates'] &
SerializableRecord;

return shortUrlService({
const snapshotParams = {
filters,
query,
resolvedDateRange: getResolvedDateRange(data.query.timefilter.timefilter),
Expand All @@ -90,16 +91,38 @@ function getShortShareableURL(
searchSessionId: data.search.session.getSessionId(),
references,
dataViewSpecs: adHocDataViews,
});
};

return {
shareURL: snapshotParams,
// for reporting use the shorten version when available
reporting:
currentDoc?.savedObjectId && !isDirty
? {
filters,
query,
resolvedDateRange: getResolvedDateRange(data.query.timefilter.timefilter),
savedObjectId: currentDoc?.savedObjectId,
}
: snapshotParams,
};
}

export async function getShareURL(
shortUrlService: (params: LensAppLocatorParams) => Promise<string>,
services: Pick<LensAppServices, 'application' | 'data'>,
configuration: ShareableConfiguration
configuration: ShareableConfiguration,
shareUrlEnabled: boolean,
isDirty: boolean
) {
const { shareURL: locatorParams, reporting: reportingLocatorParams } = getLocatorParams(
services.data,
configuration,
isDirty
);
return {
shareableUrl: await getShortShareableURL(shortUrlService, services.data, configuration),
shareableUrl: await (shareUrlEnabled ? shortUrlService(locatorParams) : undefined),
savedObjectURL: getShareURLForSavedObject(services, configuration.currentDoc),
reportingLocatorParams,
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export function FrameLayout(props: FrameLayoutProps) {
aria-labelledby="lns_ChartTitle"
>
<section
className={classNames('lnsFrameLayout__sidebar lnsFrameLayout__sidebar--left', {})}
className={'lnsFrameLayout__sidebar lnsFrameLayout__sidebar--left hide-for-sharing'}
aria-labelledby="dataPanelId"
>
<EuiScreenReaderOnly>
Expand All @@ -79,12 +79,18 @@ export function FrameLayout(props: FrameLayoutProps) {
</h2>
</EuiScreenReaderOnly>
{props.workspacePanel}
<div className="lnsFrameLayout__suggestionPanel">{props.suggestionsPanel}</div>
<div className="lnsFrameLayout__suggestionPanel hide-for-sharing">
{props.suggestionsPanel}
</div>
</section>
<section
className={classNames('lnsFrameLayout__sidebar lnsFrameLayout__sidebar--right', {
'lnsFrameLayout__sidebar-isFullscreen': isFullscreen,
})}
className={classNames(
'lnsFrameLayout__sidebar lnsFrameLayout__sidebar--right',
'hide-for-sharing',
{
'lnsFrameLayout__sidebar-isFullscreen': isFullscreen,
}
)}
aria-labelledby="configPanel"
>
<EuiScreenReaderOnly>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -404,10 +404,14 @@ export async function persistedStateToExpression(

export function getMissingIndexPattern(
currentDatasource: Datasource | null | undefined,
currentDatasourceState: { state: unknown } | null,
currentDatasourceState: { isLoading: boolean; state: unknown } | null,
indexPatterns: IndexPatternMap
) {
if (currentDatasourceState?.state == null || currentDatasource == null) {
if (
currentDatasourceState?.isLoading ||
currentDatasourceState?.state == null ||
currentDatasource == null
) {
return [];
}
const missingIds = currentDatasource.checkIntegrity(currentDatasourceState.state, indexPatterns);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ const defaultProps = {
getSuggestionForField: () => undefined,
lensInspector: getLensInspectorService(inspectorPluginMock.createStartContract()),
toggleFullscreen: jest.fn(),
getUserMessages: () => [],
addUserMessages: () => () => {},
getUserMessages: jest.fn(() => []),
addUserMessages: jest.fn(() => () => {}),
};

const toExpr = (
Expand Down Expand Up @@ -728,10 +728,10 @@ describe('workspace_panel', () => {
const mounted = await mountWithProvider(
<WorkspacePanel
{...defaultProps}
getUserMessages={getUserMessages}
datasourceMap={{
testDatasource: mockDatasource,
}}
getUserMessages={getUserMessages}
/>
);
instance = mounted.instance;
Expand All @@ -752,11 +752,12 @@ describe('workspace_panel', () => {
// but not yet applied their changes

let userMessages = [] as UserMessage[];
const getUserMessageFn = jest.fn(() => userMessages);

const mounted = await mountWithProvider(
<WorkspacePanel
{...defaultProps}
getUserMessages={() => userMessages}
getUserMessages={getUserMessageFn}
datasourceMap={{
testDatasource: mockDatasource,
}}
Expand Down
Loading

0 comments on commit 41170fe

Please sign in to comment.