Files
community-rule/lib/create/copiedRuleDocument.ts
T

60 lines
1.7 KiB
TypeScript

import type { CommunityRuleSection } from "../../app/components/type/CommunityRule/CommunityRule.types";
import { parsePublishedDocumentForCommunityRuleDisplay } from "./publishedDocumentToDisplaySections";
const IDENTITY_KEYS = [
"communityAvatarUrl",
"communityAvatarFileName",
"communityContext",
"communityLocation",
"communitySaveEmail",
"title",
] as const;
export type CopiedNameHit = {
categoryName: string;
entryTitle: string;
};
/** Copy cards and text; drop name, description, photo, and save-email. */
export function stripCopiedRuleDocument(
document: unknown,
): Record<string, unknown> {
if (!document || typeof document !== "object" || Array.isArray(document)) {
return {};
}
const copy = structuredClone(document) as Record<string, unknown>;
for (const key of IDENTITY_KEYS) {
delete copy[key];
}
return copy;
}
function entryHaystack(entry: CommunityRuleSection["entries"][number]): string {
const blockText = (entry.blocks ?? [])
.map((block) => `${block.label} ${block.body}`)
.join("\n");
return `${entry.title}\n${entry.body}\n${blockText}`;
}
/** First line that still names the original community after a copy. */
export function findCopiedNameHit(
document: unknown,
originalName: string,
): CopiedNameHit | null {
const name = originalName.trim();
if (name.length < 2) return null;
const needle = name.toLowerCase();
const sections = parsePublishedDocumentForCommunityRuleDisplay(document);
for (const section of sections) {
for (const entry of section.entries) {
if (entryHaystack(entry).toLowerCase().includes(needle)) {
return {
categoryName: section.categoryName,
entryTitle: entry.title,
};
}
}
}
return null;
}