Make it public!

This commit is contained in:
Bruno Bernardino
2024-03-16 08:40:24 +00:00
commit a5cafdddca
114 changed files with 9569 additions and 0 deletions

175
islands/Settings.tsx Normal file
View File

@@ -0,0 +1,175 @@
import { convertObjectToFormData, helpEmail } from '/lib/utils.ts';
import { FormField, generateFieldHtml, getFormDataField } from '/lib/form-utils.tsx';
interface SettingsProps {
formData: Record<string, any>;
error?: {
title: string;
message: string;
};
notice?: {
title: string;
message: string;
};
}
export type Action =
| 'change-email'
| 'verify-change-email'
| 'change-password'
| 'change-dav-password'
| 'delete-account';
export const actionWords = new Map<Action, string>([
['change-email', 'change email'],
['verify-change-email', 'change email'],
['change-password', 'change password'],
['change-dav-password', 'change DAV password'],
['delete-account', 'delete account'],
]);
function formFields(action: Action, formData: FormData) {
const fields: FormField[] = [
{
name: 'action',
label: '',
type: 'hidden',
value: action,
overrideValue: action,
required: true,
readOnly: true,
},
];
if (action === 'change-email') {
fields.push({
name: 'email',
label: 'Email',
type: 'email',
placeholder: 'jane.doe@example.com',
value: getFormDataField(formData, 'email'),
required: true,
});
} else if (action === 'verify-change-email') {
fields.push({
name: 'email',
label: 'Email',
type: 'email',
placeholder: 'jane.doe@example.com',
value: getFormDataField(formData, 'email'),
required: true,
}, {
name: 'verification-code',
label: 'Verification Code',
description: `The verification code to validate your new email.`,
type: 'text',
placeholder: '000000',
required: true,
});
} else if (action === 'change-password') {
fields.push({
name: 'current-password',
label: 'Current Password',
type: 'password',
placeholder: 'super-SECRET-passphrase',
required: true,
}, {
name: 'new-password',
label: 'New Password',
type: 'password',
placeholder: 'super-SECRET-passphrase',
required: true,
});
} else if (action === 'change-dav-password') {
fields.push({
name: 'new-dav-password',
label: 'New DAV Password',
type: 'password',
placeholder: 'super-SECRET-passphrase',
required: true,
description: 'Alternative password used for DAV access and/or HTTP Basic Auth.',
});
} else if (action === 'delete-account') {
fields.push({
name: 'current-password',
label: 'Password',
type: 'password',
placeholder: 'super-SECRET-passphrase',
description: 'You need to input your password in order to delete your account.',
required: true,
});
}
return fields;
}
export default function Settings({ formData: formDataObject, error, notice }: SettingsProps) {
const formData = convertObjectToFormData(formDataObject);
const action = getFormDataField(formData, 'action') as Action;
return (
<>
<section class='mx-auto max-w-7xl my-8'>
{error
? (
<section class='notification-error'>
<h3>{error.title}</h3>
<p>{error.message}</p>
</section>
)
: null}
{notice
? (
<section class='notification-success'>
<h3>{notice.title}</h3>
<p>{notice.message}</p>
</section>
)
: null}
<h2 class='text-2xl mb-4 text-left px-4 max-w-screen-md mx-auto lg:min-w-96'>Change your email</h2>
<form method='POST' class='mb-12'>
{formFields(
action === 'change-email' && notice?.message.includes('verify') ? 'verify-change-email' : 'change-email',
formData,
).map((field) => generateFieldHtml(field, formData))}
<section class='flex justify-end mt-8 mb-4'>
<button class='button-secondary' type='submit'>Change email</button>
</section>
</form>
<h2 class='text-2xl mb-4 text-left px-4 max-w-screen-md mx-auto lg:min-w-96'>Change your password</h2>
<form method='POST' class='mb-12'>
{formFields('change-password', formData).map((field) => generateFieldHtml(field, formData))}
<section class='flex justify-end mt-8 mb-4'>
<button class='button-secondary' type='submit'>Change password</button>
</section>
</form>
<h2 class='text-2xl mb-4 text-left px-4 max-w-screen-md mx-auto lg:min-w-96'>Change your DAV password</h2>
<form method='POST' class='mb-12'>
{formFields('change-dav-password', formData).map((field) => generateFieldHtml(field, formData))}
<section class='flex justify-end mt-8 mb-4'>
<button class='button-secondary' type='submit'>Change DAV password</button>
</section>
</form>
<h2 class='text-2xl mb-4 text-left px-4 max-w-screen-md mx-auto lg:min-w-96'>Delete your account</h2>
<p class='text-left mt-2 mb-6 px-4 max-w-screen-md mx-auto lg:min-w-96'>
Deleting your account is instant and deletes all your data. If you need help, please{' '}
<a href={`mailto:${helpEmail}`}>reach out</a>.
</p>
<form method='POST' class='mb-12'>
{formFields('delete-account', formData).map((field) => generateFieldHtml(field, formData))}
<section class='flex justify-end mt-8 mb-4'>
<button class='button-danger' type='submit'>Delete account</button>
</section>
</form>
</section>
</>
);
}

View File

