forked from firefox-devtools/profiler
/
Permalink.js
92 lines (81 loc) 路 2.94 KB
/
Permalink.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// @flow
import * as React from 'react';
import { ButtonWithPanel } from 'firefox-profiler/components/shared/ButtonWithPanel';
import * as UrlUtils from 'firefox-profiler/utils/shorten-url';
import './Permalink.css';
import { Localized } from '@fluent/react';
type Props = {|
+isNewlyPublished: boolean,
// This is for injecting a URL shortener for tests. Normally we would use a Jest mock
// that would mock out a local module, but I was having trouble getting it working
// correctly (perhaps due to ES6 modules), so I just went with dependency injection
// instead.
+injectedUrlShortener?: typeof UrlUtils.shortenUrl | void,
|};
type State = {|
fullUrl: string,
shortUrl: string,
|};
export class MenuButtonsPermalink extends React.PureComponent<Props, State> {
_permalinkTextField: HTMLInputElement | null;
_takePermalinkTextFieldRef = (elem: HTMLInputElement | null) => {
this._permalinkTextField = elem;
};
state = {
fullUrl: '',
shortUrl: '',
};
_shortenUrlAndFocusTextFieldOnCompletion = async (): Promise<void> => {
const { fullUrl } = this.state;
const currentFullUrl = window.location.href;
if (fullUrl !== currentFullUrl) {
const shortenUrl = this.props.injectedUrlShortener || UrlUtils.shortenUrl;
try {
const shortUrl = await shortenUrl(currentFullUrl);
this.setState({ shortUrl, fullUrl: currentFullUrl });
} catch (error) {
console.warn('Unable to shorten the URL.', error);
// Don't remember the fullUrl so that we will attempt to shorten the
// URL again.
this.setState({ shortUrl: currentFullUrl, fullUrl: '' });
}
}
const textField = this._permalinkTextField;
if (textField) {
textField.focus();
textField.select();
}
};
_onPermalinkPanelClose = () => {
if (this._permalinkTextField) {
this._permalinkTextField.blur();
}
};
render() {
return (
<Localized id="MenuButtons--permalink--button" attrs={{ label: true }}>
<ButtonWithPanel
buttonClassName="menuButtonsButton menuButtonsButton-hasIcon menuButtonsPermalinkButtonButton"
label="Permalink"
initialOpen={this.props.isNewlyPublished}
onPanelOpen={this._shortenUrlAndFocusTextFieldOnCompletion}
onPanelClose={this._onPermalinkPanelClose}
panelClassName="menuButtonsPermalinkPanel"
panelContent={
<input
data-testid="MenuButtonsPermalink-input"
type="text"
className="menuButtonsPermalinkTextField photon-input"
value={this.state.shortUrl}
readOnly="readOnly"
ref={this._takePermalinkTextFieldRef}
/>
}
/>
</Localized>
);
}
}