Skip to content

Allow permalinks in demo #163

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 21 additions & 15 deletions demo/App.svelte
Original file line number Diff line number Diff line change
@@ -1,24 +1,30 @@
<script>
const defaultUrl = 'https://github.com/refined-github/github-url-detection';
export let url = '';

import parseUrl from './parse-url.js';
import * as urlDetection from '../index';
import { getAllUrls } from '../collector';

const defaultUrl = 'https://github.com/refined-github/github-url-detection';
const urlParameter = new URLSearchParams(location.search);
const parsedUrlParameter = parseUrl(urlParameter.get('url'), 'https://github.com').href;
// Parse partial URL in the parameter so that it's shown as full URL in the field
let urlField = parsedUrlParameter || '';

const allUrls = [...getAllUrls()].sort();

let isUrlValid;
$: {
try {
new URL(url || defaultUrl);
isUrlValid = true;
} catch {
isUrlValid = false;
}
}
let parsedUrl;
// Do not use ?? because it should work on empty strings
$: parsedUrl = parseUrl(urlField || defaultUrl);

let detections = [];
$: {
if (isUrlValid) {
if (parsedUrl) {
if (urlField) {
urlParameter.set('url', urlField.replace('https://github.com', ''));
history.replaceState(null, '', `?${urlParameter}`);
} else {
history.replaceState(null, '', location.pathname);
}
detections = Object.entries(urlDetection)
.map(([name, detect]) => {
if (typeof detect !== 'function') {
Expand All @@ -29,7 +35,7 @@
return {
name,
detect,
result: detect(new URL(url || defaultUrl))
result: detect(parsedUrl)
};
} else {
return {name};
Expand Down Expand Up @@ -75,7 +81,7 @@
<span>URL:</span>
<input
type="search"
bind:value={url}
bind:value={urlField}
placeholder={defaultUrl}
autocomplete="off"
autocorrect="off"
Expand All @@ -88,7 +94,7 @@
{/each}
</datalist>

{#if isUrlValid}
{#if parsedUrl}
<pre><code>
{#each detections as {name, detect, result} (name)}
{#if detect}
Expand Down
11 changes: 11 additions & 0 deletions demo/parse-url.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export default function parseUrl(url, origin) {
if (!url) {
return false;
}

try {
return new URL(url, origin);
} catch {
return false;
}
}