@@ -0,0 +1,407 @@
import { useSignal } from '@preact/signals';
import { Contact } from '/lib/types.ts';
import { baseUrl, CONTACTS_PER_PAGE_COUNT, formatContactToVCard, parseVCardFromTextContents } from '/lib/utils.ts';
import { RequestBody as GetRequestBody, ResponseBody as GetResponseBody } from '/routes/api/contacts/get.tsx';
import { RequestBody as AddRequestBody, ResponseBody as AddResponseBody } from '/routes/api/contacts/add.tsx';
import { RequestBody as DeleteRequestBody, ResponseBody as DeleteResponseBody } from '/routes/api/contacts/delete.tsx';
import { RequestBody as ImportRequestBody, ResponseBody as ImportResponseBody } from '/routes/api/contacts/import.tsx';
interface ContactsProps {
initialContacts: Pick<Contact, 'id' | 'first_name' | 'last_name'>[];
page: number;
contactsCount: number;
search?: string;
}
export default function Contacts({ initialContacts, page, contactsCount, search }: ContactsProps) {
const isAdding = useSignal<boolean>(false);
const isDeleting = useSignal<boolean>(false);
const isExporting = useSignal<boolean>(false);
const isImporting = useSignal<boolean>(false);
const contacts = useSignal<Pick<Contact, 'id' | 'first_name' | 'last_name'>[]>(initialContacts);
const isOptionsDropdownOpen = useSignal<boolean>(false);
async function onClickAddContact() {
if (isAdding.value) {
return;
}
const firstName = (prompt(`What's the **first name** for the new contact?`) || '').trim();
if (!firstName) {
alert('A first name is required for a new contact!');
return;
}
const lastName = (prompt(`What's the **last name** for the new contact?`) || '').trim();
isAdding.value = true;
try {
const requestBody: AddRequestBody = { firstName, lastName, page };
const response = await fetch(`/api/contacts/add`, {
method: 'POST',
body: JSON.stringify(requestBody),
});
const result = await response.json() as AddResponseBody;
if (!result.success) {
throw new Error('Failed to add contact!');
}
contacts.value = [...result.contacts];
} catch (error) {
console.error(error);
}
isAdding.value = false;
}
function toggleOptionsDropdown() {
isOptionsDropdownOpen.value = !isOptionsDropdownOpen.value;
}
async function onClickDeleteContact(contactId: string) {
if (confirm('Are you sure you want to delete this contact?')) {
if (isDeleting.value) {
return;
}
isDeleting.value = true;
try {
const requestBody: DeleteRequestBody = { contactId, page };
const response = await fetch(`/api/contacts/delete`, {
method: 'POST',
body: JSON.stringify(requestBody),
});
const result = await response.json() as DeleteResponseBody;
if (!result.success) {
throw new Error('Failed to delete contact!');
}
contacts.value = [...result.contacts];
} catch (error) {
console.error(error);
}
isDeleting.value = false;
}
}
function onClickImportVCard() {
isOptionsDropdownOpen.value = false;
if (isImporting.value) {
return;
}
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.click();
fileInput.onchange = (event) => {
const files = (event.target as HTMLInputElement)?.files!;
const file = files[0];
if (!file) {
return;
}
const reader = new FileReader();
reader.onload = async (fileRead) => {
const importFileContents = fileRead.target?.result;
if (!importFileContents || isImporting.value) {
return;
}
isImporting.value = true;
try {
const partialContacts = parseVCardFromTextContents(importFileContents!.toString());
const requestBody: ImportRequestBody = { partialContacts, page };
const response = await fetch(`/api/contacts/import`, {
method: 'POST',
body: JSON.stringify(requestBody),
});
const result = await response.json() as ImportResponseBody;
if (!result.success) {
throw new Error('Failed to import contact!');
}
contacts.value = [...result.contacts];
} catch (error) {
console.error(error);
}
isImporting.value = false;
};
reader.readAsText(file, 'UTF-8');
};
}
async function onClickExportVCard() {
isOptionsDropdownOpen.value = false;
if (isExporting.value) {
return;
}
isExporting.value = true;
const fileName = ['contacts-', new Date().toISOString().substring(0, 19).replace(/:/g, '-'), '.vcf']
.join('');
try {
const requestBody: GetRequestBody = {};
const response = await fetch(`/api/contacts/get`, {
method: 'POST',
body: JSON.stringify(requestBody),
});
const result = await response.json() as GetResponseBody;
if (!result.success) {
throw new Error('Failed to get contact!');
}
const exportContents = formatContactToVCard([...result.contacts]);
// Add content-type
const vCardContent = ['data:text/vcard; charset=utf-8,', encodeURIComponent(exportContents)].join('');
// Download the file
const data = vCardContent;
const link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', fileName);
link.click();
link.remove();
} catch (error) {
console.error(error);
}
isExporting.value = false;
}
const pagesCount = Math.ceil(contactsCount / CONTACTS_PER_PAGE_COUNT);
const pages = Array.from({ length: pagesCount }).map((_value, index) => index + 1);
return (
<>
<section class='flex flex-row items-center justify-between mb-4'>
<section class='relative inline-block text-left mr-2'>
<form method='GET' action='/contacts' class='m-0 p-0'>
<input
class='input-field w-60'
type='search'
name='search'
value={search}
placeholder='Search contacts...'
/>
</form>
</section>
<section class='flex items-center'>
<section class='relative inline-block text-left ml-2'>
<div>
<button
type='button'
class='inline-flex w-full justify-center gap-x-1.5 rounded-md bg-slate-700 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-slate-600'
id='filter-button'
aria-expanded='true'
aria-haspopup='true'
onClick={() => toggleOptionsDropdown()}
>
VCF
<svg class='-mr-1 h-5 w-5 text-slate-400' viewBox='0 0 20 20' fill='currentColor' aria-hidden='true'>
<path
fill-rule='evenodd'
d='M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z'
clip-rule='evenodd'
/>
</svg>
</button>
</div>
<div
class={`absolute right-0 z-10 mt-2 w-44 origin-top-right rounded-md bg-slate-700 shadow-lg ring-1 ring-black ring-opacity-15 focus:outline-none ${
!isOptionsDropdownOpen.value ? 'hidden' : ''
}`}
role='menu'
aria-orientation='vertical'
aria-labelledby='filter-button'
tabindex={-1}
>
<div class='py-1'>
<button
class={`text-white block px-4 py-2 text-sm w-full text-left hover:bg-slate-600`}
onClick={() => onClickImportVCard()}
>
Import vCard
</button>
<button
class={`text-white block px-4 py-2 text-sm w-full text-left hover:bg-slate-600`}
onClick={() => onClickExportVCard()}
>
Export vCard
</button>
</div>
</div>
</section>
<button
class='inline-block justify-center gap-x-1.5 rounded-md bg-[#51A4FB] px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-sky-400 ml-2'
type='button'
title='Add new contact'
onClick={() => onClickAddContact()}
>
<img
src='/images/add.svg'
alt='Add new contact'
class={`white ${isAdding.value ? 'animate-spin' : ''}`}
width={20}
height={20}
/>
</button>
</section>
</section>
<section class='mx-auto max-w-7xl my-8'>
<table class='w-full border-collapse bg-slate-700 text-left text-sm text-slate-500 shadow-sm'>
<thead class='bg-gray-900'>
<tr>
<th scope='col' class='px-6 py-4 font-medium text-white'>First Name</th>
<th scope='col' class='px-6 py-4 font-medium text-white'>Last Name</th>
<th scope='col' class='px-6 py-4 font-medium text-white w-20'></th>
</tr>
</thead>
<tbody class='divide-y divide-slate-600 border-t border-slate-600'>
{contacts.value.map((contact) => (
<tr class='hover:bg-slate-600 group'>
<td class='flex gap-3 px-6 py-4 font-normal text-white'>
<a href={`/contacts/${contact.id}`}>{contact.first_name}</a>
</td>
<td class='px-6 py-4 text-slate-200'>
{contact.last_name}
</td>
<td class='px-6 py-4'>
<span
class='invisible cursor-pointer group-hover:visible opacity-50 hover:opacity-100'
onClick={() => onClickDeleteContact(contact.id)}
>
<img
src='/images/delete.svg'
class='red drop-shadow-md'
width={24}
height={24}
alt='Delete contact'
title='Delete contact'
/>
</span>
</td>
</tr>
))}
{contacts.value.length === 0
? (
<tr>
<td class='flex gap-3 px-6 py-4 font-normal' colspan={3}>
<div class='text-md'>
<div class='font-medium text-slate-400'>No contacts to show</div>
</div>
</td>
</tr>
)
: null}
</tbody>
</table>
<span
class={`flex justify-end items-center text-sm mt-1 mx-2 text-slate-100`}
>
{isDeleting.value
? (
<>
<img src='/images/loading.svg' class='white mr-2' width={18} height={18} />Deleting...
</>
)
: null}
{isExporting.value
? (
<>
<img src='/images/loading.svg' class='white mr-2' width={18} height={18} />Exporting...
</>
)
: null}
{isImporting.value
? (
<>
<img src='/images/loading.svg' class='white mr-2' width={18} height={18} />Importing...
</>
)
: null}
{!isDeleting.value && !isExporting.value && !isImporting.value ? <>&nbsp;</> : null}
</span>
</section>
{pagesCount > 0
? (
<section class='flex justify-end'>
<nav class='isolate inline-flex -space-x-px rounded-md shadow-sm' aria-label='Pagination'>
<a
href={page > 1 ? `/contacts?search=${search}&page=${page - 1}` : 'javascript:void(0)'}
class='relative inline-flex items-center rounded-l-md px-2 py-2 text-white hover:bg-slate-600 bg-slate-700'
title='Previous'
>
<svg class='h-5 w-5' viewBox='0 0 20 20' fill='currentColor' aria-hidden='true'>
<path
fill-rule='evenodd'
d='M12.79 5.23a.75.75 0 01-.02 1.06L8.832 10l3.938 3.71a.75.75 0 11-1.04 1.08l-4.5-4.25a.75.75 0 010-1.08l4.5-4.25a.75.75 0 011.06.02z'
clip-rule='evenodd'
/>
</svg>
</a>
{pages.map((pageNumber) => {
const isCurrent = pageNumber === page;
return (
<a
href={`/contacts?search=${search}&page=${pageNumber}`}
aria-current='page'
class={`relative inline-flex items-center ${
isCurrent ? 'bg-[#51A4FB] hover:bg-sky-400' : 'bg-slate-700 hover:bg-slate-600'
} px-4 py-2 text-sm font-semibold text-white`}
>
{pageNumber}
</a>
);
})}
<a
href={page < pagesCount ? `/contacts?search=${search}&page=${page + 1}` : 'javascript:void(0)'}
class='relative inline-flex items-center rounded-r-md px-2 py-2 text-white hover:bg-slate-600 bg-slate-700'
title='Next'
>
<svg class='h-5 w-5' viewBox='0 0 20 20' fill='currentColor' aria-hidden='true'>
<path
fill-rule='evenodd'
d='M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z'
clip-rule='evenodd'
/>
</svg>
</a>
</nav>
</section>
)
: null}
<section class='flex flex-row items-center justify-start my-12'>
<span class='font-semibold'>CardDAV URLs:</span>{' '}
<code class='bg-slate-600 mx-2 px-2 py-1 rounded-md'>{baseUrl}/dav/principals/</code>{' '}
<code class='bg-slate-600 mx-2 px-2 py-1 rounded-md'>{baseUrl}/dav/addressbooks/</code>
</section>
</>
);
}

