Files
notifications-admin/app/assets/javascripts/apiKey.js
Chris Hill-Scott c4544eb833 Add API key component
This commit adds a component for showing an API key. Usage:

```jinja
{{ from 'components/api-key.html' import api_key }}
{{ api_key('e1b0751388f3cd0fc9982c701acdb3c2') }}
```

Depending on the user’s browser, it works in three different ways.

No Javascript
---
The API key is shown on the page.

Older browsers with Javascript
---
The API key is hidden, and users can click a button to reveal it.

Newer browsers that support copying to clipboard without Flash
---
As above, but when the key is shown there is a button which copies it to the
clipboard. This is acheived by using
[this polyfill](https://www.npmjs.com/package/query-command-supported)
to reliably detect browser support for the ‘copy’ command.

The styling of the component is a bit different to the initial sketch. I think
a grey button works better than green. Green feels like it’s going to take you
somewhere else.
2016-01-17 09:39:09 +00:00

59 lines
1.7 KiB
JavaScript

(function(Modules) {
"use strict";
Modules.ApiKey = function() {
const states = {
'initial': `
<input type='button' class='api-key-button-show' value='Show API key' />
`,
'keyVisibleBasic': key => `
<span class="api-key-key">${key}</span>
`,
'keyVisible': key => `
<span class="api-key-key">${key}</span>
<input type='button' class='api-key-button-copy' value='Copy API key to clipboard' />
`,
'keyCopied': `
<span class="api-key-key">Copied to clipboard</span>
<input type='button' class='api-key-button-show' value='Show API key' />
`
};
this.copyKey = function(keyElement, callback) {
var selection = window.getSelection ? window.getSelection() : document.selection,
range = document.createRange();
selection.removeAllRanges();
range.selectNodeContents(keyElement);
selection.addRange(range);
document.execCommand('copy');
selection.removeAllRanges();
callback();
};
this.start = function(component) {
const $component = $(component).html(states.initial).attr('aria-live', 'polite'),
key = $component.data('key');
$component
.on(
'click', '.api-key-button-show', () =>
$component.html(
document.queryCommandSupported('copy') ?
states.keyVisible(key) : states.keyVisibleBasic(key)
)
)
.on(
'click', '.api-key-button-copy', () =>
this.copyKey(
$('.api-key-key', component)[0], () =>
$component.html(states.keyCopied)
)
);
};
};
})(window.GOVUK.Modules);