aboutsummaryrefslogtreecommitdiffstats
path: root/apps/mobile/app/dashboard/bookmarks/new.tsx
blob: d24c15978d56f5f82a84a68cfd1a7c0d7f2b7f67 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import React, { useState } from "react";
import { Text, View } from "react-native";
import { router } from "expo-router";
import { Button } from "@/components/ui/Button";
import CustomSafeAreaView from "@/components/ui/CustomSafeAreaView";
import { Input } from "@/components/ui/Input";
import { useToast } from "@/components/ui/Toast";

import { useCreateBookmark } from "@karakeep/shared-react/hooks/bookmarks";
import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";

const NoteEditorPage = () => {
  const dismiss = () => {
    router.back();
  };

  const [text, setText] = useState("");
  const [error, setError] = useState<string | undefined>();
  const { toast } = useToast();

  const { mutate: createBookmark } = useCreateBookmark({
    onSuccess: (resp) => {
      if (resp.alreadyExists) {
        toast({
          message: "Bookmark already exists",
        });
      }
      setText("");
      dismiss();
    },
    onError: (e) => {
      let message;
      if (e.data?.zodError) {
        const zodError = e.data.zodError;
        message = JSON.stringify(zodError);
      } else {
        message = `Something went wrong: ${e.message}`;
      }
      setError(message);
    },
  });

  const onSubmit = () => {
    const data = text.trim();
    try {
      const url = new URL(data);
      if (url.protocol != "http:" && url.protocol != "https:") {
        throw new Error(`Unsupported URL protocol: ${url.protocol}`);
      }
      createBookmark({ type: BookmarkTypes.LINK, url: data });
    } catch {
      createBookmark({ type: BookmarkTypes.TEXT, text: data });
    }
  };

  return (
    <CustomSafeAreaView>
      <View className="gap-2 px-4">
        {error && (
          <Text className="w-full text-center text-red-500">{error}</Text>
        )}
        <Input
          onChangeText={setText}
          multiline
          placeholder="What's on your mind?"
          autoFocus
          autoCapitalize={"none"}
          textAlignVertical="top"
        />
        <Button onPress={onSubmit} label="Save" />
      </View>
    </CustomSafeAreaView>
  );
};

export default NoteEditorPage;