View File

@@ -0,0 +1,471 @@
import { useSignal } from '@preact/signals';
import { Contact } from '/lib/types.ts';
import { convertObjectToFormData } from '/lib/utils.ts';
import { FormField, generateFieldHtml } from '/lib/form-utils.tsx';
import { RequestBody as DeleteRequestBody, ResponseBody as DeleteResponseBody } from '/routes/api/contacts/delete.tsx';
interface ViewContactProps {
initialContact: Contact;
formData: Record<string, any>;
error?: string;
notice?: string;
}
export function formFields(contact: Contact) {
const fields: FormField[] = [
{
name: 'name_title',
label: 'Honorary title/prefix',
type: 'text',
placeholder: 'Dr.',
value: contact.extra.name_title,
required: false,
},
{
name: 'first_name',
label: 'First name',
type: 'text',
placeholder: 'John',
value: contact.first_name,
required: true,
},
{
name: 'middle_names',
label: 'Middle name(s)',
type: 'text',
placeholder: '',
value: contact.extra.middle_names?.map((name) => (name || '').trim()).filter(Boolean).join(' '),
required: false,
},
{
name: 'last_name',
label: 'Last name',
type: 'text',
placeholder: 'Doe',
value: contact.last_name,
required: false,
},
{
name: 'birthday',
label: 'Birthday',
type: 'text',
placeholder: 'YYYYMMDD',
value: contact.extra.birthday,
required: false,
},
{
name: 'nickname',
label: 'Nickname',
type: 'text',
placeholder: 'Johnny',
value: contact.extra.nickname,
required: false,
},
{
name: 'organization',
label: 'Company/Organization',
type: 'text',
placeholder: 'Acme Corporation',
value: contact.extra.organization,
required: false,
},
{
name: 'role',
label: 'Job/Role',
type: 'text',
placeholder: '(Super) Genius',
value: contact.extra.role,
required: false,
},
{
name: 'photo_url',
label: 'Photo URL',
type: 'url',
placeholder: 'https://example.com/image.jpg',
value: contact.extra.photo_url,
required: false,
},
];
// Phones
const phones = contact.extra.fields?.filter((field) => field.type === 'phone') || [];
for (const [index, phone] of phones.entries()) {
fields.push({
name: 'phone_numbers',
label: `Phone number #${index + 1}`,
type: 'tel',
placeholder: '+44 0000 111 2222',
value: phone.value,
required: false,
});
fields.push({
name: 'phone_labels',
label: `Phone label #${index + 1}`,
type: 'text',
placeholder: 'Home, Work, etc.',
value: phone.name,
required: false,
});
}
fields.push({
name: 'phone_numbers',
label: `Phone number #${phones.length + 1}`,
type: 'tel',
placeholder: '+44 0000 111 2222',
value: '',
required: false,
}, {
name: 'phone_labels',
label: `Phone label #${phones.length + 1}`,
type: 'text',
placeholder: 'Home, Work, etc.',
value: '',
required: false,
});
// Emails
const emails = contact.extra.fields?.filter((field) => field.type === 'email') || [];
for (const [index, email] of emails.entries()) {
fields.push({
name: 'email_addresses',
label: `Email #${index + 1}`,
type: 'email',
placeholder: 'user@example.com',
value: email.value,
required: false,
});
fields.push({
name: 'email_labels',
label: `Email label #${index + 1}`,
type: 'text',
placeholder: 'Home, Work, etc.',
value: email.name,
required: false,
});
}
fields.push({
name: 'email_addresses',
label: `Email #${emails.length + 1}`,
type: 'email',
placeholder: 'user@example.com',
value: '',
required: false,
}, {
name: 'email_labels',
label: `Email label #${emails.length + 1}`,
type: 'text',
placeholder: 'Home, Work, etc.',
value: '',
required: false,
});
// URLs
const urls = contact.extra.fields?.filter((field) => field.type === 'url') || [];
for (const [index, url] of urls.entries()) {
fields.push({
name: 'url_addresses',
label: `URL #${index + 1}`,
type: 'url',
placeholder: 'https://example.com',
value: url.value,
required: false,
});
fields.push({
name: 'url_labels',
label: `URL label #${index + 1}`,
type: 'text',
placeholder: 'Home, Work, etc.',
value: url.name,
required: false,
});
}
fields.push({
name: 'url_addresses',
label: `URL #${urls.length + 1}`,
type: 'url',
placeholder: 'https://example.com',
value: '',
required: false,
}, {
name: 'url_labels',
label: `URL label #${urls.length + 1}`,
type: 'text',
placeholder: 'Home, Work, etc.',
value: '',
required: false,
});
// Others
const others = contact.extra.fields?.filter((field) => field.type === 'other') || [];
for (const [index, other] of others.entries()) {
fields.push({
name: 'other_values',
label: `Other contact #${index + 1}`,
type: 'text',
placeholder: '@acme',
value: other.value,
required: false,
});
fields.push({
name: 'other_labels',
label: `Other label #${index + 1}`,
type: 'text',
placeholder: 'Home, Work, etc.',
value: other.name,
required: false,
});
}
fields.push({
name: 'other_values',
label: `Other contact #${others.length + 1}`,
type: 'text',
placeholder: '@acme',
value: '',
required: false,
}, {
name: 'other_labels',
label: `Other label #${others.length + 1}`,
type: 'text',
placeholder: 'Home, Work, etc.',
value: '',
required: false,
});
// Addresses
const addresses = contact.extra.addresses || [];
for (const [index, address] of addresses.entries()) {
fields.push({
name: 'address_line_1s',
label: `Address line 1 #${index + 1}`,
type: 'text',
placeholder: '992 Tyburn Rd',
value: address.line_1,
required: false,
});
fields.push({
name: 'address_line_2s',
label: `Address line 2 #${index + 1}`,
type: 'text',
placeholder: 'Apt 2',
value: address.line_2,
required: false,
});
fields.push({
name: 'address_cities',
label: `Address city #${index + 1}`,
type: 'text',
placeholder: 'Birmingham',
value: address.city,
required: false,
});
fields.push({
name: 'address_postal_codes',
label: `Address postal code #${index + 1}`,
type: 'text',
placeholder: 'B24 0TL',
value: address.postal_code,
required: false,
});
fields.push({
name: 'address_states',
label: `Address state #${index + 1}`,
type: 'text',
placeholder: 'West Midlands',
value: address.state,
required: false,
});
fields.push({
name: 'address_countries',
label: `Address country #${index + 1}`,
type: 'text',
placeholder: 'United Kingdom',
value: address.country,
required: false,
});
fields.push({
name: 'address_labels',
label: `Address label #${index + 1}`,
type: 'text',
placeholder: 'Home, Work, etc.',
value: address.label,
required: false,
});
}
fields.push({
name: 'address_line_1s',
label: `Address line 1 #${addresses.length + 1}`,
type: 'text',
placeholder: '992 Tyburn Rd',
value: '',
required: false,
}, {
name: 'address_line_2s',
label: `Address line 2 #${addresses.length + 1}`,
type: 'text',
placeholder: 'Apt 2',
value: '',
required: false,
}, {
name: 'address_cities',
label: `Address city #${addresses.length + 1}`,
type: 'text',
placeholder: 'Birmingham',
value: '',
required: false,
}, {
name: 'address_postal_codes',
label: `Address postal code #${addresses.length + 1}`,
type: 'text',
placeholder: 'B24 0TL',
value: '',
required: false,
}, {
name: 'address_states',
label: `Address state #${addresses.length + 1}`,
type: 'text',
placeholder: 'West Midlands',
value: '',
required: false,
}, {
name: 'address_countries',
label: `Address country #${addresses.length + 1}`,
type: 'text',
placeholder: 'United Kingdom',
value: '',
required: false,
}, {
name: 'address_labels',
label: `Address label #${addresses.length + 1}`,
type: 'text',
placeholder: 'Home, Work, etc.',
value: '',
required: false,
});
fields.push({
name: 'notes',
label: 'Notes',
type: 'textarea',
placeholder: 'Some notes...',
value: contact.extra.notes,
required: false,
});
return fields;
}
export default function ViewContact({ initialContact, formData: formDataObject, error, notice }: ViewContactProps) {
const isDeleting = useSignal<boolean>(false);
const contact = useSignal<Contact>(initialContact);
const formData = convertObjectToFormData(formDataObject);
async function onClickDeleteContact() {
if (confirm('Are you sure you want to delete this contact?')) {
if (isDeleting.value) {
return;
}
isDeleting.value = true;
try {
const requestBody: DeleteRequestBody = { contactId: contact.value.id, page: 1 };
const response = await fetch(`/api/contacts/delete`, {
method: 'POST',
body: JSON.stringify(requestBody),
});
const result = await response.json() as DeleteResponseBody;
if (!result.success) {
throw new Error('Failed to delete contact!');
}
window.location.href = '/contacts';
} catch (error) {
console.error(error);
}
isDeleting.value = false;
}
}
return (
<>
<section class='flex flex-row items-center justify-between mb-4'>
<a href='/contacts' class='mr-2'>View contacts</a>
<section class='flex items-center'>
<button
class='inline-block justify-center gap-x-1.5 rounded-md bg-red-800 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-red-600 ml-2'
type='button'
title='Delete contact'
onClick={() => onClickDeleteContact()}
>
<img
src='/images/delete.svg'
alt='Delete contact'
class={`white ${isDeleting.value ? 'animate-spin' : ''}`}
width={20}
height={20}
/>
</button>
</section>
</section>
<section class='mx-auto max-w-7xl my-8'>
{error
? (
<section class='notification-error'>
<h3>Failed to update!</h3>
<p>{error}</p>
</section>
)
: null}
{notice
? (
<section class='notification-success'>
<h3>Success!</h3>
<p>{notice}</p>
</section>
)
: null}
<form method='POST' class='mb-12'>
{formFields(contact.peek()).map((field) => generateFieldHtml(field, formData))}
<section class='flex justify-end mt-8 mb-4'>
<button class='button' type='submit'>Update contact</button>
</section>
</form>
<span
class={`flex justify-end items-center text-sm mt-1 mx-2 text-slate-100`}
>
{isDeleting.value
? (
<>
<img src='/images/loading.svg' class='white mr-2' width={18} height={18} />Deleting...
</>
)
: null}
{!isDeleting.value ? <>&nbsp;</> : null}
</span>
</section>
</>
);
}

