Skip to content

Commit

Permalink
[8.15] fix issue with generating short url when copying share link (#…
Browse files Browse the repository at this point in the history
…201475) (#201624)

# Backport

This will backport the following commits from `main` to `8.15`:
- [fix issue with generating short url when copying share link
(#201475)](#201475)

<!--- Backport version: 8.9.8 -->

### Questions ?
Please refer to the [Backport tool
documentation](https://github.com/sqren/backport)

<!--BACKPORT [{"author":{"name":"Eyo O.
Eyo","email":"[email protected]"},"sourceCommit":{"committedDate":"2024-11-25T13:35:02Z","message":"fix
issue with generating short url when copying share link (#201475)\n\n##
Summary\r\n\r\nExtracted from
#197484, to make it\r\nmuch easier
to backport this fix to other releases that require
this\r\nfix.\r\n\r\nThis PR fixes the issue with generating short URL
for the share link.\r\n\r\n### Checklist\r\n\r\n<!-- Check the PR
satisfies following conditions. \r\n\r\nReviewers should verify this PR
satisfies this list as well.\r\n\r\n- [ ] Any text added follows [EUI's
writing\r\nguidelines](https://elastic.github.io/eui/#/guidelines/writing),
uses\r\nsentence case text and includes
[i18n\r\nsupport](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)\r\n-
[
]\r\n[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)\r\nwas
added for features that require explanation or tutorials -->\r\n- [x]
[Unit or
functional\r\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\r\nwere
updated or added to match the most common scenarios\r\n\r\n<!--\r\n- [ ]
If a plugin configuration key changed, check if it needs to
be\r\nallowlisted in the cloud and added to the
[docker\r\nlist](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)\r\n-
[ ] This was checked for breaking HTTP API changes, and any
breaking\r\nchanges have been approved by the breaking-change committee.
The\r\n`release_note:breaking` label should be applied in these
situations.\r\n- [ ] [Flaky
Test\r\nRunner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1)
was\r\nused on any tests changed\r\n- [ ] The PR description includes
the appropriate Release Notes section,\r\nand the correct
`release_note:*` label is applied per
the\r\n[guidelines](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)\r\n\r\n###
Identify risks\r\n\r\nDoes this PR introduce any risks? For example,
consider risks like hard\r\nto test bugs, performance regression,
potential of data loss.\r\n\r\nDescribe the risk, its severity, and
mitigation for each identified\r\nrisk. Invite stakeholders and evaluate
how to proceed before merging.\r\n\r\n- [ ] [See some
risk\r\nexamples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)\r\n-
[ ] ...\r\n\r\n-->\r\n\r\nCo-authored-by: Elastic Machine
<[email protected]>","sha":"197e606bdf812438dbcfe5bb783198a0ea874b52","branchLabelMapping":{"^v9.0.0$":"main","^v8.18.0$":"8.x","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["release_note:fix","v9.0.0","Team:SharedUX","backport:prev-major"],"number":201475,"url":"https://github.com/elastic/kibana/pull/201475","mergeCommit":{"message":"fix
issue with generating short url when copying share link (#201475)\n\n##
Summary\r\n\r\nExtracted from
#197484, to make it\r\nmuch easier
to backport this fix to other releases that require
this\r\nfix.\r\n\r\nThis PR fixes the issue with generating short URL
for the share link.\r\n\r\n### Checklist\r\n\r\n<!-- Check the PR
satisfies following conditions. \r\n\r\nReviewers should verify this PR
satisfies this list as well.\r\n\r\n- [ ] Any text added follows [EUI's
writing\r\nguidelines](https://elastic.github.io/eui/#/guidelines/writing),
uses\r\nsentence case text and includes
[i18n\r\nsupport](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)\r\n-
[
]\r\n[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)\r\nwas
added for features that require explanation or tutorials -->\r\n- [x]
[Unit or
functional\r\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\r\nwere
updated or added to match the most common scenarios\r\n\r\n<!--\r\n- [ ]
If a plugin configuration key changed, check if it needs to
be\r\nallowlisted in the cloud and added to the
[docker\r\nlist](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)\r\n-
[ ] This was checked for breaking HTTP API changes, and any
breaking\r\nchanges have been approved by the breaking-change committee.
The\r\n`release_note:breaking` label should be applied in these
situations.\r\n- [ ] [Flaky
Test\r\nRunner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1)
was\r\nused on any tests changed\r\n- [ ] The PR description includes
the appropriate Release Notes section,\r\nand the correct
`release_note:*` label is applied per
the\r\n[guidelines](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)\r\n\r\n###
Identify risks\r\n\r\nDoes this PR introduce any risks? For example,
consider risks like hard\r\nto test bugs, performance regression,
potential of data loss.\r\n\r\nDescribe the risk, its severity, and
mitigation for each identified\r\nrisk. Invite stakeholders and evaluate
how to proceed before merging.\r\n\r\n- [ ] [See some
risk\r\nexamples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)\r\n-
[ ] ...\r\n\r\n-->\r\n\r\nCo-authored-by: Elastic Machine
<[email protected]>","sha":"197e606bdf812438dbcfe5bb783198a0ea874b52"}},"sourceBranch":"main","suggestedTargetBranches":[],"targetPullRequestStates":[{"branch":"main","label":"v9.0.0","labelRegex":"^v9.0.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/201475","number":201475,"mergeCommit":{"message":"fix
issue with generating short url when copying share link (#201475)\n\n##
Summary\r\n\r\nExtracted from
#197484, to make it\r\nmuch easier
to backport this fix to other releases that require
this\r\nfix.\r\n\r\nThis PR fixes the issue with generating short URL
for the share link.\r\n\r\n### Checklist\r\n\r\n<!-- Check the PR
satisfies following conditions. \r\n\r\nReviewers should verify this PR
satisfies this list as well.\r\n\r\n- [ ] Any text added follows [EUI's
writing\r\nguidelines](https://elastic.github.io/eui/#/guidelines/writing),
uses\r\nsentence case text and includes
[i18n\r\nsupport](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)\r\n-
[
]\r\n[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)\r\nwas
added for features that require explanation or tutorials -->\r\n- [x]
[Unit or
functional\r\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\r\nwere
updated or added to match the most common scenarios\r\n\r\n<!--\r\n- [ ]
If a plugin configuration key changed, check if it needs to
be\r\nallowlisted in the cloud and added to the
[docker\r\nlist](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)\r\n-
[ ] This was checked for breaking HTTP API changes, and any
breaking\r\nchanges have been approved by the breaking-change committee.
The\r\n`release_note:breaking` label should be applied in these
situations.\r\n- [ ] [Flaky
Test\r\nRunner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1)
was\r\nused on any tests changed\r\n- [ ] The PR description includes
the appropriate Release Notes section,\r\nand the correct
`release_note:*` label is applied per
the\r\n[guidelines](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)\r\n\r\n###
Identify risks\r\n\r\nDoes this PR introduce any risks? For example,
consider risks like hard\r\nto test bugs, performance regression,
potential of data loss.\r\n\r\nDescribe the risk, its severity, and
mitigation for each identified\r\nrisk. Invite stakeholders and evaluate
how to proceed before merging.\r\n\r\n- [ ] [See some
risk\r\nexamples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)\r\n-
[ ] ...\r\n\r\n-->\r\n\r\nCo-authored-by: Elastic Machine
<[email protected]>","sha":"197e606bdf812438dbcfe5bb783198a0ea874b52"}},{"url":"https://github.com/elastic/kibana/pull/201593","number":201593,"branch":"8.17","state":"OPEN"},{"url":"https://github.com/elastic/kibana/pull/201594","number":201594,"branch":"8.x","state":"OPEN"}]}]
BACKPORT-->

---------

Co-authored-by: kibanamachine <[email protected]>
  • Loading branch information
eokoneyo and kibanamachine authored Nov 26, 2024
1 parent 61cba7f commit 2c9ed21
Show file tree
Hide file tree
Showing 8 changed files with 304 additions and 79 deletions.
24 changes: 24 additions & 0 deletions src/plugins/share/public/components/context/index.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* 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 { renderHook } from '@testing-library/react-hooks';
import { useShareTabsContext } from '.';

describe('share menu context', () => {
describe('useShareTabsContext', () => {
it('throws an error if used outside of ShareMenuProvider tree', () => {
const { result } = renderHook(() => useShareTabsContext());

expect(result.error?.message).toEqual(
expect.stringContaining(
'Failed to call `useShareTabsContext` because the context from ShareMenuProvider is missing.'
)
);
});
});
});
23 changes: 20 additions & 3 deletions src/plugins/share/public/components/context/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

import { ThemeServiceSetup } from '@kbn/core-theme-browser';
import { I18nStart } from '@kbn/core/public';
import { createContext, useContext } from 'react';
import React, { type PropsWithChildren, createContext, useContext } from 'react';

import { AnonymousAccessServiceContract } from '../../../common';
import type {
Expand All @@ -34,6 +34,23 @@ export interface IShareContext extends ShareContext {
anchorElement?: HTMLElement;
}

export const ShareTabsContext = createContext<IShareContext | null>(null);
const ShareTabsContext = createContext<IShareContext | null>(null);

export const useShareTabsContext = () => useContext(ShareTabsContext);
export const ShareMenuProvider = ({
shareContext,
children,
}: PropsWithChildren<{ shareContext: IShareContext }>) => {
return <ShareTabsContext.Provider value={shareContext}>{children}</ShareTabsContext.Provider>;
};

export const useShareTabsContext = () => {
const context = useContext(ShareTabsContext);

if (!context) {
throw new Error(
'Failed to call `useShareTabsContext` because the context from ShareMenuProvider is missing. Ensure the component or React root is wrapped with ShareMenuProvider'
);
}

return context;
};
10 changes: 5 additions & 5 deletions src/plugins/share/public/components/share_tabs.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

import React from 'react';
import { ShareMenuTabs } from './share_tabs';
import { ShareTabsContext } from './context';
import { ShareMenuProvider } from './context';
import { mountWithIntl } from '@kbn/test-jest-helpers';
import { KibanaLocation, LocatorGetUrlParams, UrlService } from '../../common/url_service';
import {
Expand Down Expand Up @@ -76,9 +76,9 @@ describe('Share modal tabs', () => {
},
];
const wrapper = mountWithIntl(
<ShareTabsContext.Provider value={{ ...mockShareContext, shareMenuItems: testItem }}>
<ShareMenuProvider shareContext={{ ...mockShareContext, shareMenuItems: testItem }}>
<ShareMenuTabs />
</ShareTabsContext.Provider>
</ShareMenuProvider>
);
expect(wrapper.find('[data-test-subj="export"]').exists()).toBeTruthy();
});
Expand All @@ -99,9 +99,9 @@ describe('Share modal tabs', () => {
},
];
const wrapper = mountWithIntl(
<ShareTabsContext.Provider value={{ ...mockShareContext, shareMenuItems: testItem }}>
<ShareMenuProvider shareContext={{ ...mockShareContext, shareMenuItems: testItem }}>
<ShareMenuTabs />
</ShareTabsContext.Provider>
</ShareMenuProvider>
);
expect(wrapper.find('[data-test-subj="export"]').exists()).toBeTruthy();
});
Expand Down
16 changes: 5 additions & 11 deletions src/plugins/share/public/components/share_tabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,26 @@
*/

import React, { type FC } from 'react';
import { TabbedModal } from '@kbn/shared-ux-tabbed-modal';
import { TabbedModal, type IModalTabDeclaration } from '@kbn/shared-ux-tabbed-modal';

import { ShareTabsContext, useShareTabsContext, type IShareContext } from './context';
import { ShareMenuProvider, useShareTabsContext, type IShareContext } from './context';
import { linkTab, embedTab, exportTab } from './tabs';

export const ShareMenu: FC<{ shareContext: IShareContext }> = ({ shareContext }) => {
return (
<ShareTabsContext.Provider value={shareContext}>
<ShareMenuProvider {...{ shareContext }}>
<ShareMenuTabs />
</ShareTabsContext.Provider>
</ShareMenuProvider>
);
};

// this file is intended to replace share_context_menu
export const ShareMenuTabs = () => {
const shareContext = useShareTabsContext();

if (!shareContext) {
return null;
}

const { allowEmbed, objectTypeMeta, onClose, shareMenuItems, anchorElement } = shareContext;

const tabs = [];

tabs.push(linkTab);
const tabs: Array<IModalTabDeclaration<any>> = [linkTab];

if (shareMenuItems.length > 0) {
tabs.push(exportTab);
Expand Down
189 changes: 189 additions & 0 deletions src/plugins/share/public/components/tabs/link/link_content.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
/*
* 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, { type ComponentProps } from 'react';
import { __IntlProvider as IntlProvider } from '@kbn/i18n-react';
import { render, screen, waitFor, fireEvent } from '@testing-library/react';

import { urlServiceTestSetup } from '../../../../common/url_service/__tests__/setup';
import { MockLocatorDefinition } from '../../../../common/url_service/mocks';
import { BrowserShortUrlClientFactory } from '../../../url_service/short_urls/short_url_client_factory';
import {
BrowserShortUrlClientHttp,
BrowserShortUrlClient,
} from '../../../url_service/short_urls/short_url_client';
import { BrowserUrlService } from '../../../types';
import { LinkContent } from './link_content';

const renderComponent = (props: ComponentProps<typeof LinkContent>) => {
render(
<IntlProvider locale="en">
<LinkContent {...props} />
</IntlProvider>
);
};

describe('LinkContent', () => {
const shareableUrl = 'http://localhost:5601/app/dashboards#/view/123';

const http: BrowserShortUrlClientHttp = {
basePath: {
get: () => '/xyz',
},
fetch: jest.fn(async () => {
return {} as any;
}),
};

let urlService: BrowserUrlService;

// @ts-expect-error there is a type because we override the shortUrls implementation
// eslint-disable-next-line prefer-const
({ service: urlService } = urlServiceTestSetup({
shortUrls: ({ locators }) =>
new BrowserShortUrlClientFactory({
http,
locators,
}),
}));

beforeAll(() => {
Object.defineProperty(document, 'execCommand', {
value: jest.fn(() => true),
});
});

it('uses the delegatedShareUrlHandler to generate the shareable URL when it is provided', async () => {
const objectType = 'dashboard';
const objectId = '123';
const isDirty = false;

const delegatedShareUrlHandler = jest.fn();

renderComponent({
objectType,
objectId,
isDirty,
shareableUrl,
urlService,
allowShortUrl: true,
delegatedShareUrlHandler,
});

fireEvent.click(screen.getByTestId('copyShareUrlButton'));

expect(delegatedShareUrlHandler).toHaveBeenCalled();
});

it('returns the shareable URL when the delegatedShareUrlHandler is not provided and shortURLs are not allowed', async () => {
const objectType = 'dashboard';
const objectId = '123';
const isDirty = false;

renderComponent({
objectType,
objectId,
isDirty,
shareableUrl,
urlService,
allowShortUrl: false,
});

const copyButton = screen.getByTestId('copyShareUrlButton');

fireEvent.click(copyButton);

await waitFor(() => {
expect(copyButton.getAttribute('data-share-url')).toBe(shareableUrl);
});
});

it('invokes the createWithLocator method on the shortURL service if a locator is present when the copy button is clicked', async () => {
const objectType = 'dashboard';
const objectId = '123';
const isDirty = false;
const shareableUrlLocatorParams = {
locator: new MockLocatorDefinition('TEST_LOCATOR'),
params: {},
};

const shortURL = 'http://localhost:5601/xyz/r/s/yellow-orange-tomato';

const createWithLocatorSpy = jest.spyOn(BrowserShortUrlClient.prototype, 'createWithLocator');

createWithLocatorSpy.mockResolvedValue({
// @ts-expect-error we only return locator property, as that's all we need for this test
locator: {
getUrl: jest.fn(() => Promise.resolve(shortURL)),
},
});

renderComponent({
objectType,
objectId,
isDirty,
shareableUrl,
urlService,
allowShortUrl: true,
// @ts-ignore this locator is passed mainly to test the code path that invokes createWithLocator
shareableUrlLocatorParams,
});

const copyButton = screen.getByTestId('copyShareUrlButton');

const numberOfClicks = 4;

for (const _click of Array.from({ length: numberOfClicks })) {
fireEvent.click(copyButton);
}

await waitFor(() => {
// should only invoke once no matter how many times the button is clicked
expect(createWithLocatorSpy).toHaveBeenCalledTimes(1);
expect(copyButton.getAttribute('data-share-url')).toBe(shortURL);
});
});

it('invokes the createFromLongUrl method on the shortURL service if a locator is not present when the copy button is clicked', async () => {
const objectType = 'dashboard';
const objectId = '123';
const isDirty = false;

const shortURL = 'http://localhost:5601/xyz/r/s/yellow-orange-tomato';

const createFromLongUrlSpy = jest.spyOn(BrowserShortUrlClient.prototype, 'createFromLongUrl');

// @ts-expect-error we only return url property, as that's all we need for this test
createFromLongUrlSpy.mockResolvedValue({
url: shortURL,
});

renderComponent({
objectType,
objectId,
isDirty,
shareableUrl,
urlService,
allowShortUrl: true,
});

const copyButton = screen.getByTestId('copyShareUrlButton');

const numberOfClicks = 4;

for (const _click of Array.from({ length: numberOfClicks })) {
fireEvent.click(copyButton);
}

await waitFor(() => {
// should only invoke once no matter how many times the button is clicked
expect(createFromLongUrlSpy).toHaveBeenCalledTimes(1);
expect(copyButton.getAttribute('data-share-url')).toBe(shortURL);
});
});
});
Loading

0 comments on commit 2c9ed21

Please sign in to comment.