| 1 |
import $ from 'jquery'; |
| 2 |
|
| 3 |
import { DropdownMenu, SelectControl } from '@wordpress/components'; |
| 4 |
import { useEffect, useState } from '@wordpress/element'; |
| 5 |
import { __ } from '@wordpress/i18n'; |
| 6 |
|
| 7 |
const cache = {}; |
| 8 |
|
| 9 |
/** |
| 10 |
* Component Class. |
| 11 |
* |
| 12 |
* @param props |
| 13 |
*/ |
| 14 |
export default function GistFilesSelect(props) { |
| 15 |
const { url, label, value, onChange, isToolbar, className } = props; |
| 16 |
|
| 17 |
const [items, setItems] = useState(['']); |
| 18 |
|
| 19 |
function updateStateItems(newItems) { |
| 20 |
if (items.toString() !== newItems.toString()) { |
| 21 |
setItems(newItems); |
| 22 |
} |
| 23 |
} |
| 24 |
|
| 25 |
// Mounted and updated |
| 26 |
useEffect(() => { |
| 27 |
let checkUrl = url; |
| 28 |
|
| 29 |
const match = /^https:\/\/gist.github.com?.+\/(.+)/g.exec(checkUrl); |
| 30 |
|
| 31 |
if (match && typeof match[1] !== 'undefined') { |
| 32 |
checkUrl = `https://gist.github.com/${match[1].split('#')[0]}.json`; |
| 33 |
} else { |
| 34 |
return; |
| 35 |
} |
| 36 |
|
| 37 |
// request the json version of this gist |
| 38 |
$.ajax({ |
| 39 |
url: checkUrl, |
| 40 |
// data: data, |
| 41 |
dataType: 'jsonp', |
| 42 |
timeout: 20000, |
| 43 |
beforeSend() { |
| 44 |
if (cache[checkUrl]) { |
| 45 |
// loading the response from cache and preventing the ajax call |
| 46 |
cache[checkUrl].then( |
| 47 |
(response) => { |
| 48 |
updateStateItems([''].concat(response.files)); |
| 49 |
}, |
| 50 |
() => { |
| 51 |
updateStateItems(['']); |
| 52 |
} |
| 53 |
); |
| 54 |
return false; |
| 55 |
} |
| 56 |
|
| 57 |
// saving the promise for the requested json as a proxy for the actual response |
| 58 |
cache[checkUrl] = $.Deferred(); |
| 59 |
}, |
| 60 |
success(response) { |
| 61 |
if (cache[checkUrl]) { |
| 62 |
cache[checkUrl].resolve(response); |
| 63 |
} |
| 64 |
updateStateItems([''].concat(response.files)); |
| 65 |
}, |
| 66 |
error() { |
| 67 |
updateStateItems(['']); |
| 68 |
}, |
| 69 |
}); |
| 70 |
}); |
| 71 |
|
| 72 |
return isToolbar ? ( |
| 73 |
<DropdownMenu |
| 74 |
icon="media-default" |
| 75 |
label={label} |
| 76 |
controls={items.map((item) => ({ |
| 77 |
title: item || __('Show all files', 'ghostkit'), |
| 78 |
isActive: item === value, |
| 79 |
onClick: () => onChange(item), |
| 80 |
}))} |
| 81 |
className={className} |
| 82 |
/> |
| 83 |
) : ( |
| 84 |
<SelectControl |
| 85 |
label={label} |
| 86 |
value={value} |
| 87 |
options={items.map((item) => ({ |
| 88 |
value: item, |
| 89 |
label: item || __('Show all files', 'ghostkit'), |
| 90 |
}))} |
| 91 |
onChange={onChange} |
| 92 |
className={className} |
| 93 |
__next40pxDefaultSize |
| 94 |
__nextHasNoMarginBottom |
| 95 |
/> |
| 96 |
); |
| 97 |
} |
| 98 |
|