199
islands/dashboard/Links.tsx Normal file
View File

@@ -0,0 +1,199 @@
import { useSignal } from '@preact/signals';
import { useEffect } from 'preact/hooks';
import { DashboardLink } from '/lib/types.ts';
import { validateUrl } from '/lib/utils.ts';
import { RequestBody, ResponseBody } from '/routes/api/dashboard/save-links.tsx';
interface LinksProps {
initialLinks: DashboardLink[];
}
export default function Links({ initialLinks }: LinksProps) {
const hasSavedTimeout = useSignal<ReturnType<typeof setTimeout>>(0);
const isSaving = useSignal<boolean>(false);
const hasSaved = useSignal<boolean>(false);
const links = useSignal<DashboardLink[]>(initialLinks);
async function saveLinks(newLinks: DashboardLink[]) {
if (isSaving.value) {
return;
}
hasSaved.value = false;
isSaving.value = true;
const oldLinks = [...links.value];
links.value = newLinks;
try {
const requestBody: RequestBody = { links: newLinks };
const response = await fetch(`/api/dashboard/save-links`, {
method: 'POST',
body: JSON.stringify(requestBody),
});
const result = await response.json() as ResponseBody;
if (!result.success) {
throw new Error('Failed to save notes!');
}
} catch (error) {
console.error(error);
links.value = [...oldLinks];
}
isSaving.value = false;
hasSaved.value = true;
if (hasSavedTimeout.value) {
clearTimeout(hasSavedTimeout.value);
}
hasSavedTimeout.value = setTimeout(() => {
hasSaved.value = false;
}, 3000);
}
useEffect(() => {
return () => {
if (hasSavedTimeout.value) {
clearTimeout(hasSavedTimeout.value);
}
};
});
function onClickAddLink() {
const name = (prompt(`What's the **name** for the new link?`) || '').trim();
const url = (prompt(`What's the **URL** for the new link?`) || '').trim();
if (!name || !url) {
alert('A name and URL are required for a new link!');
return;
}
if (!validateUrl(url)) {
alert('Invalid URL!');
return;
}
const newLinks = [...links.value, { name, url }];
saveLinks(newLinks);
}
function onClickDeleteLink(indexToDelete: number) {
if (confirm('Are you sure you want to delete this link?')) {
const newLinks = [...links.value];
newLinks.splice(indexToDelete, 1);
saveLinks(newLinks);
}
}
function onClickMoveLeftLink(indexToMoveLeft: number) {
if (indexToMoveLeft <= 0) {
return;
}
if (confirm('Are you sure you want to move this link left?')) {
const newLinks = [...links.value];
const linkToMove = newLinks.splice(indexToMoveLeft, 1);
newLinks.splice(indexToMoveLeft - 1, 0, linkToMove[0]);
saveLinks(newLinks);
}
}
return (
<>
<section class='flex flex-row items-center justify-end mb-4'>
<section class='flex items-center'>
<button
class='inline-block justify-center gap-x-1.5 rounded-md bg-[#51A4FB] px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-sky-400 ml-2'
type='button'
title='Add new link'
onClick={() => onClickAddLink()}
>
<img
src='/images/add.svg'
alt='Add new link'
class={`white`}
width={20}
height={20}
/>
</button>
</section>
</section>
<section class='mx-auto max-w-7xl px-6 lg:px-8 my-8'>
<section class='group grid grid-cols-1 gap-x-8 gap-y-16 text-center lg:grid-cols-3'>
{links.value.map((link, index) => (
<div class='group mx-auto flex max-w-xs flex-col gap-y-4 rounded shadow-md bg-slate-700 relative hover:bg-slate-600'>
<article class='order-first text-3xl font-semibold tracking-tight sm:text-2xl'>
<a href={link.url} class='text-white py-4 px-8 block' target='_blank' rel='noreferrer noopener'>
{link.name}
</a>
</article>
<span
class='invisible group-hover:visible absolute top-0 right-0 -mr-3 -mt-3 cursor-pointer'
onClick={() => onClickDeleteLink(index)}
>
<img
src='/images/delete.svg'
class='red drop-shadow-md'
width={24}
height={24}
alt='Delete link'
title='Delete link'
/>
</span>
{index > 0
? (
<span
class='invisible group-hover:visible absolute top-0 left-0 -ml-3 -mt-3 cursor-pointer'
onClick={() => onClickMoveLeftLink(index)}
>
<img
src='/images/left-circle.svg'
class='gray'
width={24}
height={24}
alt='Move link left'
title='Move link left'
/>
</span>
)
: null}
</div>
))}
</section>
<span
class={`flex justify-end items-center text-sm mt-1 mx-2 ${
hasSaved.value ? 'text-green-600' : 'text-slate-100'
}`}
>
{isSaving.value
? (
<>
<img src='/images/loading.svg' class='white mr-2' width={18} height={18} />Saving...
</>
)
: null}
{hasSaved.value
? (
<>
<img src='/images/check.svg' class='green mr-2' width={18} height={18} />Saved!
</>
)
: null}
{!isSaving.value && !hasSaved.value ? <>&nbsp;</> : null}
</span>
</section>
</>
);
}

