Clean code.

This commit is contained in:
yuanhau 2025-05-10 22:05:10 +08:00
parent bf357f1c84
commit 5d58016b1d
39 changed files with 481 additions and 381 deletions

View file

@ -8,10 +8,10 @@ on:
jobs: jobs:
deploy: deploy:
runs-on: ubuntu-latest runs-on: ubuntu-latest
env: env:
DEPLOY_URL: ${{ secrets.DEPLOY_URL }} DEPLOY_URL: ${{ secrets.DEPLOY_URL }}
steps: steps:
- name: Send deployment request - name: Send deployment request
id: deploy-request id: deploy-request
@ -24,11 +24,11 @@ jobs:
--silent \ --silent \
--show-error \ --show-error \
"${{ secrets.DEPLOY_URL }}" || echo "Failed to send request") "${{ secrets.DEPLOY_URL }}" || echo "Failed to send request")
if [ $? -eq 0 ]; then if [ $? -eq 0 ]; then
echo "Deployment request sent successfully" echo "Deployment request sent successfully"
echo "Response: $RESPONSE" echo "Response: $RESPONSE"
else else
echo "Error sending deployment request" echo "Error sending deployment request"
exit 1 exit 1
fi fi

2
.gitignore vendored
View file

@ -25,4 +25,4 @@ logs
# Scraping data # Scraping data
.venv .venv
__pycache__ __pycache__

View file

