wildflock/public/index.js

109 lines
3.5 KiB
JavaScript

function renderAliases(data) {
const dataContainer = document.getElementById('container');
const template = window.innerWidth > 768 ? Handlebars.compile(defaultTemplate) : Handlebars.compile(responsiveCardTemplate);
const html = template({
data: data
.sort((a, b) => new Date(a.created) - new Date(b.created))
.map(alias => ({ ...alias, created: new Date(alias.created).toLocaleString() }))
});
dataContainer.innerHTML = html;
}
function createAlias() {
const tags = document.getElementById('tags').value?.split(',') || [];
fetch('/aliases', {
method: 'POST',
body: JSON.stringify({ tags }),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(data => {
renderAliases(data)
})
}
function deleteAlias(id) {
fetch(`/aliases/${id}`, {
method: 'DELETE'
})
.then(res => res.json())
.then(data => {
renderAliases(data)
})
}
function copyToClipboard(text) {
navigator.clipboard.writeText(text)
}
const defaultTemplate = `
<table class="table">
<thead>
<tr>
<th scope="col">Address</th>
<th scope="col">Tags</th>
<th scope="col">Created</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
{{#each data}}
<tr>
<td onclick="copyToClipboard('{{address}}')" style="cursor: pointer;">{{address}}</td>
<td> {{#each tags}}{{this}} {{/each}}</td>
<td>{{created}}</td>
<td>
<div onclick="deleteAlias('{{id}}')" class="btn btn-danger {{#unless id}}disabled{{/unless}}">Delete</div>
</td>
</tr>
{{/each}}
</tbody>
</table>
<input type="text" id="tags" placeholder="Add tags (optional)">
<div class="btn btn-primary" onclick="createAlias()">Create alias</div class="btn btn-primary">
`
// Responsive card template for mobile
const responsiveCardTemplate = `
{{#each data}}
<div class="card">
<div class="card-body">
<h5 class="card-title
{{#if tags.length}}
text-primary
{{/if}}
">
{{#each tags}}
<span class="badge bg-secondary">{{this}}</span>
{{/each}}
</h5>
<h5 class="card-title" onclick="copyToClipboard('{{address}}')" style="cursor: pointer;">{{address}}</h5>
<p class="card-text">{{created}}</p>
<div onclick="deleteAlias('{{id}}')" class="btn btn-sm btn-danger {{#unless id}}disabled{{/unless}}">Delete</div>
</div>
</div>
{{/each}}
<input type="text" id="tags" placeholder="Add tags (optional)">
<button class="btn btn-primary btn-sm" onclick="createAlias()">Create alias</button">
`
fetch('/aliases').then(async res => {
const dataContainer = document.getElementById('container');
const data = await res.json();
if (!res.ok) {
dataContainer.innerHTML = `
<div class="alert alert-warning" role="alert">
Login to see your aliases
</div>
<a href="/auth-oidc" class="btn btn-primary">Login</a>
`
return
}
renderAliases(data);
})