View File

@@ -0,0 +1,98 @@
import { useSignal, useSignalEffect } from '@preact/signals';
import { useEffect } from 'preact/hooks';
import { RequestBody, ResponseBody } from '/routes/api/dashboard/save-notes.tsx';
interface NotesProps {
initialNotes: string;
}
export default function Notes({ initialNotes }: NotesProps) {
const saveTimeout = useSignal<ReturnType<typeof setTimeout>>(0);
const hasSavedTimeout = useSignal<ReturnType<typeof setTimeout>>(0);
const isSaving = useSignal<boolean>(false);
const hasSaved = useSignal<boolean>(false);
function saveNotes(newNotes: string) {
if (saveTimeout.value) {
clearTimeout(saveTimeout.value);
}
saveTimeout.value = setTimeout(async () => {
hasSaved.value = false;
isSaving.value = true;
try {
const requestBody: RequestBody = { notes: newNotes };
const response = await fetch(`/api/dashboard/save-notes`, {
method: 'POST',
body: JSON.stringify(requestBody),
});
const result = await response.json() as ResponseBody;
if (!result.success) {
throw new Error('Failed to save notes!');
}
} catch (error) {
console.error(error);
}
isSaving.value = false;
hasSaved.value = true;
}, 1000);
}
useSignalEffect(() => {
if (hasSaved.value && !hasSavedTimeout.value) {
hasSavedTimeout.value = setTimeout(() => {
hasSaved.value = false;
}, 3000);
}
});
useEffect(() => {
return () => {
if (saveTimeout.value) {
clearTimeout(saveTimeout.value);
}
if (hasSavedTimeout.value) {
clearTimeout(hasSavedTimeout.value);
}
};
}, []);
return (
<section class='flex flex-col'>
<textarea
class='my-2 input-field text-sm font-mono'
onInput={(event) => saveNotes(event.currentTarget.value)}
rows={10}
>
{initialNotes}
</textarea>
<span
class={`flex justify-end items-center text-sm mt-1 mx-2 ${
hasSaved.value ? 'text-green-600' : 'text-slate-100'
}`}
>
{isSaving.value
? (
<>
<img src='/images/loading.svg' class='white mr-2' width={18} height={18} />Saving...
</>
)
: null}
{hasSaved.value
? (
<>
<img src='/images/check.svg' class='green mr-2' width={18} height={18} />Saved!
</>
)
: null}
{!isSaving.value && !hasSaved.value ? <>&nbsp;</> : null}
</span>
</section>
);
}