@ -1,30 +1,33 @@
<script setup lang="ts"> <script setup lang="ts">
import type { ListboxRootEmits, ListboxRootProps } from 'reka-ui' import type { ListboxRootEmits, ListboxRootProps } from "reka-ui";
import { cn } from '@/lib/utils' import { cn } from "@/lib/utils";
import { ListboxRoot, useFilter, useForwardPropsEmits } from 'reka-ui' import { ListboxRoot, useFilter, useForwardPropsEmits } from "reka-ui";
import { computed, type HTMLAttributes, reactive, ref, watch } from 'vue' import { computed, type HTMLAttributes, reactive, ref, watch } from "vue";
import { provideCommandContext } from '.' import { provideCommandContext } from ".";
const props = withDefaults(defineProps<ListboxRootProps & { class?: HTMLAttributes['class'] }>(), { const props = withDefaults(
modelValue: '', defineProps<ListboxRootProps & { class?: HTMLAttributes["class"] }>(),
}) {
modelValue: "",
},
);
const emits = defineEmits<ListboxRootEmits>() const emits = defineEmits<ListboxRootEmits>();
const delegatedProps = computed(() => { const delegatedProps = computed(() => {
const { class: _, ...delegated } = props const { class: _, ...delegated } = props;
return delegated return delegated;
}) });
const forwarded = useForwardPropsEmits(delegatedProps, emits) const forwarded = useForwardPropsEmits(delegatedProps, emits);
const allItems = ref<Map<string, string>>(new Map()) const allItems = ref<Map<string, string>>(new Map());
const allGroups = ref<Map<string, Set<string>>>(new Map()) const allGroups = ref<Map<string, Set<string>>>(new Map());
const { contains } = useFilter({ sensitivity: 'base' }) const { contains } = useFilter({ sensitivity: "base" });
const filterState = reactive({ const filterState = reactive({
search: '', search: "",
filtered: { filtered: {
/** The count of all visible items. */ /** The count of all visible items. */
count: 0, count: 0,
@ -33,59 +36,66 @@ const filterState = reactive({
/** Set of groups with at least one visible item. */ /** Set of groups with at least one visible item. */
groups: new Set() as Set<string>, groups: new Set() as Set<string>,
}, },
}) });
function filterItems() { function filterItems() {
if (!filterState.search) { if (!filterState.search) {
filterState.filtered.count = allItems.value.size filterState.filtered.count = allItems.value.size;
// Do nothing, each item will know to show itself because search is empty // Do nothing, each item will know to show itself because search is empty
return return;
} }
// Reset the groups // Reset the groups
filterState.filtered.groups = new Set() filterState.filtered.groups = new Set();
let itemCount = 0 let itemCount = 0;
// Check which items should be included // Check which items should be included
for (const [id, value] of allItems.value) { for (const [id, value] of allItems.value) {
const score = contains(value, filterState.search) const score = contains(value, filterState.search);
filterState.filtered.items.set(id, score ? 1 : 0) filterState.filtered.items.set(id, score ? 1 : 0);
if (score) if (score) itemCount++;
itemCount++
} }
// Check which groups have at least 1 item shown // Check which groups have at least 1 item shown
for (const [groupId, group] of allGroups.value) { for (const [groupId, group] of allGroups.value) {
for (const itemId of group) { for (const itemId of group) {
if (filterState.filtered.items.get(itemId)! > 0) { if (filterState.filtered.items.get(itemId)! > 0) {
filterState.filtered.groups.add(groupId) filterState.filtered.groups.add(groupId);
break break;
} }
} }
} }
filterState.filtered.count = itemCount filterState.filtered.count = itemCount;
} }
function handleSelect() { function handleSelect() {
filterState.search = '' filterState.search = "";
} }
watch(() => filterState.search, () => { watch(
filterItems() () => filterState.search,
}) () => {
filterItems();
},
);
provideCommandContext({ provideCommandContext({
allItems, allItems,
allGroups, allGroups,
filterState, filterState,
}) });
</script> </script>
<template> <template>
<ListboxRoot <ListboxRoot
v-bind="forwarded" v-bind="forwarded"
:class="cn('flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground', props.class)" :class="
cn(
'flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground',
props.class,
)
"
> >
<slot /> <slot />
</ListboxRoot> </ListboxRoot>

View file

@ -1,19 +1,21 @@
<script setup lang="ts"> <script setup lang="ts">
import type { DialogRootEmits, DialogRootProps } from 'reka-ui' import type { DialogRootEmits, DialogRootProps } from "reka-ui";
import { Dialog, DialogContent } from '@/components/ui/dialog' import { Dialog, DialogContent } from "@/components/ui/dialog";
import { useForwardPropsEmits } from 'reka-ui' import { useForwardPropsEmits } from "reka-ui";
import Command from './Command.vue' import Command from "./Command.vue";
const props = defineProps<DialogRootProps>() const props = defineProps<DialogRootProps>();
const emits = defineEmits<DialogRootEmits>() const emits = defineEmits<DialogRootEmits>();
const forwarded = useForwardPropsEmits(props, emits) const forwarded = useForwardPropsEmits(props, emits);
</script> </script>
<template> <template>
<Dialog v-bind="forwarded"> <Dialog v-bind="forwarded">
<DialogContent class="overflow-hidden p-0 shadow-lg"> <DialogContent class="overflow-hidden p-0 shadow-lg">
<Command class="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5"> <Command
class="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5"
>
<slot /> <slot />
</Command> </Command>
</DialogContent> </DialogContent>

View file

@ -1,25 +1,32 @@
<script setup lang="ts"> <script setup lang="ts">
import type { PrimitiveProps } from 'reka-ui' import type { PrimitiveProps } from "reka-ui";
import { cn } from '@/lib/utils' import { cn } from "@/lib/utils";
import { Primitive } from 'reka-ui' import { Primitive } from "reka-ui";
import { computed, type HTMLAttributes } from 'vue' import { computed, type HTMLAttributes } from "vue";
import { useCommand } from '.' import { useCommand } from ".";
const props = defineProps<PrimitiveProps & { class?: HTMLAttributes['class'] }>() const props = defineProps<
PrimitiveProps & { class?: HTMLAttributes["class"] }
>();
const delegatedProps = computed(() => { const delegatedProps = computed(() => {
const { class: _, ...delegated } = props const { class: _, ...delegated } = props;
return delegated return delegated;
}) });
const { filterState } = useCommand() const { filterState } = useCommand();
const isRender = computed(() => !!filterState.search && filterState.filtered.count === 0, const isRender = computed(
) () => !!filterState.search && filterState.filtered.count === 0,
);
</script> </script>
<template> <template>
<Primitive v-if="isRender" v-bind="delegatedProps" :class="cn('py-6 text-center text-sm', props.class)"> <Primitive
v-if="isRender"
v-bind="delegatedProps"
:class="cn('py-6 text-center text-sm', props.class)"
>
<slot /> <slot />
</Primitive> </Primitive>
</template> </template>

View file

@ -1,44 +1,55 @@
<script setup lang="ts"> <script setup lang="ts">
import type { ListboxGroupProps } from 'reka-ui' import type { ListboxGroupProps } from "reka-ui";
import { cn } from '@/lib/utils' import { cn } from "@/lib/utils";
import { ListboxGroup, ListboxGroupLabel, useId } from 'reka-ui' import { ListboxGroup, ListboxGroupLabel, useId } from "reka-ui";
import { computed, type HTMLAttributes, onMounted, onUnmounted } from 'vue' import { computed, type HTMLAttributes, onMounted, onUnmounted } from "vue";
import { provideCommandGroupContext, useCommand } from '.' import { provideCommandGroupContext, useCommand } from ".";
const props = defineProps<ListboxGroupProps & { const props = defineProps<
class?: HTMLAttributes['class'] ListboxGroupProps & {
heading?: string class?: HTMLAttributes["class"];
}>() heading?: string;
}
>();
const delegatedProps = computed(() => { const delegatedProps = computed(() => {
const { class: _, ...delegated } = props const { class: _, ...delegated } = props;
return delegated return delegated;
}) });
const { allGroups, filterState } = useCommand() const { allGroups, filterState } = useCommand();
const id = useId() const id = useId();
const isRender = computed(() => !filterState.search ? true : filterState.filtered.groups.has(id)) const isRender = computed(() =>
!filterState.search ? true : filterState.filtered.groups.has(id),
);
provideCommandGroupContext({ id }) provideCommandGroupContext({ id });
onMounted(() => { onMounted(() => {
if (!allGroups.value.has(id)) if (!allGroups.value.has(id)) allGroups.value.set(id, new Set());
allGroups.value.set(id, new Set()) });
})
onUnmounted(() => { onUnmounted(() => {
allGroups.value.delete(id) allGroups.value.delete(id);
}) });
</script> </script>
<template> <template>
<ListboxGroup <ListboxGroup
v-bind="delegatedProps" v-bind="delegatedProps"
:id="id" :id="id"
:class="cn('overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground', props.class)" :class="
cn(
'overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground',
props.class,
)
"
:hidden="isRender ? undefined : true" :hidden="isRender ? undefined : true"
> >
<ListboxGroupLabel v-if="heading" class="px-2 py-1.5 text-xs font-medium text-muted-foreground"> <ListboxGroupLabel
v-if="heading"
class="px-2 py-1.5 text-xs font-medium text-muted-foreground"
>
{{ heading }} {{ heading }}
</ListboxGroupLabel> </ListboxGroupLabel>
<slot /> <slot />

View file

@ -1,27 +1,33 @@
<script setup lang="ts"> <script setup lang="ts">
import { cn } from '@/lib/utils' import { cn } from "@/lib/utils";
import { Search } from 'lucide-vue-next' import { Search } from "lucide-vue-next";
import { ListboxFilter, type ListboxFilterProps, useForwardProps } from 'reka-ui' import {
import { computed, type HTMLAttributes } from 'vue' ListboxFilter,
import { useCommand } from '.' type ListboxFilterProps,
useForwardProps,
} from "reka-ui";
import { computed, type HTMLAttributes } from "vue";
import { useCommand } from ".";
defineOptions({ defineOptions({
inheritAttrs: false, inheritAttrs: false,
}) });
const props = defineProps<ListboxFilterProps & { const props = defineProps<
class?: HTMLAttributes['class'] ListboxFilterProps & {
}>() class?: HTMLAttributes["class"];
}
>();
const delegatedProps = computed(() => { const delegatedProps = computed(() => {
const { class: _, ...delegated } = props const { class: _, ...delegated } = props;
return delegated return delegated;
}) });
const forwardedProps = useForwardProps(delegatedProps) const forwardedProps = useForwardProps(delegatedProps);
const { filterState } = useCommand() const { filterState } = useCommand();
</script> </script>
<template> <template>
@ -31,7 +37,12 @@ const { filterState } = useCommand()
v-bind="{ ...forwardedProps, ...$attrs }" v-bind="{ ...forwardedProps, ...$attrs }"
v-model="filterState.search" v-model="filterState.search"
auto-focus auto-focus
:class="cn('flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50', props.class)" :class="
cn(
'flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50',
props.class,
)
"
/> />
</div> </div>
</template> </template>

View file

@ -1,32 +1,39 @@
<script setup lang="ts"> <script setup lang="ts">
import type { ListboxItemEmits, ListboxItemProps } from 'reka-ui' import type { ListboxItemEmits, ListboxItemProps } from "reka-ui";
import { cn } from '@/lib/utils' import { cn } from "@/lib/utils";
import { useCurrentElement } from '@vueuse/core' import { useCurrentElement } from "@vueuse/core";
import { ListboxItem, useForwardPropsEmits, useId } from 'reka-ui' import { ListboxItem, useForwardPropsEmits, useId } from "reka-ui";
import { computed, type HTMLAttributes, onMounted, onUnmounted, ref } from 'vue' import {
import { useCommand, useCommandGroup } from '.' computed,
type HTMLAttributes,
onMounted,
onUnmounted,
ref,
} from "vue";
import { useCommand, useCommandGroup } from ".";
const props = defineProps<ListboxItemProps & { class?: HTMLAttributes['class'] }>() const props = defineProps<
const emits = defineEmits<ListboxItemEmits>() ListboxItemProps & { class?: HTMLAttributes["class"] }
>();
const emits = defineEmits<ListboxItemEmits>();
const delegatedProps = computed(() => { const delegatedProps = computed(() => {
const { class: _, ...delegated } = props const { class: _, ...delegated } = props;
return delegated return delegated;
}) });
const forwarded = useForwardPropsEmits(delegatedProps, emits) const forwarded = useForwardPropsEmits(delegatedProps, emits);
const id = useId() const id = useId();
const { filterState, allItems, allGroups } = useCommand() const { filterState, allItems, allGroups } = useCommand();
const groupContext = useCommandGroup() const groupContext = useCommandGroup();
const isRender = computed(() => { const isRender = computed(() => {
if (!filterState.search) { if (!filterState.search) {
return true; return true;
} } else {
else { const filteredCurrentItem = filterState.filtered.items.get(id);
const filteredCurrentItem = filterState.filtered.items.get(id)
// If the filtered items is undefined means not in the all times map yet // If the filtered items is undefined means not in the all times map yet
// Do the first render to add into the map // Do the first render to add into the map
if (filteredCurrentItem === undefined) { if (filteredCurrentItem === undefined) {
@ -36,30 +43,31 @@ const isRender = computed(() => {
// Check with filter // Check with filter
return filteredCurrentItem > 0; return filteredCurrentItem > 0;
} }
}) });
const itemRef = ref() const itemRef = ref();
const currentElement = useCurrentElement(itemRef) const currentElement = useCurrentElement(itemRef);
onMounted(() => { onMounted(() => {
if (!(currentElement.value instanceof HTMLElement)) if (!(currentElement.value instanceof HTMLElement)) return;
return
// textValue to perform filter // textValue to perform filter
allItems.value.set(id, currentElement.value.textContent ?? props.value.toString()) allItems.value.set(
id,
currentElement.value.textContent ?? props.value.toString(),
);
const groupId = groupContext?.id const groupId = groupContext?.id;
if (groupId) { if (groupId) {
if (!allGroups.value.has(groupId)) { if (!allGroups.value.has(groupId)) {
allGroups.value.set(groupId, new Set([id])) allGroups.value.set(groupId, new Set([id]));
} } else {
else { allGroups.value.get(groupId)?.add(id);
allGroups.value.get(groupId)?.add(id)
} }
} }
}) });
onUnmounted(() => { onUnmounted(() => {
allItems.value.delete(id) allItems.value.delete(id);
}) });
</script> </script>
<template> <template>
@ -68,10 +76,17 @@ onUnmounted(() => {
v-bind="forwarded" v-bind="forwarded"
:id="id" :id="id"
ref="itemRef" ref="itemRef"
:class="cn('relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:size-4 [&_svg]:shrink-0', props.class)" :class="
@select="() => { cn(
filterState.search = '' 'relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:size-4 [&_svg]:shrink-0',
}" props.class,
)
"
@select="
() => {
filterState.search = '';
}
"
> >
<slot /> <slot />
</ListboxItem> </ListboxItem>

View file

@ -1,22 +1,27 @@
<script setup lang="ts"> <script setup lang="ts">
import type { ListboxContentProps } from 'reka-ui' import type { ListboxContentProps } from "reka-ui";
import { cn } from '@/lib/utils' import { cn } from "@/lib/utils";
import { ListboxContent, useForwardProps } from 'reka-ui' import { ListboxContent, useForwardProps } from "reka-ui";
import { computed, type HTMLAttributes } from 'vue' import { computed, type HTMLAttributes } from "vue";
const props = defineProps<ListboxContentProps & { class?: HTMLAttributes['class'] }>() const props = defineProps<
ListboxContentProps & { class?: HTMLAttributes["class"] }
>();
const delegatedProps = computed(() => { const delegatedProps = computed(() => {
const { class: _, ...delegated } = props const { class: _, ...delegated } = props;
return delegated return delegated;
}) });
const forwarded = useForwardProps(delegatedProps) const forwarded = useForwardProps(delegatedProps);
</script> </script>
<template> <template>
<ListboxContent v-bind="forwarded" :class="cn('max-h-[300px] overflow-y-auto overflow-x-hidden', props.class)"> <ListboxContent
v-bind="forwarded"
:class="cn('max-h-[300px] overflow-y-auto overflow-x-hidden', props.class)"
>
<div role="presentation"> <div role="presentation">
<slot /> <slot />
</div> </div>

View file

@ -1,16 +1,18 @@
<script setup lang="ts"> <script setup lang="ts">
import type { SeparatorProps } from 'reka-ui' import type { SeparatorProps } from "reka-ui";
import { cn } from '@/lib/utils' import { cn } from "@/lib/utils";
import { Separator } from 'reka-ui' import { Separator } from "reka-ui";
import { computed, type HTMLAttributes } from 'vue' import { computed, type HTMLAttributes } from "vue";
const props = defineProps<SeparatorProps & { class?: HTMLAttributes['class'] }>() const props = defineProps<
SeparatorProps & { class?: HTMLAttributes["class"] }
>();
const delegatedProps = computed(() => { const delegatedProps = computed(() => {
const { class: _, ...delegated } = props const { class: _, ...delegated } = props;
return delegated return delegated;
}) });
</script> </script>
<template> <template>

View file

@ -1,14 +1,18 @@
<script setup lang="ts"> <script setup lang="ts">
import type { HTMLAttributes } from 'vue' import type { HTMLAttributes } from "vue";
import { cn } from '@/lib/utils' import { cn } from "@/lib/utils";
const props = defineProps<{ const props = defineProps<{
class?: HTMLAttributes['class'] class?: HTMLAttributes["class"];
}>() }>();
</script> </script>
<template> <template>
<span :class="cn('ml-auto text-xs tracking-widest text-muted-foreground', props.class)"> <span
:class="
cn('ml-auto text-xs tracking-widest text-muted-foreground', props.class)
"
>
<slot /> <slot />
</span> </span>
</template> </template>

View file

@ -1,25 +1,29 @@
import type { Ref } from 'vue' import type { Ref } from "vue";
import { createContext } from 'reka-ui' import { createContext } from "reka-ui";
export { default as Command } from './Command.vue' export { default as Command } from "./Command.vue";
export { default as CommandDialog } from './CommandDialog.vue' export { default as CommandDialog } from "./CommandDialog.vue";
export { default as CommandEmpty } from './CommandEmpty.vue' export { default as CommandEmpty } from "./CommandEmpty.vue";
export { default as CommandGroup } from './CommandGroup.vue' export { default as CommandGroup } from "./CommandGroup.vue";
export { default as CommandInput } from './CommandInput.vue' export { default as CommandInput } from "./CommandInput.vue";
export { default as CommandItem } from './CommandItem.vue' export { default as CommandItem } from "./CommandItem.vue";
export { default as CommandList } from './CommandList.vue' export { default as CommandList } from "./CommandList.vue";
export { default as CommandSeparator } from './CommandSeparator.vue' export { default as CommandSeparator } from "./CommandSeparator.vue";
export { default as CommandShortcut } from './CommandShortcut.vue' export { default as CommandShortcut } from "./CommandShortcut.vue";
export const [useCommand, provideCommandContext] = createContext<{ export const [useCommand, provideCommandContext] = createContext<{
allItems: Ref<Map<string, string>> allItems: Ref<Map<string, string>>;
allGroups: Ref<Map<string, Set<string>>> allGroups: Ref<Map<string, Set<string>>>;
filterState: { filterState: {
search: string search: string;
filtered: { count: number, items: Map<string, number>, groups: Set<string> } filtered: {
} count: number;
}>('Command') items: Map<string, number>;
groups: Set<string>;
};
};
}>("Command");
export const [useCommandGroup, provideCommandGroupContext] = createContext<{ export const [useCommandGroup, provideCommandGroupContext] = createContext<{
id?: string id?: string;
}>('CommandGroup') }>("CommandGroup");

View file

@ -1,10 +1,15 @@
<script setup lang="ts"> <script setup lang="ts">
import { DialogRoot, type DialogRootEmits, type DialogRootProps, useForwardPropsEmits } from 'reka-ui' import {
DialogRoot,
type DialogRootEmits,
type DialogRootProps,
useForwardPropsEmits,
} from "reka-ui";
const props = defineProps<DialogRootProps>() const props = defineProps<DialogRootProps>();
const emits = defineEmits<DialogRootEmits>() const emits = defineEmits<DialogRootEmits>();
const forwarded = useForwardPropsEmits(props, emits) const forwarded = useForwardPropsEmits(props, emits);
</script> </script>
<template> <template>

View file

@ -1,7 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { DialogClose, type DialogCloseProps } from 'reka-ui' import { DialogClose, type DialogCloseProps } from "reka-ui";
const props = defineProps<DialogCloseProps>() const props = defineProps<DialogCloseProps>();
</script> </script>
<template> <template>

View file

@ -1,6 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { cn } from '@/lib/utils' import { cn } from "@/lib/utils";
import { X } from 'lucide-vue-next' import { X } from "lucide-vue-next";
import { import {
DialogClose, DialogClose,
DialogContent, DialogContent,
@ -9,19 +9,21 @@ import {
DialogOverlay, DialogOverlay,
DialogPortal, DialogPortal,
useForwardPropsEmits, useForwardPropsEmits,
} from 'reka-ui' } from "reka-ui";
import { computed, type HTMLAttributes } from 'vue' import { computed, type HTMLAttributes } from "vue";
const props = defineProps<DialogContentProps & { class?: HTMLAttributes['class'] }>() const props = defineProps<
const emits = defineEmits<DialogContentEmits>() DialogContentProps & { class?: HTMLAttributes["class"] }
>();
const emits = defineEmits<DialogContentEmits>();
const delegatedProps = computed(() => { const delegatedProps = computed(() => {
const { class: _, ...delegated } = props const { class: _, ...delegated } = props;
return delegated return delegated;
}) });
const forwarded = useForwardPropsEmits(delegatedProps, emits) const forwarded = useForwardPropsEmits(delegatedProps, emits);
</script> </script>
<template> <template>
@ -35,7 +37,8 @@ const forwarded = useForwardPropsEmits(delegatedProps, emits)
cn( cn(
'fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg', 'fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
props.class, props.class,
)" )
"
> >
<slot /> <slot />

View file

@ -1,17 +1,23 @@
<script setup lang="ts"> <script setup lang="ts">
import { cn } from '@/lib/utils' import { cn } from "@/lib/utils";
import { DialogDescription, type DialogDescriptionProps, useForwardProps } from 'reka-ui' import {
import { computed, type HTMLAttributes } from 'vue' DialogDescription,
type DialogDescriptionProps,
useForwardProps,
} from "reka-ui";
import { computed, type HTMLAttributes } from "vue";
const props = defineProps<DialogDescriptionProps & { class?: HTMLAttributes['class'] }>() const props = defineProps<
DialogDescriptionProps & { class?: HTMLAttributes["class"] }
>();
const delegatedProps = computed(() => { const delegatedProps = computed(() => {
const { class: _, ...delegated } = props const { class: _, ...delegated } = props;
return delegated return delegated;
}) });
const forwardedProps = useForwardProps(delegatedProps) const forwardedProps = useForwardProps(delegatedProps);
</script> </script>
<template> <template>

View file

@ -1,8 +1,8 @@
<script setup lang="ts"> <script setup lang="ts">
import type { HTMLAttributes } from 'vue' import type { HTMLAttributes } from "vue";
import { cn } from '@/lib/utils' import { cn } from "@/lib/utils";
const props = defineProps<{ class?: HTMLAttributes['class'] }>() const props = defineProps<{ class?: HTMLAttributes["class"] }>();
</script> </script>
<template> <template>

View file

@ -1,10 +1,10 @@
<script setup lang="ts"> <script setup lang="ts">
import type { HTMLAttributes } from 'vue' import type { HTMLAttributes } from "vue";
import { cn } from '@/lib/utils' import { cn } from "@/lib/utils";
const props = defineProps<{ const props = defineProps<{
class?: HTMLAttributes['class'] class?: HTMLAttributes["class"];
}>() }>();
</script> </script>
<template> <template>

View file

@ -1,6 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { cn } from '@/lib/utils' import { cn } from "@/lib/utils";
import { X } from 'lucide-vue-next' import { X } from "lucide-vue-next";
import { import {
DialogClose, DialogClose,
DialogContent, DialogContent,
@ -9,19 +9,21 @@ import {
DialogOverlay, DialogOverlay,
DialogPortal, DialogPortal,
useForwardPropsEmits, useForwardPropsEmits,
} from 'reka-ui' } from "reka-ui";
import { computed, type HTMLAttributes } from 'vue' import { computed, type HTMLAttributes } from "vue";
const props = defineProps<DialogContentProps & { class?: HTMLAttributes['class'] }>() const props = defineProps<
const emits = defineEmits<DialogContentEmits>() DialogContentProps & { class?: HTMLAttributes["class"] }
>();
const emits = defineEmits<DialogContentEmits>();
const delegatedProps = computed(() => { const delegatedProps = computed(() => {
const { class: _, ...delegated } = props const { class: _, ...delegated } = props;
return delegated return delegated;
}) });
const forwarded = useForwardPropsEmits(delegatedProps, emits) const forwarded = useForwardPropsEmits(delegatedProps, emits);
</script> </script>
<template> <template>
@ -37,13 +39,18 @@ const forwarded = useForwardPropsEmits(delegatedProps, emits)
) )
" "
v-bind="forwarded" v-bind="forwarded"
@pointer-down-outside="(event) => { @pointer-down-outside="
const originalEvent = event.detail.originalEvent; (event) => {
const target = originalEvent.target as HTMLElement; const originalEvent = event.detail.originalEvent;
if (originalEvent.offsetX > target.clientWidth || originalEvent.offsetY > target.clientHeight) { const target = originalEvent.target as HTMLElement;
event.preventDefault(); if (
originalEvent.offsetX > target.clientWidth ||
originalEvent.offsetY > target.clientHeight
) {
event.preventDefault();
}
} }
}" "
> >
<slot /> <slot />

View file

@ -1,27 +1,26 @@
<script setup lang="ts"> <script setup lang="ts">
import { cn } from '@/lib/utils' import { cn } from "@/lib/utils";
import { DialogTitle, type DialogTitleProps, useForwardProps } from 'reka-ui' import { DialogTitle, type DialogTitleProps, useForwardProps } from "reka-ui";
import { computed, type HTMLAttributes } from 'vue' import { computed, type HTMLAttributes } from "vue";
const props = defineProps<DialogTitleProps & { class?: HTMLAttributes['class'] }>() const props = defineProps<
DialogTitleProps & { class?: HTMLAttributes["class"] }
>();
const delegatedProps = computed(() => { const delegatedProps = computed(() => {
const { class: _, ...delegated } = props const { class: _, ...delegated } = props;
return delegated return delegated;
}) });
const forwardedProps = useForwardProps(delegatedProps) const forwardedProps = useForwardProps(delegatedProps);
</script> </script>
<template> <template>
<DialogTitle <DialogTitle
v-bind="forwardedProps" v-bind="forwardedProps"
:class=" :class="
cn( cn('text-lg font-semibold leading-none tracking-tight', props.class)
'text-lg font-semibold leading-none tracking-tight',
props.class,
)
" "
> >
<slot /> <slot />

View file

@ -1,7 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { DialogTrigger, type DialogTriggerProps } from 'reka-ui' import { DialogTrigger, type DialogTriggerProps } from "reka-ui";
const props = defineProps<DialogTriggerProps>() const props = defineProps<DialogTriggerProps>();
</script> </script>
<template> <template>

View file

@ -1,9 +1,9 @@
export { default as Dialog } from './Dialog.vue' export { default as Dialog } from "./Dialog.vue";
export { default as DialogClose } from './DialogClose.vue' export { default as DialogClose } from "./DialogClose.vue";
export { default as DialogContent } from './DialogContent.vue' export { default as DialogContent } from "./DialogContent.vue";
export { default as DialogDescription } from './DialogDescription.vue' export { default as DialogDescription } from "./DialogDescription.vue";
export { default as DialogFooter } from './DialogFooter.vue' export { default as DialogFooter } from "./DialogFooter.vue";
export { default as DialogHeader } from './DialogHeader.vue' export { default as DialogHeader } from "./DialogHeader.vue";
export { default as DialogScrollContent } from './DialogScrollContent.vue' export { default as DialogScrollContent } from "./DialogScrollContent.vue";
export { default as DialogTitle } from './DialogTitle.vue' export { default as DialogTitle } from "./DialogTitle.vue";
export { default as DialogTrigger } from './DialogTrigger.vue' export { default as DialogTrigger } from "./DialogTrigger.vue";

View file

@ -1,10 +1,15 @@
<script setup lang="ts"> <script setup lang="ts">
import { HoverCardRoot, type HoverCardRootEmits, type HoverCardRootProps, useForwardPropsEmits } from 'reka-ui' import {
HoverCardRoot,
type HoverCardRootEmits,
type HoverCardRootProps,
useForwardPropsEmits,
} from "reka-ui";
const props = defineProps<HoverCardRootProps>() const props = defineProps<HoverCardRootProps>();
const emits = defineEmits<HoverCardRootEmits>() const emits = defineEmits<HoverCardRootEmits>();
const forwarded = useForwardPropsEmits(props, emits) const forwarded = useForwardPropsEmits(props, emits);
</script> </script>
<template> <template>

View file

@ -1,27 +1,27 @@
<script setup lang="ts"> <script setup lang="ts">
import { cn } from '@/lib/utils' import { cn } from "@/lib/utils";
import { import {
HoverCardContent, HoverCardContent,
type HoverCardContentProps, type HoverCardContentProps,
HoverCardPortal, HoverCardPortal,
useForwardProps, useForwardProps,
} from 'reka-ui' } from "reka-ui";
import { computed, type HTMLAttributes } from 'vue' import { computed, type HTMLAttributes } from "vue";
const props = withDefaults( const props = withDefaults(
defineProps<HoverCardContentProps & { class?: HTMLAttributes['class'] }>(), defineProps<HoverCardContentProps & { class?: HTMLAttributes["class"] }>(),
{ {
sideOffset: 4, sideOffset: 4,
}, },
) );
const delegatedProps = computed(() => { const delegatedProps = computed(() => {
const { class: _, ...delegated } = props const { class: _, ...delegated } = props;
return delegated return delegated;
}) });
const forwardedProps = useForwardProps(delegatedProps) const forwardedProps = useForwardProps(delegatedProps);
</script> </script>
<template> <template>

View file

@ -1,7 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { HoverCardTrigger, type HoverCardTriggerProps } from 'reka-ui' import { HoverCardTrigger, type HoverCardTriggerProps } from "reka-ui";
const props = defineProps<HoverCardTriggerProps>() const props = defineProps<HoverCardTriggerProps>();
</script> </script>
<template> <template>

View file

@ -1,3 +1,3 @@
export { default as HoverCard } from './HoverCard.vue' export { default as HoverCard } from "./HoverCard.vue";
export { default as HoverCardContent } from './HoverCardContent.vue' export { default as HoverCardContent } from "./HoverCardContent.vue";
export { default as HoverCardTrigger } from './HoverCardTrigger.vue' export { default as HoverCardTrigger } from "./HoverCardTrigger.vue";

View file

@ -42,7 +42,6 @@ create table if not exists newsProvidersZh (
) )
`; `;
const createGoLinks = await sql` const createGoLinks = await sql`
create table if not exists go_links { create table if not exists go_links {
uuid text primary key, uuid text primary key,
@ -51,7 +50,7 @@ create table if not exists go_links {
forwardUrl text not null, forwardUrl text not null,
created_at timestampz default current_timestamp created_at timestampz default current_timestamp
} }
` `;
/* /*
const createAdminPosts = await sql` const createAdminPosts = await sql`
create table if not exists adminPosts ( create table if not exists adminPosts (

View file

@ -6,7 +6,7 @@ services:
ports: ports:
- "127.0.0.1:36694:80" - "127.0.0.1:36694:80"
volumes: volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro - /var/run/docker.sock:/var/run/docker.sock:ro
networks: networks:
- app-network - app-network
newsanalyze-service: newsanalyze-service:
@ -18,7 +18,7 @@ services:
retries: 3 retries: 3
networks: networks:
- app-network - app-network
labels: labels:
- "traefik.enable=true" - "traefik.enable=true"
- "traefik.http.routers.newsanalyze.rule=Host(`news.yuanhau.com`)" - "traefik.http.routers.newsanalyze.rule=Host(`news.yuanhau.com`)"
- "traefik.http.routers.newsanalyze.entrypoints=webinternal" - "traefik.http.routers.newsanalyze.entrypoints=webinternal"

View file

@ -111,6 +111,6 @@ export default defineNuxtConfig({
componentDir: "./components/ui", componentDir: "./components/ui",
}, },
nitro: { nitro: {
preset: "bun" // This is dumb. preset: "bun", // This is dumb.
} },
}); });

View file

@ -2,7 +2,7 @@
const { t } = useI18n(); const { t } = useI18n();
</script> </script>
<template> <template>
<div> <div>
<h1>{{ t("newsOrgs.title") }}</h1> <h1>{{ t("newsOrgs.title") }}</h1>
</div> </div>
</template> </template>

View file

@ -1,9 +1,16 @@
<script setup lang="ts"> <script setup lang="ts">
const route = useRoute();
const slug = route.params.slug;
const {
data: fetchNewsArticle,
pending,
error,
} = await useFetch(`/api/objectstorage/files/${slug}`, {
method: "GET",
});
</script> </script>
<template> <template>
<div class=""> <div class="">
<div class="content"> <div class="content"></div>
</div> </div>
</div> </template>
</template>

3
scraping/README.md Normal file
View file

@ -0,0 +1,3 @@
# Scraping
This file contains the code for scraping the news from websites. And storing the data into the a postgres database.

View file

@ -1,12 +1,7 @@
import scrapy from urllib.request import urlopen
class BlogSpider(scrapy.Spider): url = "https://tw.news.yahoo.com/"
name = 'blogspider'
start_urls = ['https://news.google.com/u/4/home?hl=zh-TW&gl=TW&ceid=TW:zh-Hant&pageId=none']
def parse(self, response): page = urlopen(url)
for title in response.css('.oxy-post-title'):
yield {'title': title.css('::text').get()}
for next_page in response.css('a.next'): page
yield response.follow(next_page, self.parse)

View file

@ -1 +1 @@
scrapy urlopen

View file

@ -1,35 +1,35 @@
import { Groq } from 'groq-sdk'; import { Groq } from "groq-sdk";
import sql from "~/server/components/postgres"; import sql from "~/server/components/postgres";
const groq = new Groq(); const groq = new Groq();
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
const slug = getRouterParam(event, 'slug'); const slug = getRouterParam(event, "slug");
const body = await readBody(event); const body = await readBody(event);
const fetchNewsArticle = await sql` const fetchNewsArticle = await sql`
select * from newArticle select * from newArticle
where slug = ${slug} where slug = ${slug}
`; `;
const chatCompletion = await groq.chat.completions.create({ const chatCompletion = await groq.chat.completions.create({
"messages": [ messages: [
{ {
"role": "user", role: "user",
"content": `${body}` content: `${body}`,
}, },
{ {
"role": "system", role: "system",
"content": `You are a news chat, the following content will be used to chat with the user title: ${fetchNewsArticle.title}\n content: ${fetchNewsArticle.content}` content: `You are a news chat, the following content will be used to chat with the user title: ${fetchNewsArticle.title}\n content: ${fetchNewsArticle.content}`,
} },
], ],
"model": "llama3-70b-8192", model: "llama3-70b-8192",
"temperature": 1, temperature: 1,
"max_completion_tokens": 1024, max_completion_tokens: 1024,
"top_p": 1, top_p: 1,
"stream": true, stream: true,
"stop": null stop: null,
}); });
for await (const chunk of chatCompletion) { for await (const chunk of chatCompletion) {
process.stdout.write(chunk.choices[0]?.delta?.content || ''); process.stdout.write(chunk.choices[0]?.delta?.content || "");
} }
}) });

View file

@ -1,34 +1,34 @@
import { Groq } from 'groq-sdk'; import { Groq } from "groq-sdk";
import sql from "~/server/components/postgres"; import sql from "~/server/components/postgres";
const groq = new Groq(); const groq = new Groq();
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
const slug = getRouterParam(event, 'slug'); const slug = getRouterParam(event, "slug");
const fetchNewsArticle = await sql` const fetchNewsArticle = await sql`
select * from newArticle select * from newArticle
where slug = ${slug} where slug = ${slug}
`; `;
const chatCompletion = await groq.chat.completions.create({ const chatCompletion = await groq.chat.completions.create({
"messages": [ messages: [
{ {
"role": "user", role: "user",
"content": `${fetchNewsArticle.title}\n${fetchNewsArticle.content}` content: `${fetchNewsArticle.title}\n${fetchNewsArticle.content}`,
}, },
{ {
"role": "system", role: "system",
"content": `You are a news summarizer. You will be given a news article and you will summarize it into a short paragraph.` content: `You are a news summarizer. You will be given a news article and you will summarize it into a short paragraph.`,
} },
], ],
"model": "llama3-70b-8192", model: "llama3-70b-8192",
"temperature": 1, temperature: 1,
"max_completion_tokens": 1024, max_completion_tokens: 1024,
"top_p": 1, top_p: 1,
"stream": true, stream: true,
"stop": null stop: null,
}); });
for await (const chunk of chatCompletion) { for await (const chunk of chatCompletion) {
process.stdout.write(chunk.choices[0]?.delta?.content || ''); process.stdout.write(chunk.choices[0]?.delta?.content || "");
} }
}) });

View file

@ -1,28 +1,28 @@
import sql from "~/server/components/postgres"; import sql from "~/server/components/postgres";
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
const slug = getRouterParam(event, 'slug'); const slug = getRouterParam(event, "slug");
// Validate and sanitize the slug
if (!slug || typeof slug !== 'string') {
throw createError({
statusCode: 400,
message: 'Invalid slug parameter'
});
}
const cleanSlug = slug.replace(/[^a-zA-Z0-9-_]/g, '');
try { // Validate and sanitize the slug
const result = await sql` if (!slug || typeof slug !== "string") {
throw createError({
statusCode: 400,
message: "Invalid slug parameter",
});
}
const cleanSlug = slug.replace(/[^a-zA-Z0-9-_]/g, "");
try {
const result = await sql`
select * from articles select * from articles
where slug = ${cleanSlug} where slug = ${cleanSlug}
` `;
return result.rows[0] || null; return result.rows[0] || null;
} catch (error) { } catch (error) {
console.error('Database error:', error); console.error("Database error:", error);
throw createError({ throw createError({
statusCode: 500, statusCode: 500,
message: 'Internal server error' message: "Internal server error",
}); });
} }
}); });

View file

@ -1,7 +1,7 @@
import { SQL } from "bun"; import { SQL } from "bun";
const postgres = new SQL({ const postgres = new SQL({
url: process.env.POSTGRES_URL, url: process.env.POSTGRES_URL,
}) });
export default postgres; export default postgres;

View file

@ -1,24 +1,24 @@
import sql from "~/server/components/postgres"; import sql from "~/server/components/postgres";
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
const slug = getRouterParam(event, 'slug'); const slug = getRouterParam(event, "slug");
if (!slug || typeof slug !== 'string') { if (!slug || typeof slug !== "string") {
throw createError({ throw createError({
statusCode: 400, statusCode: 400,
message: 'Invalid slug parameter' message: "Invalid slug parameter",
}); });
} }
const cleanSlug = slug.replace(/[^a-zA-Z0-9-_]/g, ''); const cleanSlug = slug.replace(/[^a-zA-Z0-9-_]/g, "");
try { try {
const result = await sql` const result = await sql`
select * from go_links select * from go_links
where slug = ${cleanSlug} where slug = ${cleanSlug}
` `;
return result.rows[0] || null; return result.rows[0] || null;
} catch (error) { } catch (error) {
console.error('Database error:', error); console.error("Database error:", error);
throw createError({ throw createError({
statusCode: 500, statusCode: 500,
message: 'Internal server error' message: "Internal server error",
}); });
} }
}) });