Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 12 additions & 14 deletions atlas/app/admin/projects/[id]/ProjectEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1041,7 +1041,7 @@ export default function ProjectEditor({
alignItems: "center",
}}
>
<span>Auto-fill from latest semester&apos;s PD doc</span>
<span>Fill from latest semester&apos;s PD doc</span>
{latestPd.trim() && urlOk(latestPd) && (
<a
href={latestPd.trim()}
Expand All @@ -1058,19 +1058,17 @@ export default function ProjectEditor({
accent="#0a8576"
initialUrl={latestPd}
onUrlChange={setLatestPd}
onFetched={(blurb, _full, tech) =>
setForm((f) => {
if (!f) return f;
const next = { ...f, blurb };
if (tech) {
if (tech.raw) next.techNote = tech.raw;
// Fill tags only when none yet — never clobber curated tech.
if (tech.tags.length && f.tech.length === 0)
next.tech = tech.tags;
}
return next;
})
}
fill={{
current: {
blurb: form.blurb,
tech: form.tech,
techNote: form.techNote,
repoUrl: form.repoUrl,
},
// Sets the form field only; the admin still saves normally.
onUse: (field, value) =>
setForm((f) => (f ? { ...f, [field]: value } : f)),
}}
/>
</div>
{!urlOk(latestPd) && (
Expand Down
122 changes: 118 additions & 4 deletions atlas/components/PdBlurbFetch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import { useCallback, useState } from "react";
import { extractPdBlurb } from "@/lib/gdocs";
import { parseTechStack, type TechParse } from "@/lib/tech";
import { docIdFromUrl, exportDoc } from "@/lib/google-doc";
import { parsePd } from "@/lib/pd-check";
import { pdFillSuggestions, type PdFillField, type PdFillValues } from "@/lib/pd-fill";

// "Red" = high red, low green/blue. Catches #ff0000, #cc0000, #e60000, Google
// red #ea4335, and rgb() forms. Leaves blue links + black body untouched.
Expand Down Expand Up @@ -100,14 +102,22 @@ type Status =

export default function PdBlurbFetch({
onFetched,
fill,
initialUrl = "",
onUrlChange,
accent = "#0fa392",
}: {
// Called with the extracted blurb (may be "" if no heading found), the full
// doc text, and the parsed Tech Stack cell — so the parent can fill the
// textarea + tech tags for the admin to confirm.
onFetched: (blurb: string, fullText: string, tech?: TechParse) => void;
onFetched?: (blurb: string, fullText: string, tech?: TechParse) => void;
// "Fill from PD" mode: instead of filling anything, show per-field
// suggestions (current → from PD) against `current`, each with its own
// "Use this" that calls onUse. Nothing is saved — the admin saves normally.
fill?: {
current: PdFillValues;
onUse: <K extends PdFillField>(field: K, value: PdFillValues[K]) => void;
};
// Seed the input with the project's stored PD doc link (so the admin can
// re-pull in one click), and lift any edits back so the link is saved.
initialUrl?: string;
Expand All @@ -117,6 +127,8 @@ export default function PdBlurbFetch({
const clientId = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID;
const [url, setUrl] = useState(initialUrl);
const [status, setStatus] = useState<Status>({ kind: "idle" });
const [pd, setPd] = useState<PdFillValues | null>(null);
const fillMode = !!fill;
const fetchDoc = useCallback(async () => {
const id = docIdFromUrl(url);
if (!id) {
Expand All @@ -127,7 +139,25 @@ export default function PdBlurbFetch({
return;
}
setStatus({ kind: "loading" });
setPd(null);
try {
if (fillMode) {
// One token, both exports at once: HTML for the red-note-aware blurb,
// plain text for parsePd (what the PD importer is tuned on).
const [html, text] = await Promise.all([
exportDoc(clientId as string, id, "text/html"),
exportDoc(clientId as string, id, "text/plain"),
]);
const f = parsePd(text);
// No full-text fallback here: only suggest a description the PD has.
const blurb =
extractPdBlurb(htmlToBlurbText(html, true)) ||
extractPdBlurb(htmlToBlurbText(html, false)) ||
f.blurb;
setPd({ blurb, tech: f.tech, techNote: f.techNote, repoUrl: f.repoUrl });
setStatus({ kind: "idle" });
return;
}
// Export as HTML (not text/plain) so we can SEE color and drop red
// editorial notes. Same drive.readonly consent.
const html = await exportDoc(clientId as string, id, "text/html");
Expand All @@ -141,7 +171,7 @@ export default function PdBlurbFetch({
if (!blurb) blurb = extractPdBlurb(full);
const text = stripped || full;
const tech = parseTechStack(techCellFromHtml(html));
onFetched(blurb || text.trim(), text, tech);
onFetched?.(blurb || text.trim(), text, tech);
setStatus(
blurb
? { kind: "ok", msg: "Fetched — review and edit the description below, then save." }
Expand All @@ -156,7 +186,7 @@ export default function PdBlurbFetch({
msg: e instanceof Error ? e.message : "Something went wrong fetching the doc.",
});
}
}, [url, clientId, onFetched]);
}, [url, clientId, onFetched, fillMode]);

if (!clientId) {
return (
Expand Down Expand Up @@ -216,7 +246,7 @@ export default function PdBlurbFetch({
fontWeight: 600,
}}
>
{status.kind === "loading" ? "Fetching…" : "Fetch blurb"}
{status.kind === "loading" ? "Fetching…" : fillMode ? "Fill from PD" : "Fetch blurb"}
</button>
</div>
{status.kind !== "idle" && status.kind !== "loading" && (
Expand All @@ -225,6 +255,90 @@ export default function PdBlurbFetch({
{status.msg}
</div>
)}
{fill && pd && <PdSuggestions pd={pd} fill={fill} accent={accent} />}
</div>
);
}

const show = (v: string | string[]) =>
(Array.isArray(v) ? v.join(", ") : v).trim() || "(empty)";

function PdSuggestions({
pd,
fill,
accent,
}: {
pd: PdFillValues;
fill: NonNullable<Parameters<typeof PdBlurbFetch>[0]["fill"]>;
accent: string;
}) {
const list = pdFillSuggestions(fill.current, pd);
if (!list.length)
return (
<div style={{ fontSize: 12.5, color: "#a86700", marginTop: 7 }}>
⚠ Opened the doc but found no description, tech stack or GitHub repo to suggest.
</div>
);
const box: React.CSSProperties = {
fontSize: 12.5,
lineHeight: 1.45,
whiteSpace: "pre-line",
maxHeight: 120,
overflow: "auto",
padding: "6px 8px",
borderRadius: 6,
background: "#fff",
border: "1px solid var(--line, #e4e4e4)",
};
return (
<div style={{ display: "grid", gap: 10, marginTop: 10 }}>
{list.map((s) => (
<div key={s.field} style={{ borderLeft: `2px solid ${s.held.length ? "#a86700" : accent}`, paddingLeft: 10 }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8, marginBottom: 5 }}>
<span style={{ fontFamily: "var(--mono)", fontSize: 10.5, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ink-4)" }}>
{s.label}
</span>
{s.same ? (
<span style={{ fontSize: 12, color: "#9a9a9a" }}>✓ Already matches</span>
) : s.held.length ? null : (
<button
type="button"
onClick={() => fill.onUse(s.field, s.value)}
style={{
padding: "3px 10px",
border: "none",
borderRadius: 6,
cursor: "pointer",
background: `color-mix(in oklab, ${accent} 88%, #000)`,
color: "#fff",
fontFamily: "var(--mono)",
fontSize: 11.5,
fontWeight: 600,
}}
>
Use this
</button>
)}
</div>
{!s.same && (
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
<div>
<div style={{ fontSize: 11, color: "#9a9a9a", marginBottom: 3 }}>Current</div>
<div style={{ ...box, color: "#9a9a9a" }}>{show(s.current)}</div>
</div>
<div>
<div style={{ fontSize: 11, color: "#9a9a9a", marginBottom: 3 }}>From PD</div>
<div style={box}>{show(s.value)}</div>
</div>
</div>
)}
{s.held.length > 0 && (
<div style={{ fontSize: 12.5, color: "#a86700", marginTop: 5 }}>
⚠ Not offered — fix the PD first: {s.held.join(" ")}
</div>
)}
</div>
))}
</div>
);
}
46 changes: 46 additions & 0 deletions atlas/lib/pd-fill.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { describe, it, expect } from "vitest";
import { pdFillSuggestions, type PdFillValues } from "./pd-fill";

const EMPTY: PdFillValues = { blurb: "", tech: [], techNote: "", repoUrl: "" };
const PD: PdFillValues = {
blurb: "Acme wants a public data portal so residents can explore neighbourhood statistics.",
tech: ["React", "PostgreSQL"],
techNote: "• React\n• PostgreSQL",
repoUrl: "https://github.com/BU-Spark/acme-portal",
};

describe("pdFillSuggestions", () => {
it("suggests every field the PD has, with current → PD", () => {
const s = pdFillSuggestions({ ...EMPTY, blurb: "old" }, PD);
expect(s.map((x) => x.field)).toEqual(["blurb", "tech", "techNote", "repoUrl"]);
expect(s[0]).toMatchObject({ current: "old", value: PD.blurb, held: [], same: false });
});

it("skips fields the PD has no value for", () => {
expect(pdFillSuggestions(EMPTY, EMPTY)).toEqual([]);
expect(pdFillSuggestions(EMPTY, { ...EMPTY, techNote: "• Python" }).map((x) => x.field)).toEqual(["techNote"]);
});

it("offers a repo only when it is an http(s) GitHub repo URL", () => {
const repo = (u: string) => pdFillSuggestions(EMPTY, { ...EMPTY, repoUrl: u });
expect(repo("https://gitlab.com/a/b")).toEqual([]);
expect(repo("ftp://github.com/a/b")).toEqual([]);
expect(repo("https://github.com/a")).toEqual([]);
expect(repo("http://github.com/a/b")).toHaveLength(1);
});

it("carries syncHolds reasons: blurb holds on the blurb, tech holds on note and tags", () => {
const s = pdFillSuggestions(EMPTY, {
...PD,
blurb: "We build a tool. Email jane@example.org with questions.",
techNote: "DATABASE_URL=postgresql://u:secret@db.proxy.example.net:5432/x",
});
const by = Object.fromEntries(s.map((x) => [x.field, x.held.length]));
expect(by).toEqual({ blurb: 1, tech: 1, techNote: 1, repoUrl: 0 });
});

it("flags values the form already holds", () => {
const s = pdFillSuggestions({ ...PD, tech: ["React", "PostgreSQL"] }, PD);
expect(s.every((x) => x.same)).toBe(true);
});
});
66 changes: 66 additions & 0 deletions atlas/lib/pd-fill.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// "Fill from PD" suggestions for the project editor. PURE: takes what the PD
// parsed to and what the form holds now, returns one suggestion per field the
// PD actually has a value for. The editor shows each as current → from PD with
// its own "Use this"; nothing is applied or saved here.
import { syncHolds } from "./pd-check";

export type PdFillField = "blurb" | "tech" | "techNote" | "repoUrl";

export interface PdFillValues {
blurb: string;
tech: string[];
techNote: string;
repoUrl: string;
}

export interface PdFillSuggestion<K extends PdFillField = PdFillField> {
field: K;
label: string;
current: PdFillValues[K];
value: PdFillValues[K];
/** syncHolds reasons. Non-empty = show as a warning, offer no "Use". */
held: string[];
/** The form already holds this value. */
same: boolean;
}

const GITHUB = /^https?:\/\/(?:www\.)?github\.com\/[\w.-]+\/[\w.-]+\/?$/i;
const LABELS: Record<PdFillField, string> = {
blurb: "Description",
tech: "Tech tags",
techNote: "Tech note",
repoUrl: "Repo URL",
};

const eq = (a: string | string[], b: string | string[]) =>
Array.isArray(a) && Array.isArray(b)
? a.length === b.length && a.every((x, i) => x === b[i])
: String(a).trim() === String(b).trim();

export function pdFillSuggestions(current: PdFillValues, pd: PdFillValues): PdFillSuggestion[] {
const holds = syncHolds(pd.blurb.trim(), pd.techNote.trim());
const has: Record<PdFillField, boolean> = {
blurb: !!pd.blurb.trim(),
// Tags only as parsePd/parseTechStack extracted them — no extra guessing.
tech: pd.tech.length > 0,
techNote: !!pd.techNote.trim(),
repoUrl: GITHUB.test(pd.repoUrl.trim()),
};
const held: Record<PdFillField, string[]> = {
blurb: holds.blurb,
// Tags come from the same cell as the note, so a held note holds them too.
tech: holds.tech,
techNote: holds.tech,
repoUrl: [],
};
return (Object.keys(LABELS) as PdFillField[])
.filter((k) => has[k])
.map((k) => ({
field: k,
label: LABELS[k],
current: current[k],
value: k === "repoUrl" ? pd.repoUrl.trim() : pd[k],
held: held[k],
same: eq(current[k], pd[k]),
}));
}
Loading