265
islands/news/Articles.tsx Normal file
View File

@@ -0,0 +1,265 @@
import { useSignal } from '@preact/signals';
import { NewsFeedArticle } from '/lib/types.ts';
import {
RequestBody as RefreshRequestBody,
ResponseBody as RefreshResponseBody,
} from '/routes/api/news/refresh-articles.tsx';
import { RequestBody as ReadRequestBody, ResponseBody as ReadResponseBody } from '/routes/api/news/mark-read.tsx';
interface ArticlesProps {
initialArticles: NewsFeedArticle[];
}
interface Filter {
status: 'all' | 'unread';
}
export default function Articles({ initialArticles }: ArticlesProps) {
const isRefreshing = useSignal<boolean>(false);
const articles = useSignal<NewsFeedArticle[]>(initialArticles);
const filter = useSignal<Filter>({ status: 'unread' });
const sessionReadArticleIds = useSignal<Set<string>>(new Set());
const isFilterDropdownOpen = useSignal<boolean>(false);
const dateFormat = new Intl.DateTimeFormat('en-GB', { dateStyle: 'medium' });
async function refreshArticles() {
if (isRefreshing.value) {
return;
}
isRefreshing.value = true;
try {
const requestBody: RefreshRequestBody = {};
const response = await fetch(`/api/news/refresh-articles`, {
method: 'POST',
body: JSON.stringify(requestBody),
});
const result = await response.json() as RefreshResponseBody;
if (!result.success) {
throw new Error('Failed to refresh articles!');
}
articles.value = [...result.newArticles];
} catch (error) {
console.error(error);
}
isRefreshing.value = false;
}
const filteredArticles = articles.value.filter((article) => {
if (filter.value.status === 'unread') {
if (article.is_read && !sessionReadArticleIds.value.has(article.id)) {
return false;
}
return true;
}
return true;
});
async function onClickView(articleId: string) {
const newArticles = [...articles.value];
const matchingArticle = newArticles.find((article) => article.id === articleId);
if (matchingArticle) {
if (matchingArticle.is_read) {
return;
}
matchingArticle.is_read = true;
} else {
return;
}
sessionReadArticleIds.value.add(articleId);
articles.value = [...newArticles];
try {
const requestBody: ReadRequestBody = { articleId };
const response = await fetch(`/api/news/mark-read`, {
method: 'POST',
body: JSON.stringify(requestBody),
});
const result = await response.json() as ReadResponseBody;
if (!result.success) {
throw new Error('Failed to mark article as read!');
}
} catch (error) {
console.error(error);
}
}
async function onClickMarkAllRead() {
const newArticles = [...articles.value].map((article) => {
article.is_read = true;
sessionReadArticleIds.value.add(article.id);
return article;
});
articles.value = [...newArticles];
try {
const requestBody: ReadRequestBody = { articleId: 'all' };
const response = await fetch(`/api/news/mark-read`, {
method: 'POST',
body: JSON.stringify(requestBody),
});
const result = await response.json() as ReadResponseBody;
if (!result.success) {
throw new Error('Failed to mark all articles as read!');
}
} catch (error) {
console.error(error);
}
}
function toggleFilterDropdown() {
isFilterDropdownOpen.value = !isFilterDropdownOpen.value;
}
function setNewFilter(newFilter: Partial<Filter>) {
filter.value = { ...filter.value, ...newFilter };
isFilterDropdownOpen.value = false;
}
return (
<>
<section class='flex flex-row items-center justify-between mb-4'>
<a href='/news/feeds' class='mr-2'>Manage feeds</a>
<section class='flex items-center'>
<section class='relative inline-block text-left ml-2'>
<div>
<button
type='button'
class='inline-flex w-full justify-center gap-x-1.5 rounded-md bg-slate-700 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-slate-600'
id='filter-button'
aria-expanded='true'
aria-haspopup='true'
onClick={() => toggleFilterDropdown()}
>
Filter
<svg class='-mr-1 h-5 w-5 text-slate-400' viewBox='0 0 20 20' fill='currentColor' aria-hidden='true'>
<path
fill-rule='evenodd'
d='M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z'
clip-rule='evenodd'
/>
</svg>
</button>
</div>
<div
class={`absolute right-0 z-10 mt-2 w-44 origin-top-right rounded-md bg-slate-700 shadow-lg ring-1 ring-black ring-opacity-15 focus:outline-none ${
!isFilterDropdownOpen.value ? 'hidden' : ''
}`}
role='menu'
aria-orientation='vertical'
aria-labelledby='filter-button'
tabindex={-1}
>
<div class='py-1'>
<button
class={`text-white block px-4 py-2 text-sm w-full text-left hover:bg-slate-600 ${
filter.value.status === 'unread' ? 'font-semibold' : ''
}`}
onClick={() => setNewFilter({ status: 'unread' })}
>
Show only unread
</button>
<button
class={`text-white block px-4 py-2 text-sm w-full text-left hover:bg-slate-600 ${
filter.value.status === 'all' ? 'font-semibold' : ''
}`}
onClick={() => setNewFilter({ status: 'all' })}
>
Show all
</button>
</div>
</div>
</section>
<button
class='inline-block justify-center gap-x-1.5 rounded-md bg-slate-700 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-slate-600 ml-2'
type='button'
title='Mark all read'
onClick={() => onClickMarkAllRead()}
>
<img
src='/images/check-all.svg'
alt='Mark all read'
class={`white`}
width={20}
height={20}
/>
</button>
<button
class='inline-block justify-center gap-x-1.5 rounded-md bg-[#51A4FB] px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-sky-400 ml-2'
type='button'
title='Fetch new articles'
onClick={() => refreshArticles()}
>
<img
src='/images/refresh.svg'
alt='Fetch new articles'
class={`white ${isRefreshing.value ? 'animate-spin' : ''}`}
width={20}
height={20}
/>
</button>
</section>
</section>
<section class='mx-auto max-w-7xl my-8'>
{filteredArticles.length === 0
? <p class='my-4 block text-center text-lg text-slate-400'>There are no new articles to show.</p>
: (
<section class='divide-y divide-slate-800 shadow-sm rounded-md'>
{filteredArticles.map((article) => (
<details
class={`group order-first mx-auto max-w-full relative bg-slate-700 duration-150 first:rounded-tl-md first:rounded-tr-md last:rounded-bl-md last:rounded-br-md`}
>
<summary
class={`bg-slate-700 hover:bg-slate-600 px-4 py-4 cursor-pointer flex justify-between group-[:first-child]:rounded-tl-md group-[:first-child]:rounded-tr-md ${
article.is_read ? 'opacity-50' : 'font-semibold'
}`}
onClick={() => onClickView(article.id)}
>
<span class='mr-2'>{article.article_title}</span>
<span class='text-sm text-slate-300 ml-2 font-normal'>
{dateFormat.format(new Date(article.article_date))}
</span>
</summary>
<article class='overflow-auto max-w-full max-h-80 py-2 px-4 font-mono text-sm whitespace-pre-wrap border-t border-b border-slate-600'>
{article.article_summary}
</article>
<a
href={article.article_url}
class='py-4 px-8 flex justify-between text-right hover:bg-slate-600 group-[:last-child]:rounded-bl-md group-[:last-child]:rounded-br-md'
target='_blank'
rel='noreferrer noopener'
onClick={() => onClickView(article.id)}
>
<span class='text-sm text-slate-400 mr-2 font-normal'>{article.article_url}</span>
<span class='ml-2'>View article</span>
</a>
</details>
))}
</section>
)}
</section>
</>
);
}

