summaryrefslogtreecommitdiffstats
path: root/templates/repo/clone_script.tmpl
blob: 40dae76dc7164197c0c0a8d6bc97fa58f9f14726 (plain)
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
<script>
	// synchronously set clone button states and urls here to avoid flickering
	// on page load. initRepoCloneLink calls this when proto changes.
	// this applies the protocol-dependant clone url to all elements with the
	// `js-clone-url` and `js-clone-url-vsc` classes.
	// TODO: This localStorage setting should be moved to backend user config
	// so it's available during rendering, then this inline script can be removed.
	(window.updateCloneStates = function() {
		const httpsBtn = document.getElementById('repo-clone-https');
		const sshBtn = document.getElementById('repo-clone-ssh');
		const value = localStorage.getItem('repo-clone-protocol') || 'https';
		const isSSH = value === 'ssh' && sshBtn || value !== 'ssh' && !httpsBtn;

		if (httpsBtn) {
			httpsBtn.textContent = window.origin.split(':')[0].toUpperCase();
			httpsBtn.classList.toggle('primary', !isSSH);
			httpsBtn.classList.toggle('basic', isSSH);
		}
		if (sshBtn) {
			sshBtn.classList.toggle('primary', isSSH);
			sshBtn.classList.toggle('basic', !isSSH);
		}

		const btn = isSSH ? sshBtn : httpsBtn;
		if (!btn) return;

		// NOTE: Keep this function in sync with the one in the js folder
		function toOriginUrl(urlStr) {
			try {
				if (urlStr.startsWith('http://') || urlStr.startsWith('https://') || urlStr.startsWith('/')) {
					const {origin, protocol, hostname, port} = window.location;
					const url = new URL(urlStr, origin);
					url.protocol = protocol;
					url.hostname = hostname;
					url.port = port || (protocol === 'https:' ? '443' : '80');
					return url.toString();
				}
			} catch {}
			return urlStr;
		}
		const link = toOriginUrl(btn.getAttribute('data-link'));

		for (const el of document.getElementsByClassName('js-clone-url')) {
			el[el.nodeName === 'INPUT' ? 'value' : 'textContent'] = link;
		}
		for (const el of document.getElementsByClassName('js-clone-url-editor')) {
			el.href = el.getAttribute('data-href-template').replace('{url}', encodeURIComponent(link));
		}
	})();
</script>