Skip to content

Commit

Permalink
Fix ts errors
Browse files Browse the repository at this point in the history
  • Loading branch information
haishanh committed Jun 30, 2024
1 parent 97679ea commit 963b86f
Show file tree
Hide file tree
Showing 26 changed files with 93 additions and 83 deletions.
6 changes: 3 additions & 3 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,15 @@ export const handle: Handle = async function handle({ event, resolve }) {
return response;
}

let token: string;
let token: string | undefined;
const authHeader = request.headers.get('authorization');
if (authHeader) token = authHeader.replace(/[bB]earer\s/, '');

const sp = url.searchParams;
if (!token && sp.get('pat')) token = sp.get('pat');
if (!token && sp.get('pat')) token = sp.get('pat')!;

if (!token) {
const cookieHeader = request.headers.get('cookie');
const cookieHeader = request.headers.get('cookie') || '';
const cookies = cookieUtil.parseCookie(cookieHeader);
token = cookies.token;
}
Expand Down
4 changes: 2 additions & 2 deletions src/lib/client/backend.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ export type Backend = {
pat: string;
};

export function coalesceBase(b: Backend | null) {
export function coalesceBase(b?: Backend) {
return b && b.apiBase ? b.apiBase : '';
}

export function genAuthHeader(b: Backend | null) {
export function genAuthHeader(b?: Backend) {
return {
...(b && b.pat ? { Authorization: `Bearer ${b.pat}` } : undefined),
};
Expand Down
11 changes: 7 additions & 4 deletions src/lib/client/form.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,14 @@ type ValidationRuleItem = {
};

// it either returns { value: {} } or { error: {} }
export function validate<V>(rule: { [k in keyof V]: ValidationRuleItem[] }, value: V) {
const keys = Object.keys(value);
const validatedValue: V = {} as V;
export function validate<V extends { [key: string]: string }>(
rule: { [k in keyof V]: ValidationRuleItem[] },
value: V,
) {
const keys: (keyof V)[] = Object.keys(value);
const validatedValue: Partial<{[k in keyof V]: string}> = {};

const error: { [k in keyof V]: string } = {} as { [k in keyof V]: string };
const error: Partial<{ [k in keyof V]: string }> = {};
for (const k of keys) error[k] = '';

let valid = true;
Expand Down
2 changes: 1 addition & 1 deletion src/lib/client/group.store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export const groupMapById = derived<typeof groupList, Map<number, Group>>(groupL
export let fetchPromise: Promise<any>;
let initialFetchPromise: Promise<any>;

async function fetchGroups0(opts: { server: Backend }) {
async function fetchGroups0(opts: { server?: Backend }) {
const base = coalesceBase(opts?.server);
const ret = await request({
url: base + '/api/groups',
Expand Down
22 changes: 12 additions & 10 deletions src/lib/components/actions/popover.action.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,32 @@
export type PopoverPlacement = 'north' | 'south';

function positionPopover(node: HTMLDivElement, anchor: HTMLElement, vOffset: number) {
// popover rect
const p = node.getBoundingClientRect();
// anchor rect
const t = anchor.getBoundingClientRect();

let placement: 'north' | 'south';
let placement: PopoverPlacement;
let top = 0;
let left = 0;
const dimension: { height?: number } = {};

if (t.bottom + vOffset + p.height <= window.innerHeight) {
// try place below the anchor
top = t.top + t.height + vOffset + window.pageYOffset;
top = t.top + t.height + vOffset + window.scrollY;
placement = 'south';
} else if (t.top - vOffset >= p.height) {
top = t.top - vOffset - p.height + window.pageYOffset;
top = t.top - vOffset - p.height + window.scrollY;
placement = 'north';
} else {
const southVerticalReminder = window.innerHeight - t.bottom - vOffset;
const northVerticalReminder = t.top - vOffset;
if (southVerticalReminder > northVerticalReminder) {
top = t.top + t.height + vOffset + window.pageYOffset;
top = t.top + t.height + vOffset + window.scrollY;
placement = 'south';
dimension.height = southVerticalReminder - 3;
} else {
top = t.top - vOffset - p.height + window.pageYOffset;
top = t.top - vOffset - p.height + window.scrollY;
placement = 'north';
dimension.height = northVerticalReminder - 3;
}
Expand All @@ -33,16 +35,16 @@ function positionPopover(node: HTMLDivElement, anchor: HTMLElement, vOffset: num
const tmid = Math.floor((t.right - t.left) / 2) + t.left;
// try to center align it if possible
if (tmid + Math.ceil(p.width / 2) <= window.innerWidth && tmid <= t.left) {
left = tmid - Math.ceil(p.width / 2) + window.pageXOffset;
left = tmid - Math.ceil(p.width / 2) + window.scrollX;
} else if (t.left >= 0 && t.left + p.width <= window.innerWidth) {
// try align left edge with the anchor
left = t.left + window.pageXOffset;
left = t.left + window.scrollX;
} else if (t.right >= p.width) {
// aight with right edge of the anchor
left = t.right - p.width + window.pageXOffset;
left = t.right - p.width + window.scrollX;
} else {
// center to the *window*
left = Math.floor((window.innerWidth - p.width) / 2) + window.pageXOffset;
left = Math.floor((window.innerWidth - p.width) / 2) + window.scrollX;
}

return { position: { top, left }, placement };
Expand All @@ -54,7 +56,7 @@ export function popover(
vOffset: number;
anchor: HTMLElement;
closeFn: () => void;
onPosition: (opts: { position: { top: number; left: number }; placement: string }) => void;
onPosition: (opts: { position: { top: number; left: number }; placement: PopoverPlacement }) => void;
},
) {
const { anchor, closeFn, onPosition, vOffset } = params;
Expand Down
4 changes: 2 additions & 2 deletions src/lib/components/autocomplte/ListboxList.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
const dispatch = createEventDispatcher();
export let autoSelect = false;
export let filtered = [];
export let filtered: { name: string }[] = [];
$: {
const highlighted = filtered[highlightedIdx];
let idx: number;
let idx = -1;
if (highlighted) idx = filtered.findIndex((item) => item.name === highlighted.name);
if (highlighted && idx >= 0) {
if (highlightedIdx !== idx) highlightedIdx = idx;
Expand Down
6 changes: 2 additions & 4 deletions src/lib/components/autocomplte/Tag.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
import VisuallyHidden from '$lib/components/base/VisuallyHidden.svelte';
export let color: string | number = 1;
export let color : keyof typeof colorMap = '1';
export let hasClose = true;
export let tag: { name: string } = null;
export let tag: { name: string };
const dispatch = createEventDispatcher();
Expand All @@ -18,8 +18,6 @@
const colorMap = {
'0': 'color:#14551B;background:#ADF29B;',
// color: var(--accent);
// background-color: hsla(94deg, 99%, 33%, 0.2);
'1': 'color:var(--accent);background-color:hsla(94deg, 99%, 33%, 0.2)',
'2': 'color:#6C0E58;background:#FFAAD3;',
'3': 'color:var(--color-text);background:hsl(0deg 0% 97%);border-color:hsl(0deg 0% 80%);',
Expand Down
4 changes: 2 additions & 2 deletions src/lib/components/base/Field.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@
export let name = '';
export let value = '';
export let placeholder = '';
export let type: string | null = null;
export let type = '';
export let error = '';
function handleInputOnInput(e: InputEvent) {
function handleInputOnInput(e: Event) {
const target = e.target as HTMLInputElement;
value = target.value;
error = '';
Expand Down
4 changes: 2 additions & 2 deletions src/lib/components/base/popover/Popover.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import { createEventDispatcher } from 'svelte';
import { popover } from '$lib/components/actions/popover.action';
import { popover, type PopoverPlacement } from '$lib/components/actions/popover.action';
import Portal from '../misc/Portal.svelte';
const dispatch = createEventDispatcher();
Expand All @@ -22,7 +22,7 @@
function handlePopoverPositionChange(opts: {
position: { top: number; left: number };
placement: 'north' | 'south';
placement: PopoverPlacement;
}) {
const { top, left } = opts.position;
style = `top:${top}px;left:${left}px`;
Expand Down
1 change: 1 addition & 0 deletions src/lib/components/base/tabs/tabs.ctx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export const actions = {
selectTab: (ctx: ContextType, tab0: HTMLButtonElement) => {
tab0.focus();
const id = tab0.getAttribute('aria-controls');
if (!id) return;
const store = ctx.store;
store.update((s) => {
s.activePanelId = id;
Expand Down
2 changes: 1 addition & 1 deletion src/lib/components/base/toast/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ export type ToastItemInput = {

export type ToastItem = ToastItemInput & {
id: string;
duration?: number;
duration: number;
};
3 changes: 2 additions & 1 deletion src/lib/components/bookmark/BookmarkList.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@
}
}
function activatePrevBookmark() {
if (activeIdx > 0) activeIdx = activeIdx - 1;
if (typeof activeIdx === 'number' && activeIdx > 0) activeIdx = activeIdx - 1;
}
async function handleDeleteMulti() {
const ids = retrieveSelectedBookmarks();
Expand All @@ -188,6 +188,7 @@
function handleKeydown(event: KeyboardEvent) {
const active = document.activeElement;
if (!active) return;
const notSimple = event.metaKey || event.ctrlKey || event.shiftKey || event.isComposing;
if (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA') return;
if (document.querySelector('[data-cherry-modal-overlay]')) return;
Expand Down
8 changes: 3 additions & 5 deletions src/lib/components/bookmark/BookmarkTagsPreview.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,9 @@
let tags: TagType[] = hydrateTags(tagIds);
function hydrateTags(ids: number[]) {
if (ids && ids.length > 0) {
if (typeof ids[0] === 'number') {
const byId = $tagMapById;
return ids.map((id) => byId.get(id));
}
if (ids && ids.length > 0 && typeof ids[0] === 'number') {
const byId = $tagMapById;
return ids.map((id) => byId.get(id)!);
}
return [];
}
Expand Down
21 changes: 12 additions & 9 deletions src/lib/components/feature/UserSignForm.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,7 @@
username: [commonRule.email],
password: [passwordRule],
};
let error = {
username: '',
password: '',
};
let error: Partial<{ username: string; password: string }> = {};
let username = '';
let password = '';
Expand All @@ -40,17 +37,23 @@
}
function onSubmit() {
const result = validate(rule, { username, password });
const valueBeforeValidation = { username, password };
const result = validate(rule, valueBeforeValidation);
if (result.error) {
error = result.error;
return;
}
const toSubmit = {
...valueBeforeValidation,
...result.value,
};
let inflight: ReturnType<typeof join>;
if (kind === 'signup') {
inflight = join(result.value);
inflight = join(toSubmit);
} else {
inflight = signin(result.value);
inflight = signin(toSubmit);
}
inflight.then(onSuccessSignin, (err) => {
if (err instanceof RequestError) {
Expand Down Expand Up @@ -79,8 +82,8 @@
</script>

<form on:submit|preventDefault={onSubmit}>
<Field name="Email" type="email" placeholder="[email protected]" bind:value={username} error={error.username} />
<Field name="Password" type="password" placeholder="" bind:value={password} error={error.password} />
<Field name="Email" type="email" placeholder="[email protected]" bind:value={username} error={error.username || ''} />
<Field name="Password" type="password" placeholder="" bind:value={password} error={error.password || ''} />
<div class="action">
<Button type="submit">{kind === 'signup' ? 'Join' : 'Sign in'}</Button>
</div>
Expand Down
20 changes: 11 additions & 9 deletions src/lib/components/home/GroupAddModal.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -32,26 +32,28 @@
};
export const close = () => {
group = null;
group = { name: '' };
modal.close();
};
async function onSubmit() {
if (!group.name) return;
if (!group?.name) return;
try {
if ('id' in group) {
await updateGroup(group);
addToast({ description: 'Group renamed', status: 'success' });
} else {
await createGroup(group);
addToast({ description: 'Group created', status: 'success' });
if (group) {
if ('id' in group) {
await updateGroup(group);
addToast({ description: 'Group renamed', status: 'success' });
} else {
await createGroup(group);
addToast({ description: 'Group created', status: 'success' });
}
}
close();
} catch (err) {
console.log('update or create group error', err);
if (err instanceof RequestError) {
const response = err.response;
if (response.status === 409) {
if (response?.status === 409) {
addToast({ description: 'Group with this name already exists', status: 'warning' });
return;
}
Expand Down
5 changes: 3 additions & 2 deletions src/lib/components/home/GroupSideBar.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
function loadLastViewdGroupIds() {
try {
const v = localStorage.getItem(LAST_VIEWED_GROUPS_STORAGE_KEY);
if (!v) return [];
const items = JSON.parse(v);
return items || [];
} catch (e) {
Expand All @@ -71,13 +72,13 @@
}
type GroupLinkItem = { href: string; label: string; groupId: number | null };
const fixedLinks = [
const fixedLinks: GroupLinkItem[] = [
{ href: '/', label: 'All', groupId: null },
// { href: '/?group=0', label: 'Ungrouped', groupId: 0 },
];
// let links = fixedLinks;
let lastViewedLinks: typeof fixedLinks = [];
let lastViewedLinks: GroupLinkItem[] = [];
// $: {
// console.log(links.map((n) => n.label).join(','));
Expand Down
6 changes: 3 additions & 3 deletions src/lib/components/pagination/Pagination.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
export let pageUriTemplate = '';
export let maybeHasMore: boolean;
type PaginationItem = { page: number; link: string } | { gap: boolean };
type PaginationItem = { page: number } | { gap: boolean };
let items: PaginationItem[];
$: items = makeNavItems(total, current);
Expand All @@ -26,8 +26,8 @@
// ^
// 1 .. 95 96 97 98 99 100
function makeNavItems(total: number, current: number) {
let items = [];
if (total <= 0 || typeof total !== 'number') return items;
if (total <= 0 || typeof total !== 'number') return [];
let items: PaginationItem[] = [];
const maxNumberOfItems = 7;
if (total <= maxNumberOfItems) {
for (let i = 1; i <= total; i++) {
Expand Down
4 changes: 2 additions & 2 deletions src/lib/utils/nbf1Parser.util.do.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import { Parser as NetscapeBookmarkFile1Parser } from './nbf1Parser.util';

function parseNetscapeBookmarkFile1(html: string) {
const map = new Map();
new NetscapeBookmarkFile1Parser().parse(html, (b) => {
new NetscapeBookmarkFile1Parser(html, (b) => {
if (map.has(b.group)) {
map.get(b.group).push(b);
} else {
map.set(b.group, [b]);
}
});
}).parse();
for (const e of map) {
console.log(JSON.stringify(e[0], null, 2));
console.log(JSON.stringify(e[1], null, 2));
Expand Down
Loading

0 comments on commit 963b86f

Please sign in to comment.