372
islands/news/Feeds.tsx Normal file
View File

@@ -0,0 +1,372 @@
import { useSignal } from '@preact/signals';
import { NewsFeed } from '/lib/types.ts';
import { escapeHtml, validateUrl } from '/lib/utils.ts';
import { RequestBody as AddRequestBody, ResponseBody as AddResponseBody } from '/routes/api/news/add-feed.tsx';
import { RequestBody as DeleteRequestBody, ResponseBody as DeleteResponseBody } from '/routes/api/news/delete-feed.tsx';
import {
RequestBody as ImportRequestBody,
ResponseBody as ImportResponseBody,
} from '/routes/api/news/import-feeds.tsx';
interface FeedsProps {
initialFeeds: NewsFeed[];
}
function formatNewsFeedsToOpml(feeds: NewsFeed[]) {
return `<?xml version="1.0" encoding="UTF-8"?>
<opml version="2.0">
<head>
<title>Subscriptions</title>
</head>
<body>
${
feeds.map((feed) =>
`<outline title="${escapeHtml(feed.extra.title || '')}" text="${escapeHtml(feed.extra.title || '')}" type="${
feed.extra.feed_type || 'rss'
}" xmlUrl="${escapeHtml(feed.feed_url)}" htmlUrl="${escapeHtml(feed.feed_url)}"/>`
).join('\n ')
}
</body>
</opml>`;
}
function parseOpmlFromTextContents(html: string): string[] {
const feedUrls: string[] = [];
const document = new DOMParser().parseFromString(html, 'text/html');
const feeds = Array.from(document.getElementsByTagName('outline'));
for (const feed of feeds) {
const url = (feed.getAttribute('xmlUrl') || feed.getAttribute('htmlUrl') || '').trim();
if (validateUrl(url)) {
feedUrls.push(url);
}
}
return feedUrls;
}
export default function Feeds({ initialFeeds }: FeedsProps) {
const isAdding = useSignal<boolean>(false);
const isDeleting = useSignal<boolean>(false);
const isExporting = useSignal<boolean>(false);
const isImporting = useSignal<boolean>(false);
const feeds = useSignal<NewsFeed[]>(initialFeeds);
const isOptionsDropdownOpen = useSignal<boolean>(false);
const dateFormat = new Intl.DateTimeFormat('en-GB', { dateStyle: 'medium', timeStyle: 'short' });
async function onClickAddFeed() {
if (isAdding.value) {
return;
}
const url = (prompt(`What's the **URL** for the new feed?`) || '').trim();
if (!url) {
alert('A URL is required for a new feed!');
return;
}
if (!validateUrl(url)) {
alert('Invalid URL!');
return;
}
isAdding.value = true;
try {
const requestBody: AddRequestBody = { feedUrl: url };
const response = await fetch(`/api/news/add-feed`, {
method: 'POST',
body: JSON.stringify(requestBody),
});
const result = await response.json() as AddResponseBody;
if (!result.success) {
throw new Error('Failed to add feed!');
}
feeds.value = [...result.newFeeds];
} catch (error) {
console.error(error);
}
isAdding.value = false;
}
function toggleOptionsDropdown() {
isOptionsDropdownOpen.value = !isOptionsDropdownOpen.value;
}
async function onClickDeleteFeed(feedId: string) {
if (confirm('Are you sure you want to delete this feed and all its articles?')) {
if (isDeleting.value) {
return;
}
isDeleting.value = true;
try {
const requestBody: DeleteRequestBody = { feedId };
const response = await fetch(`/api/news/delete-feed`, {
method: 'POST',
body: JSON.stringify(requestBody),
});
const result = await response.json() as DeleteResponseBody;
if (!result.success) {
throw new Error('Failed to delete feed!');
}
feeds.value = [...result.newFeeds];
} catch (error) {
console.error(error);
}
isDeleting.value = false;
}
}
function onClickImportOpml() {
isOptionsDropdownOpen.value = false;
if (isImporting.value) {
return;
}
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.click();
fileInput.onchange = (event) => {
const files = (event.target as HTMLInputElement)?.files!;
const file = files[0];
if (!file) {
return;
}
const reader = new FileReader();
reader.onload = async (fileRead) => {
const importFileContents = fileRead.target?.result;
if (!importFileContents || isImporting.value) {
return;
}
isImporting.value = true;
try {
const feedUrls = parseOpmlFromTextContents(importFileContents!.toString());
const requestBody: ImportRequestBody = { feedUrls };
const response = await fetch(`/api/news/import-feeds`, {
method: 'POST',
body: JSON.stringify(requestBody),
});
const result = await response.json() as ImportResponseBody;
if (!result.success) {
throw new Error('Failed to import feeds!');
}
feeds.value = [...result.newFeeds];
} catch (error) {
console.error(error);
}
isImporting.value = false;
};
reader.readAsText(file, 'UTF-8');
};
}
function onClickExportOpml() {
isOptionsDropdownOpen.value = false;
if (isExporting.value) {
return;
}
isExporting.value = true;
const fileName = ['feeds-', new Date().toISOString().substring(0, 19).replace(/:/g, '-'), '.opml']
.join('');
const exportContents = formatNewsFeedsToOpml([...feeds.peek()]);
// Add content-type
const xmlContent = ['data:application/xml; charset=utf-8,', exportContents].join('');
// Download the file
const data = encodeURI(xmlContent);
const link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', fileName);
link.click();
link.remove();
isExporting.value = false;
}
return (
<>
<section class='flex flex-row items-center justify-between mb-4'>
<a href='/news' class='mr-2'>View articles</a>
<section class='flex items-center'>
<section class='relative inline-block text-left ml-2'>
<div>
<button
type='button'
class='inline-flex w-full justify-center gap-x-1.5 rounded-md bg-slate-700 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-slate-600'
id='filter-button'
aria-expanded='true'
aria-haspopup='true'
onClick={() => toggleOptionsDropdown()}
>
OPML
<svg class='-mr-1 h-5 w-5 text-slate-400' viewBox='0 0 20 20' fill='currentColor' aria-hidden='true'>
<path
fill-rule='evenodd'
d='M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z'
clip-rule='evenodd'
/>
</svg>
</button>
</div>
<div
class={`absolute right-0 z-10 mt-2 w-44 origin-top-right rounded-md bg-slate-700 shadow-lg ring-1 ring-black ring-opacity-15 focus:outline-none ${
!isOptionsDropdownOpen.value ? 'hidden' : ''
}`}
role='menu'
aria-orientation='vertical'
aria-labelledby='filter-button'
tabindex={-1}
>
<div class='py-1'>
<button
class={`text-white block px-4 py-2 text-sm w-full text-left hover:bg-slate-600`}
onClick={() => onClickImportOpml()}
>
Import OPML
</button>
<button
class={`text-white block px-4 py-2 text-sm w-full text-left hover:bg-slate-600`}
onClick={() => onClickExportOpml()}
>
Export OPML
</button>
</div>
</div>
</section>
<button
class='inline-block justify-center gap-x-1.5 rounded-md bg-[#51A4FB] px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-sky-400 ml-2'
type='button'
title='Add new feed'
onClick={() => onClickAddFeed()}
>
<img
src='/images/add.svg'
alt='Add new feed'
class={`white ${isAdding.value ? 'animate-spin' : ''}`}
width={20}
height={20}
/>
</button>
</section>
</section>
<section class='mx-auto max-w-7xl my-8'>
<table class='w-full border-collapse bg-slate-700 text-left text-sm text-slate-500 shadow-sm'>
<thead class='bg-gray-900'>
<tr>
<th scope='col' class='px-6 py-4 font-medium text-white'>Title & URL</th>
<th scope='col' class='px-6 py-4 font-medium text-white'>Last Crawl</th>
<th scope='col' class='px-6 py-4 font-medium text-white'>Type</th>
<th scope='col' class='px-6 py-4 font-medium text-white w-20'></th>
</tr>
</thead>
<tbody class='divide-y divide-slate-600 border-t border-slate-600'>
{feeds.value.map((newsFeed) => (
<tr class='hover:bg-slate-600 group'>
<td class='flex gap-3 px-6 py-4 font-normal text-white'>
<div class='text-sm'>
<div class='font-medium text-white'>{newsFeed.extra.title || 'N/A'}</div>
<div class='text-slate-400'>{newsFeed.feed_url}</div>
</div>
</td>
<td class='px-6 py-4 text-slate-200'>
{newsFeed.last_crawled_at ? dateFormat.format(new Date(newsFeed.last_crawled_at)) : 'N/A'}
</td>
<td class='px-6 py-4'>
<div class='text-xs font-semibold text-slate-200'>
{newsFeed.extra.feed_type?.split('').map((character) => character.toUpperCase()).join('') || 'N/A'}
</div>
</td>
<td class='px-6 py-4'>
<span
class='invisible cursor-pointer group-hover:visible opacity-50 hover:opacity-100'
onClick={() => onClickDeleteFeed(newsFeed.id)}
>
<img
src='/images/delete.svg'
class='red drop-shadow-md'
width={24}
height={24}
alt='Delete feed'
title='Delete feed'
/>
</span>
</td>
</tr>
))}
{feeds.value.length === 0
? (
<tr class='hover:bg-slate-600'>
<td class='flex gap-3 px-6 py-4 font-normal' colspan={4}>
<div class='text-md'>
<div class='font-medium text-slate-400'>No feeds to show</div>
</div>
</td>
</tr>
)
: null}
</tbody>
</table>
<span
class={`flex justify-end items-center text-sm mt-1 mx-2 text-slate-100`}
>
{isDeleting.value
? (
<>
<img src='/images/loading.svg' class='white mr-2' width={18} height={18} />Deleting...
</>
)
: null}
{isExporting.value
? (
<>
<img src='/images/loading.svg' class='white mr-2' width={18} height={18} />Exporting...
</>
)
: null}
{isImporting.value
? (
<>
<img src='/images/loading.svg' class='white mr-2' width={18} height={18} />Importing...
</>
)
: null}
{!isDeleting.value && !isExporting.value && !isImporting.value ? <>&nbsp;</> : null}
</span>
</section>
</>
);
}