Skip to content

Commit ea0e865

Browse files
authored
Add permalinks to demo (#163)
1 parent b559e98 commit ea0e865

File tree

2 files changed

+32
-15
lines changed

2 files changed

+32
-15
lines changed

demo/App.svelte

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,30 @@
11
<script>
2-
const defaultUrl = 'https://github.com/refined-github/github-url-detection';
3-
export let url = '';
2+
3+
import parseUrl from './parse-url.js';
44
import * as urlDetection from '../index';
55
import { getAllUrls } from '../collector';
66
7+
const defaultUrl = 'https://github.com/refined-github/github-url-detection';
8+
const urlParameter = new URLSearchParams(location.search);
9+
const parsedUrlParameter = parseUrl(urlParameter.get('url'), 'https://github.com').href;
10+
// Parse partial URL in the parameter so that it's shown as full URL in the field
11+
let urlField = parsedUrlParameter || '';
12+
713
const allUrls = [...getAllUrls()].sort();
814
9-
let isUrlValid;
10-
$: {
11-
try {
12-
new URL(url || defaultUrl);
13-
isUrlValid = true;
14-
} catch {
15-
isUrlValid = false;
16-
}
17-
}
15+
let parsedUrl;
16+
// Do not use ?? because it should work on empty strings
17+
$: parsedUrl = parseUrl(urlField || defaultUrl);
1818
1919
let detections = [];
2020
$: {
21-
if (isUrlValid) {
21+
if (parsedUrl) {
22+
if (urlField) {
23+
urlParameter.set('url', urlField.replace('https://github.com', ''));
24+
history.replaceState(null, '', `?${urlParameter}`);
25+
} else {
26+
history.replaceState(null, '', location.pathname);
27+
}
2228
detections = Object.entries(urlDetection)
2329
.map(([name, detect]) => {
2430
if (typeof detect !== 'function') {
@@ -29,7 +35,7 @@
2935
return {
3036
name,
3137
detect,
32-
result: detect(new URL(url || defaultUrl))
38+
result: detect(parsedUrl)
3339
};
3440
} else {
3541
return {name};
@@ -75,7 +81,7 @@
7581
<span>URL:</span>
7682
<input
7783
type="search"
78-
bind:value={url}
84+
bind:value={urlField}
7985
placeholder={defaultUrl}
8086
autocomplete="off"
8187
autocorrect="off"
@@ -88,7 +94,7 @@
8894
{/each}
8995
</datalist>
9096

91-
{#if isUrlValid}
97+
{#if parsedUrl}
9298
<pre><code>
9399
{#each detections as {name, detect, result} (name)}
94100
{#if detect}

demo/parse-url.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
export default function parseUrl(url, origin) {
2+
if (!url) {
3+
return false;
4+
}
5+
6+
try {
7+
return new URL(url, origin);
8+
} catch {
9+
return false;
10+
}
11+
}

0 commit comments

Comments
 (0)