Skip to content

Commit

Permalink
[Embeddable Rebuild] [Image] Migrate image embeddable to new embeddab…
Browse files Browse the repository at this point in the history
…le framework (#178544)

Closes #174962
Closes #165848
Closes #179521

## Summary

This PR converts the Image embeddable to the new React embeddable
framework. There should not be **any** changes in user-facing behaviour
(unless they were made intentionally, such as the small change described
[here](#178544 (comment)))
- therefore, testing of this PR should be focused on ensuring that no
behaviour is changed and/or broken with this refactor.

Since I was already doing a major overhaul, I took the opportunity to
clean up some of the image embeddable code, such as the small change
described
[here](#178544 (comment)).
Some of my changes are heavily influenced by the Presentation team style
(such as my changes to the file organization) so, if there are any
disagreements, I am 100% open to make changes - after all, this code
does not belong to us and we are not responsible for maintenance. Since
this is the first embeddable to be officially refactored (🎉), I expect
there to be lots of questions + feedback and that is okay!

### Small Style Changes
In order to close #165848, I did
two things:
1. I fixed the contrast of the `optionsMenuButton` as described in
#178544 (comment)
2. I ensured that the `PresentationPanel` enforces rounded corners in
view mode while keeping appearances consistent in edit mode (i.e. the
upper corners remain square so that it looks consistent with the title
bar):
    
    | | Before | After |
    |-----|--------|--------|
| **View mode** |
![image](https://github.com/elastic/kibana/assets/8698078/5ecda06f-a47d-41c5-9370-cf51af1489e4)
|
![image](https://github.com/elastic/kibana/assets/8698078/b3503016-63e2-4f70-9600-aa12fd650a67)
|
| **Edit mode** |
![image](https://github.com/elastic/kibana/assets/8698078/bf014f11-8e77-4814-8df3-b1d4cd780bf4)
|
![image](https://github.com/elastic/kibana/assets/8698078/3d8f4606-3d61-48b7-a2d0-f8e4787b8315)
|

### Checklist

- [x] 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)
- [x] [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
- [x] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
([FTR](https://buildkite.com/elastic/kibana-flaky-test-suite-runner/builds/5559))

![image](https://github.com/elastic/kibana/assets/8698078/2041b786-adfd-4f6e-b885-bc348a4a9e20)
- [x] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)

### 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: kibanamachine <[email protected]>
  • Loading branch information
Heenawter and kibanamachine authored Apr 8, 2024
1 parent d1e792a commit 826f7cb
Show file tree
Hide file tree
Showing 39 changed files with 613 additions and 470 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,9 @@ export const useBatchedPublishingSubjects = <SubjectsType extends [...AnyPublish
if (definedSubjects.length === 0) return;
const subscription = combineLatest(definedSubjects)
.pipe(
debounceTime(0),
// When a new observer subscribes to a BehaviorSubject, it immediately receives the current value. Skip this emit.
skip(1)
skip(1),
debounceTime(0)
)
.subscribe((values) => {
setLatestPublishedValues((lastPublishedValues) => {
Expand Down
16 changes: 3 additions & 13 deletions src/plugins/image_embeddable/kibana.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,8 @@
"id": "imageEmbeddable",
"server": false,
"browser": true,
"requiredPlugins": [
"embeddable",
"files",
"uiActions"
],
"optionalPlugins": [
"security",
"screenshotMode",
],
"requiredBundles": [
"kibanaUtils",
"kibanaReact"
]
"requiredPlugins": ["embeddable", "files", "uiActions", "kibanaReact"],
"optionalPlugins": ["security", "screenshotMode", "embeddableEnhanced"],
"requiredBundles": []
}
}
59 changes: 59 additions & 0 deletions src/plugins/image_embeddable/public/actions/create_image_action.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { i18n } from '@kbn/i18n';
import { CanAddNewPanel } from '@kbn/presentation-containers';
import { EmbeddableApiContext } from '@kbn/presentation-publishing';
import { IncompatibleActionError } from '@kbn/ui-actions-plugin/public';
import {
ADD_IMAGE_EMBEDDABLE_ACTION_ID,
IMAGE_EMBEDDABLE_TYPE,
} from '../image_embeddable/constants';
import { uiActionsService } from '../services/kibana_services';

const parentApiIsCompatible = async (parentApi: unknown): Promise<CanAddNewPanel | undefined> => {
const { apiCanAddNewPanel } = await import('@kbn/presentation-containers');
// we cannot have an async type check, so return the casted parentApi rather than a boolean
return apiCanAddNewPanel(parentApi) ? (parentApi as CanAddNewPanel) : undefined;
};

export const registerCreateImageAction = () => {
uiActionsService.registerAction<EmbeddableApiContext>({
id: ADD_IMAGE_EMBEDDABLE_ACTION_ID,
getIconType: () => 'image',
isCompatible: async ({ embeddable: parentApi }) => {
return Boolean(await parentApiIsCompatible(parentApi));
},
execute: async ({ embeddable: parentApi }) => {
const canAddNewPanelParent = await parentApiIsCompatible(parentApi);
if (!canAddNewPanelParent) throw new IncompatibleActionError();
const { openImageEditor } = await import('../components/image_editor/open_image_editor');
try {
const imageConfig = await openImageEditor({ parentApi: canAddNewPanelParent });

canAddNewPanelParent.addNewPanel({
panelType: IMAGE_EMBEDDABLE_TYPE,
initialState: { imageConfig },
});
} catch {
// swallow the rejection, since this just means the user closed without saving
}
},
getDisplayName: () =>
i18n.translate('imageEmbeddable.imageEmbeddableFactory.displayName', {
defaultMessage: 'Image',
}),
});

uiActionsService.attachAction('ADD_PANEL_TRIGGER', ADD_IMAGE_EMBEDDABLE_ACTION_ID);
if (uiActionsService.hasTrigger('ADD_CANVAS_ELEMENT_TRIGGER')) {
// Because Canvas is not enabled in Serverless, this trigger might not be registered - only attach
// the create action if the Canvas-specific trigger does indeed exist.
uiActionsService.attachAction('ADD_CANVAS_ELEMENT_TRIGGER', ADD_IMAGE_EMBEDDABLE_ACTION_ID);
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

import { i18n } from '@kbn/i18n';
import type { Trigger } from '@kbn/ui-actions-plugin/public';
import type { ImageEmbeddable } from '../image_embeddable';

export const IMAGE_CLICK_TRIGGER = 'IMAGE_CLICK_TRIGGER';

Expand All @@ -21,7 +20,3 @@ export const imageClickTrigger: Trigger = {
defaultMessage: 'Clicking the image will trigger the action',
}),
};

export interface ImageClickContext {
embeddable: ImageEmbeddable;
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { FilesContext } from '@kbn/shared-ux-file-context';
import { createMockFilesClient } from '@kbn/shared-ux-file-mocks';
import { ImageViewerContext } from '../image_viewer';
import { ImageEditorFlyout, ImageEditorFlyoutProps } from './image_editor_flyout';
import { imageEmbeddableFileKind } from '../imports';
import { imageEmbeddableFileKind } from '../../imports';

const validateUrl = jest.fn(() => ({ isValid: true }));

Expand All @@ -35,12 +35,7 @@ const ImageEditor = (props: Partial<ImageEditorFlyoutProps>) => {
validateUrl,
}}
>
<ImageEditorFlyout
validateUrl={validateUrl}
onCancel={() => {}}
onSave={() => {}}
{...props}
/>
<ImageEditorFlyout onCancel={() => {}} onSave={() => {}} {...props} />
</ImageViewerContext.Provider>
</FilesContext>
</I18nProvider>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@ import { FilePicker } from '@kbn/shared-ux-file-picker';
import { i18n } from '@kbn/i18n';
import { FormattedMessage } from '@kbn/i18n-react';
import type { AuthenticatedUser } from '@kbn/security-plugin/common';
import { FileImageMetadata, imageEmbeddableFileKind } from '../imports';
import { ImageConfig } from '../types';
import { FileImageMetadata, imageEmbeddableFileKind } from '../../imports';
import { ImageConfig } from '../../types';
import { ImageViewer } from '../image_viewer/image_viewer'; // use eager version to avoid flickering
import { ValidateUrlFn } from '../utils/validate_url';
import { validateImageConfig, DraftImageConfig } from '../utils/validate_image_config';
import { validateImageConfig, DraftImageConfig } from '../../utils/validate_image_config';
import { useImageViewerContext } from '../image_viewer/image_viewer_context';

/**
* Shared sizing css for image, upload placeholder, empty and not found state
Expand All @@ -56,13 +56,14 @@ export interface ImageEditorFlyoutProps {
onCancel: () => void;
onSave: (imageConfig: ImageConfig) => void;
initialImageConfig?: ImageConfig;
validateUrl: ValidateUrlFn;
user?: AuthenticatedUser;
}

export function ImageEditorFlyout(props: ImageEditorFlyoutProps) {
const isEditing = !!props.initialImageConfig;
const { euiTheme } = useEuiTheme();
const { validateUrl } = useImageViewerContext();

const [fileId, setFileId] = useState<undefined | string>(() =>
props.initialImageConfig?.src?.type === 'file' ? props.initialImageConfig.src.fileId : undefined
);
Expand All @@ -78,7 +79,7 @@ export function ImageEditorFlyout(props: ImageEditorFlyoutProps) {
props.initialImageConfig?.src?.type === 'url' ? props.initialImageConfig.src.url : ''
);
const [srcUrlError, setSrcUrlError] = useState<string | null>(() => {
if (srcUrl) return props.validateUrl(srcUrl)?.error ?? null;
if (srcUrl) return validateUrl(srcUrl)?.error ?? null;
return null;
});
const [isFilePickerOpen, setIsFilePickerOpen] = useState<boolean>(false);
Expand Down Expand Up @@ -108,7 +109,7 @@ export function ImageEditorFlyout(props: ImageEditorFlyoutProps) {
};

const isDraftImageConfigValid = validateImageConfig(draftImageConfig, {
validateUrl: props.validateUrl,
validateUrl,
});

const onSave = () => {
Expand Down Expand Up @@ -224,11 +225,7 @@ export function ImageEditorFlyout(props: ImageEditorFlyoutProps) {
{!isDraftImageConfigValid ? (
<EuiEmptyPrompt
css={css`
max-width: none;
${CONTAINER_SIZING_CSS}
.euiEmptyPrompt__main {
height: 100%;
}
max-inline-size: none !important;
`}
iconType="image"
color="subdued"
Expand Down Expand Up @@ -289,7 +286,7 @@ export function ImageEditorFlyout(props: ImageEditorFlyoutProps) {
onChange={(e) => {
const url = e.target.value;

const { isValid, error } = props.validateUrl(url);
const { isValid, error } = validateUrl(url);
if (!isValid) {
setSrcUrlError(error!);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@
* Side Public License, v 1.
*/

export * from './configure_image';
export { openImageEditor } from './open_image_editor';
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import React from 'react';

import { tracksOverlays, CanAddNewPanel } from '@kbn/presentation-containers';
import { toMountPoint } from '@kbn/react-kibana-mount';
import { FilesContext } from '@kbn/shared-ux-file-context';

import { ImageConfig } from '../../image_embeddable/types';
import { FileImageMetadata, imageEmbeddableFileKind } from '../../imports';
import { coreServices, filesService, securityService } from '../../services/kibana_services';
import { createValidateUrl } from '../../utils/validate_url';
import { ImageViewerContext } from '../image_viewer/image_viewer_context';

export const openImageEditor = async ({
parentApi,
initialImageConfig,
}: {
parentApi: CanAddNewPanel;
initialImageConfig?: ImageConfig;
}): Promise<ImageConfig> => {
const { ImageEditorFlyout } = await import('./image_editor_flyout');

const { overlays, theme, i18n, http } = coreServices;
const user = securityService ? await securityService.authc.getCurrentUser() : undefined;
const filesClient = filesService.filesClientFactory.asUnscoped<FileImageMetadata>();

/**
* If available, the parent API will keep track of which flyout is open and close it
* if the app changes, disable certain actions when the flyout is open, etc.
*/
const overlayTracker = tracksOverlays(parentApi) ? parentApi : undefined;

return new Promise((resolve, reject) => {
const onSave = (imageConfig: ImageConfig) => {
resolve(imageConfig);
flyoutSession.close();
overlayTracker?.clearOverlays();
};

const onCancel = () => {
reject();
flyoutSession.close();
overlayTracker?.clearOverlays();
};

const flyoutSession = overlays.openFlyout(
toMountPoint(
<FilesContext client={filesClient}>
<ImageViewerContext.Provider
value={{
getImageDownloadHref: (fileId: string) => {
return filesClient.getDownloadHref({
id: fileId,
fileKind: imageEmbeddableFileKind.id,
});
},
validateUrl: createValidateUrl(http.externalUrl),
}}
>
<ImageEditorFlyout
user={user}
onCancel={onCancel}
onSave={onSave}
initialImageConfig={initialImageConfig}
/>
</ImageViewerContext.Provider>
</FilesContext>,
{ theme, i18n }
),
{
onClose: () => {
onCancel();
},
ownFocus: true,
'data-test-subj': 'createImageEmbeddableFlyout',
}
);

overlayTracker?.openOverlay(flyoutSession);
});
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import React, { useEffect, useState } from 'react';

import { PublishingSubject, useBatchedPublishingSubjects } from '@kbn/presentation-publishing';

import { imageClickTrigger } from '../actions';
import { ImageEmbeddableApi } from '../image_embeddable/types';
import { FileImageMetadata, FilesClient, imageEmbeddableFileKind } from '../imports';
import { coreServices, screenshotModeService, uiActionsService } from '../services/kibana_services';
import { ImageConfig } from '../types';
import { createValidateUrl } from '../utils/validate_url';
import { ImageViewer } from './image_viewer';
import { ImageViewerContext } from './image_viewer/image_viewer_context';

import './image_embeddable.scss';

interface ImageEmbeddableProps {
api: ImageEmbeddableApi & {
setDataLoading: (loading: boolean | undefined) => void;
imageConfig$: PublishingSubject<ImageConfig>;
};
filesClient: FilesClient<FileImageMetadata>;
}

export const ImageEmbeddable = ({ api, filesClient }: ImageEmbeddableProps) => {
const [imageConfig, dynamicActionsState] = useBatchedPublishingSubjects(
api.imageConfig$,
api.dynamicActionsState$
);
const [hasTriggerActions, setHasTriggerActions] = useState(false);

useEffect(() => {
/**
* set the loading to `true` any time the image changes; the ImageViewer component
* is responsible for setting loading to `false` again once the image loads
*/
api.setDataLoading(true);
}, [api, imageConfig]);

useEffect(() => {
// set `hasTriggerActions` depending on whether or not the image has at least one drilldown
setHasTriggerActions((dynamicActionsState?.dynamicActions.events ?? []).length > 0);
}, [dynamicActionsState]);

return (
<ImageViewerContext.Provider
value={{
getImageDownloadHref: (fileId: string) => {
return filesClient.getDownloadHref({
id: fileId,
fileKind: imageEmbeddableFileKind.id,
});
},
validateUrl: createValidateUrl(coreServices.http.externalUrl),
}}
>
<ImageViewer
data-rendering-count={1} // TODO: Remove this as part of https://github.com/elastic/kibana/issues/179376
className="imageEmbeddableImage"
imageConfig={imageConfig}
isScreenshotMode={screenshotModeService?.isScreenshotMode()}
onLoad={() => {
api.setDataLoading(false);
}}
onError={() => {
api.setDataLoading(false);
}}
onClick={
// note: passing onClick enables the cursor pointer style, so we only pass it if there are compatible actions
hasTriggerActions
? () => {
uiActionsService.executeTriggerActions(imageClickTrigger.id, {
embeddable: api,
});
}
: undefined
}
/>
</ImageViewerContext.Provider>
);
};
File renamed without changes
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import React from 'react';
import { render } from '@testing-library/react';
import { ImageViewer } from './image_viewer';
import { ImageViewerContext } from './image_viewer_context';
import { ImageConfig } from '../types';
import { ImageConfig } from '../../types';

const validateUrl = jest.fn(() => ({ isValid: true }));

Expand Down
Loading

0 comments on commit 826f7cb

Please sign in to comment.