All files / src/apps/user/pages/knowledge EditKnowledge.tsx

47.05% Statements 72/153
45.02% Branches 77/171
39.02% Functions 16/41
52.27% Lines 69/132

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709                                                                            2x                                                                                                                                 3x 2x         1x 1x                                                 1x 1x 1x     1x       1x                                                         2x     2x   2x         14x                                               2x       3x                                                           2x                                                                           2x                                                                                                           1x 1x 1x   1x 1x         1x         1x     1x             2x 18x   18x 18x   18x     18x 18x 7x 7x   18x 18x           18x     6x 6x           18x 13x 3x 13x 13x 6x   13x               18x 1x 1x 1x         1x 1x 1x 1x                 1x       1x       18x 1x 17x           17x 2x                 15x                           44x                                                                                                                     20x 20x 20x                                                                                                         4x 1x                                                                                                                                                                                                                                                                  
import React, { useEffect, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import PrefillNote from "./recommendations/PrefillNote";
import { describePrefill, sourcePrefill } from "./recommendations/prefill";
import { errorDetail } from "@/util/apiError";
import WebSourceConfigForm from "./WebSourceConfigForm";
import {
  WebSourceForm,
  validateWebForm,
  webConfigFromForm,
  webFormFromConfig,
} from "./webSource";
import { useQuery } from "@tanstack/react-query";
import { QUERY_KEYS } from "@/services/query_keys";
import SubPage from "@/components/page/SubPage/SubPage";
import { APP_ROUTES } from "@/routes/const";
import { useApiHandler } from "@/services/useApiHandler";
import { Knowledge } from "@/objects/Knowledge";
import {
  BookCopy,
  Database,
  Globe,
  FileStack,
  Network,
  Plug,
  Check,
  AlertCircle,
  Loader2,
  Info,
  Settings,
  Link as LinkIcon,
  FileText,
  Server,
} from "lucide-react";
import { SectionCard, Skeleton, useResourceId } from "@/components/detail";
 
// ─── Source types ─────────────────────────────────────────────────────────────
 
const SOURCE_TYPES = [
  {
    value: "file",
    label: "File Upload",
    description: "Upload documents from your device.",
    icon: FileStack,
  },
  {
    value: "web",
    label: "Web / URL",
    description: "Crawl web pages and keep a snapshot each time they change.",
    icon: Globe,
  },
  {
    value: "db",
    label: "Database",
    description: "Query records from a database.",
    icon: Database,
  },
  {
    value: "api",
    label: "API",
    description: "Pull data from a REST API.",
    icon: Plug,
  },
  {
    value: "graph",
    label: "Knowledge Graph",
    description: "Interactive entity-relationship graph.",
    icon: Network,
  },
] as const;
 
type SourceType = (typeof SOURCE_TYPES)[number]["value"];
 
// ─── Source config shapes ─────────────────────────────────────────────────────
 
interface FileConfig {
  paths: string;
  extensions: string;
}
interface DbConfig {
  connection_string: string;
  query: string;
}
interface ApiConfig {
  endpoint: string;
  auth_header: string;
  auth_value: string;
}
interface GraphConfig {
  node_count: number;
  edge_count: number;
}
type SourceConfig =
  | FileConfig
  | WebSourceForm
  | DbConfig
  | ApiConfig
  | GraphConfig;
 
function configToForm(
  type: string,
  config: Record<string, unknown>,
): SourceConfig {
  if (type === "file") {
    return {
      paths: (config.paths as string[] | undefined)?.join("\n") ?? "",
      extensions: (config.extensions as string[] | undefined)?.join(", ") ?? "",
    };
  }
  Eif (type === "web") {
    return webFormFromConfig(config);
  }
  if (type === "db") {
    return {
      connection_string: (config.connection_string as string | undefined) ?? "",
      query: (config.query as string | undefined) ?? "",
    };
  }
  if (type === "graph") {
    return {
      node_count: (config.node_count as number | undefined) ?? 0,
      edge_count: (config.edge_count as number | undefined) ?? 0,
    };
  }
  return {
    endpoint: (config.endpoint as string | undefined) ?? "",
    auth_header: (config.auth_header as string | undefined) ?? "",
    auth_value: "",
  };
}
 
function buildSourceConfig(
  type: SourceType,
  config: SourceConfig,
): Record<string, unknown> {
  Eif (type === "file") {
    const c = config as FileConfig;
    return {
      paths: c.paths
        .split("\n")
        .map((s) => s.trim())
        .filter(Boolean),
      extensions: c.extensions
        .split(",")
        .map((s) => s.trim().toLowerCase())
        .filter(Boolean),
    };
  }
  if (type === "web") {
    return { ...webConfigFromForm(config as WebSourceForm) };
  }
  if (type === "db") {
    const c = config as DbConfig;
    return {
      connection_string: c.connection_string.trim(),
      query: c.query.trim(),
    };
  }
  if (type === "graph") {
    const c = config as GraphConfig;
    return { node_count: c.node_count, edge_count: c.edge_count };
  }
  const c = config as ApiConfig;
  return {
    endpoint: c.endpoint.trim(),
    auth_header: c.auth_header.trim() || undefined,
    auth_value: c.auth_value.trim() || undefined,
  };
}
 
// ─── Primitives ───────────────────────────────────────────────────────────────
 
const inputBase =
  "w-full px-3 py-2 text-sm rounded-lg border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-300 dark:focus:ring-gray-500 transition-colors";
 
const errorBase =
  "w-full px-3 py-2 text-sm rounded-lg border border-red-300 dark:border-red-700 bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-red-200 dark:focus:ring-red-900 transition-colors";
 
const FieldLabel: React.FC<{
  label: string;
  description?: string;
  required?: boolean;
}> = ({ label, description, required }) => (
  <div className="mb-1.5">
    <div className="text-sm font-medium text-gray-700 dark:text-gray-300">
      {label}
      {required && <span className="ml-0.5 text-red-500">*</span>}
    </div>
    {description && (
      <p className="text-xs text-gray-400 dark:text-gray-500 mt-0.5">
        {description}
      </p>
    )}
  </div>
);
 
function configIcon(key: string): React.ElementType {
  if (key.includes("url") || key.includes("endpoint") || key.includes("host"))
    return LinkIcon;
  if (key.includes("path")) return FileText;
  if (key.includes("auth") || key.includes("header")) return Settings;
  if (key.includes("connect") || key.includes("db")) return Server;
  return Settings;
}
 
// ─── Source config forms ──────────────────────────────────────────────────────
 
const FileConfigForm: React.FC<{
  config: FileConfig;
  onChange: (c: FileConfig) => void;
}> = ({ config, onChange }) => (
  <>
    <div>
      <FieldLabel
        label="File Paths"
        description="Optional. One path per line. Documents themselves are uploaded or imported on the source's page."
      />
      <textarea
        value={config.paths}
        onChange={(e) => onChange({ ...config, paths: e.target.value })}
        placeholder={"e.g.\n/data/reports/\ns3://my-bucket/docs/"}
        rows={4}
        className={inputBase + " resize-none font-mono text-xs"}
      />
    </div>
    <div>
      <FieldLabel
        label="Allowed Extensions"
        description="Comma-separated. Leave empty to allow all."
      />
      <input
        type="text"
        value={config.extensions}
        onChange={(e) => onChange({ ...config, extensions: e.target.value })}
        placeholder="e.g. .pdf, .txt, .docx"
        className={inputBase}
      />
    </div>
  </>
);
 
const DbConfigForm: React.FC<{
  config: DbConfig;
  onChange: (c: DbConfig) => void;
}> = ({ config, onChange }) => (
  <>
    <div>
      <FieldLabel
        label="Connection String"
        description="Full database connection URI."
        required
      />
      <input
        type="text"
        value={config.connection_string}
        onChange={(e) =>
          onChange({ ...config, connection_string: e.target.value })
        }
        placeholder="e.g. postgresql://user:pass@host/db"
        className={inputBase + " font-mono text-xs"}
      />
    </div>
    <div>
      <FieldLabel
        label="Query"
        description="SQL query or collection name."
        required
      />
      <textarea
        value={config.query}
        onChange={(e) => onChange({ ...config, query: e.target.value })}
        placeholder="SELECT id, content FROM documents"
        rows={4}
        className={inputBase + " resize-none font-mono text-xs"}
      />
    </div>
  </>
);
 
const ApiConfigForm: React.FC<{
  config: ApiConfig;
  onChange: (c: ApiConfig) => void;
}> = ({ config, onChange }) => (
  <>
    <div>
      <FieldLabel
        label="Endpoint URL"
        description="REST endpoint returning the data to index."
        required
      />
      <input
        type="text"
        value={config.endpoint}
        onChange={(e) => onChange({ ...config, endpoint: e.target.value })}
        placeholder="https://api.example.com/v1/documents"
        className={inputBase + " font-mono text-xs"}
      />
    </div>
    <div className="grid grid-cols-2 gap-4">
      <div>
        <FieldLabel label="Auth Header" description="e.g. Authorization" />
        <input
          type="text"
          value={config.auth_header}
          onChange={(e) => onChange({ ...config, auth_header: e.target.value })}
          placeholder="Authorization"
          className={inputBase}
        />
      </div>
      <div>
        <FieldLabel label="Auth Value" description="e.g. Bearer <token>" />
        <input
          type="password"
          value={config.auth_value}
          onChange={(e) => onChange({ ...config, auth_value: e.target.value })}
          placeholder="Bearer ..."
          className={inputBase}
        />
      </div>
    </div>
  </>
);
 
// ─── Validation ───────────────────────────────────────────────────────────────
 
interface EditFormState {
  name: string;
  description: string;
  source_type: SourceType;
  config: SourceConfig;
}
 
function validate(data: EditFormState): string | null {
  Iif (!data.name.trim()) return "Name is required.";
  Iif (data.name.trim().length < 2) return "Name must be at least 2 characters.";
  Iif (data.name.trim().length > 50)
    return "Name must be 50 characters or fewer.";
  Iif (!data.description.trim()) return "Description is required.";
  Iif (data.source_type === "web") {
    const web = validateWebForm(data.config as WebSourceForm);
    const first = Object.values(web)[0];
    if (first) return first;
  }
  Iif (data.source_type === "db") {
    const c = data.config as DbConfig;
    if (!c.connection_string.trim()) return "Connection string is required.";
    if (!c.query.trim()) return "Query is required.";
  }
  Iif (data.source_type === "api" && !(data.config as ApiConfig).endpoint.trim())
    return "Endpoint URL is required.";
  // graph type has no required config fields
  return null;
}
 
// ─── Loading skeleton ─────────────────────────────────────────────────────────
 
// ─── EditKnowledge ────────────────────────────────────────────────────────────
 
const EditKnowledge: React.FC = () => {
  const { getApiHandler } = useApiHandler();
  // Decoded once, safely: a malformed id reads as none, never a throw.
  const knowledgeId = useResourceId("knowledgeId");
  const navigate = useNavigate();
 
  const [formState, setFormState] = useState<EditFormState | null>(null);
  // A recommendation's "Change its settings" sets them over the stored ones,
  // for a website source only, and says so above the form.
  const [params] = useSearchParams();
  const [prefill] = useState(() => {
    const read = sourcePrefill(params);
    return { ...read, web: { refresh: read.web.refresh, max_age_days: read.web.max_age_days } };
  });
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
 
  const {
    data: knowledge,
    error: fetchError,
    isLoading,
  } = useQuery({
    queryKey: [QUERY_KEYS.GET.KNOWLEDGE_BY_ID, knowledgeId, "edit"],
    queryFn: async () => {
      Iif (!knowledgeId) return null;
      return getApiHandler().knowledge_router.id(knowledgeId);
    },
    enabled: !!knowledgeId,
  });
 
  // Initialise form once data loads
  useEffect(() => {
    if (!knowledge) return;
    const type = (knowledge.source_type ?? "file") as SourceType;
    const config = configToForm(type, knowledge.source_config ?? {});
    const suggested = Object.fromEntries(
      Object.entries(prefill.web).filter(([, v]) => v !== undefined),
    );
    setFormState({
      name: knowledge.name ?? "",
      description: knowledge.description ?? "",
      source_type: type,
      config: type === "web" ? { ...(config as WebSourceForm), ...suggested } : config,
    });
  }, [knowledge, prefill]);
 
  const handleSubmit = async () => {
    Iif (!formState || !knowledgeId) return;
    const err = validate(formState);
    Iif (err) {
      setError(err);
      return;
    }
 
    setSubmitting(true);
    setError(null);
    try {
      await getApiHandler().knowledge_router.edit(knowledgeId, {
        name: formState.name.trim(),
        description: formState.description.trim(),
        source_type: formState.source_type,
        source_config: buildSourceConfig(
          formState.source_type,
          formState.config,
        ),
      } as unknown as Knowledge);
      navigate(APP_ROUTES.USER.knowledge);
    } catch (e: unknown) {
      setError(errorDetail(e, "Something went wrong. Please try again."));
    } finally {
      setSubmitting(false);
    }
  };
 
  if (!knowledgeId)
    return <div className="p-4 text-red-500">Invalid knowledge base ID.</div>;
  Iif (fetchError)
    return (
      <div className="p-4 text-red-500">Error: {fetchError.toString()}</div>
    );
  // Not the viewer's to change here (a built-in, a reader, or what a project
  // inherits): svc-core would refuse the save, so no form is offered.
  if (knowledge?.can_change === false)
    return (
      <SubPage title={`Edit "${knowledge.name}"`}>
        <p role="note" className="text-sm text-gray-500 dark:text-gray-400">
          You can&rsquo;t change this source here. It belongs to another
          workspace, or your access in this one is read only.
        </p>
      </SubPage>
    );
 
  return (
    <SubPage
      title={
        isLoading ? "Edit Knowledge Base" : `Edit "${knowledge?.name ?? ""}"`
      }
    >
      <div className="max-w-2xl space-y-4">
        {formState?.source_type === "web" && (
          <PrefillNote changes={describePrefill(prefill)} />
        )}
        {isLoading || !formState ? (
          <div className="space-y-4">
            <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 shadow-sm p-5 space-y-4">
              {Array.from({ length: 4 }).map((_, i) => (
                <div key={i} className="space-y-1.5">
                  <Skeleton className="h-3.5 w-24" />
                  <Skeleton className="h-9 w-full" />
                </div>
              ))}
            </div>
          </div>
        ) : (
          <>
            {/* Basic details */}
            <SectionCard variant="form" icon={BookCopy} title="Basic Details">
              <div>
                <FieldLabel
                  label="Name"
                  description="A short, descriptive name."
                  required
                />
                <input
                  type="text"
                  value={formState.name}
                  onChange={(e) => {
                    setFormState((s) => s && { ...s, name: e.target.value });
                    setError(null);
                  }}
                  placeholder="e.g. Medical Reports"
                  className={
                    error && !formState.name.trim() ? errorBase : inputBase
                  }
                />
              </div>
              <div>
                <FieldLabel
                  label="Description"
                  description="Describe the contents and intended use."
                  required
                />
                <textarea
                  value={formState.description}
                  onChange={(e) => {
                    setFormState(
                      (s) => s && { ...s, description: e.target.value },
                    );
                    setError(null);
                  }}
                  placeholder="e.g. Historical patient records for medical recall."
                  rows={3}
                  className={
                    (error && !formState.description.trim()
                      ? errorBase
                      : inputBase) + " resize-none"
                  }
                />
              </div>
            </SectionCard>
 
            {/* Source type */}
            <SectionCard variant="form" icon={Database} title="Source Type">
              <div className="grid grid-cols-2 gap-2">
                {SOURCE_TYPES.map((st) => {
                  const Icon = st.icon;
                  const active = formState.source_type === st.value;
                  return (
                    <button
                      key={st.value}
                      type="button"
                      onClick={() => {
                        const newType = st.value as SourceType;
                        setFormState(
                          (s) =>
                            s && {
                              ...s,
                              source_type: newType,
                              config: configToForm(
                                newType,
                                knowledge?.source_type === newType
                                  ? (knowledge.source_config ?? {})
                                  : {},
                              ),
                            },
                        );
                        setError(null);
                      }}
                      className={`flex items-start gap-3 p-3 rounded-lg border text-left transition-colors ${
                        active
                          ? "border-gray-900 dark:border-gray-100 bg-gray-50 dark:bg-gray-700"
                          : "border-gray-200 dark:border-gray-600 hover:border-gray-300 dark:hover:border-gray-500"
                      }`}
                    >
                      <div
                        className={`p-1.5 rounded-md shrink-0 ${active ? "bg-gray-900 dark:bg-gray-100" : "bg-gray-100 dark:bg-gray-700"}`}
                      >
                        <Icon
                          className={`size-4 ${active ? "text-white dark:text-gray-900" : "text-gray-500 dark:text-gray-400"}`}
                        />
                      </div>
                      <div>
                        <div
                          className={`text-sm font-medium ${active ? "text-gray-900 dark:text-gray-100" : "text-gray-700 dark:text-gray-300"}`}
                        >
                          {st.label}
                        </div>
                        <div className="text-xs text-gray-400 dark:text-gray-500 mt-0.5 leading-relaxed">
                          {st.description}
                        </div>
                      </div>
                    </button>
                  );
                })}
              </div>
            </SectionCard>
 
            {/* Source configuration */}
            <SectionCard variant="form"
              icon={(() => {
                if (formState.source_type === "file") return FileStack;
                Eif (formState.source_type === "web") return Globe;
                if (formState.source_type === "db") return Database;
                if (formState.source_type === "graph") return Network;
                return Plug;
              })()}
              title="Source Configuration"
            >
              {formState.source_type === "file" && (
                <FileConfigForm
                  config={formState.config as FileConfig}
                  onChange={(config) => {
                    setFormState((s) => s && { ...s, config });
                    setError(null);
                  }}
                />
              )}
              {formState.source_type === "web" && (
                <WebSourceConfigForm
                  config={formState.config as WebSourceForm}
                  onChange={(config) => {
                    setFormState((s) => s && { ...s, config });
                    setError(null);
                  }}
                  errors={{}}
                />
              )}
              {formState.source_type === "db" && (
                <DbConfigForm
                  config={formState.config as DbConfig}
                  onChange={(config) => {
                    setFormState((s) => s && { ...s, config });
                    setError(null);
                  }}
                />
              )}
              {formState.source_type === "api" && (
                <ApiConfigForm
                  config={formState.config as ApiConfig}
                  onChange={(config) => {
                    setFormState((s) => s && { ...s, config });
                    setError(null);
                  }}
                />
              )}
              {formState.source_type === "graph" && (
                <div className="space-y-3">
                  <div className="grid grid-cols-2 gap-3">
                    <div className="rounded-lg border border-gray-200 dark:border-gray-700 px-4 py-3">
                      <p className="text-xs text-gray-400 dark:text-gray-500">
                        Entities
                      </p>
                      <p className="text-2xl font-semibold text-gray-800 dark:text-gray-200 mt-0.5">
                        {(formState.config as GraphConfig).node_count}
                      </p>
                    </div>
                    <div className="rounded-lg border border-gray-200 dark:border-gray-700 px-4 py-3">
                      <p className="text-xs text-gray-400 dark:text-gray-500">
                        Relationships
                      </p>
                      <p className="text-2xl font-semibold text-gray-800 dark:text-gray-200 mt-0.5">
                        {(formState.config as GraphConfig).edge_count}
                      </p>
                    </div>
                  </div>
                  <div className="rounded-lg bg-teal-50 dark:bg-teal-950/30 border border-teal-200 dark:border-teal-800 px-4 py-3 flex items-start gap-2">
                    <Network className="size-3.5 text-teal-600 dark:text-teal-400 shrink-0 mt-0.5" />
                    <p className="text-xs text-teal-600 dark:text-teal-400">
                      Graph structure is edited in the knowledge base viewer
                      using the interactive canvas.
                    </p>
                  </div>
                </div>
              )}
 
              {formState.source_type !== "graph" && (
                <div className="rounded-lg bg-blue-50 dark:bg-blue-950/30 border border-blue-200 dark:border-blue-800 px-4 py-3 flex items-start gap-2">
                  <Info className="size-3.5 text-blue-600 dark:text-blue-400 shrink-0 mt-0.5" />
                  <p className="text-xs text-blue-600 dark:text-blue-400">
                    Source configuration is stored securely. Connection
                    credentials are encrypted at rest.
                  </p>
                </div>
              )}
            </SectionCard>
 
            {/* Error banner */}
            {error && (
              <div className="flex items-center gap-2 px-4 py-3 rounded-lg bg-red-50 dark:bg-red-950/40 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-300 text-sm">
                <AlertCircle className="size-4 shrink-0" />
                {error}
              </div>
            )}
 
            {/* Actions */}
            <div className="flex justify-end gap-3">
              <button
                type="button"
                onClick={() => navigate(-1)}
                className="px-4 py-2 rounded-lg text-sm font-medium text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
              >
                Cancel
              </button>
              <button
                type="button"
                onClick={handleSubmit}
                disabled={submitting}
                className="flex items-center gap-1.5 px-4 py-2 rounded-lg bg-gray-900 dark:bg-white text-white dark:text-gray-900 text-sm font-medium hover:opacity-80 disabled:opacity-50 transition-opacity"
              >
                {submitting ? (
                  <>
                    <Loader2 className="size-4 animate-spin" />
                    Saving…
                  </>
                ) : (
                  <>
                    <Check className="size-4" />
                    Save Changes
                  </>
                )}
              </button>
            </div>
          </>
        )}
      </div>
    </SubPage>
  );
};
 
export default EditKnowledge;