articles: auto-link company mentions to manufacturer directory
When an article body is rendered, scan it for any company name in bb.tracked_companies (directory_visible=true) and wrap the first mention of each company in <a class="company-mention" data-company-slug="...">Name</a> linking to /manufacturers/<slug>. Caps at 12 mentions per article so heavy press-release lists don't get visually noisy. Match rules: - Word-boundary, case-insensitive - Skips text already inside <a>, <script>, <style>, code/pre/headings - Skips any element with data-no-autolink="true" - Longest name wins on overlap (Sony Pictures beats Sony) - One link per company per article (first occurrence) Hover behavior: a new CompanyMentionsHover client component mounts once per article page, listens globally for [data-company-slug] hovers, and pops a floating card showing logo, name, 2-sentence bio, sponsor/NAB/IBC badges, HQ city, 3 recent stories, and links to the full profile + external website. Preview data fetched from new endpoint /api/public/companies/[slug]/preview with a client-side cache keyed by slug. Includes non-advertisers — any visible directory entry gets linked, which is the point. If a company is *also* a current banner advertiser on broadcastbeat, the hover card adds a green "Sponsor" badge. Styling: dotted underline that becomes solid on hover, slightly bolder weight, accent color on hover. Subtle so multi-mention paragraphs don't look like a link-soup.
This commit is contained in:
158
src/lib/company-mentions.ts
Normal file
158
src/lib/company-mentions.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* Auto-link company names in article body HTML to their manufacturer
|
||||
* directory profiles. Mentions are wrapped in
|
||||
* <a href="/manufacturers/<slug>" data-company-slug="<slug>" class="company-mention">Name</a>
|
||||
* so a client-side hover-card component can pop a preview on hover.
|
||||
*
|
||||
* Linking respects the directory_visible flag, only links the FIRST
|
||||
* occurrence per company per article (to avoid clutter), and never
|
||||
* double-wraps existing <a> tags.
|
||||
*/
|
||||
|
||||
import * as cheerio from "cheerio";
|
||||
import { createAdminClient } from "./supabase/admin";
|
||||
|
||||
export type DirectoryCompany = {
|
||||
name: string;
|
||||
slug: string;
|
||||
/** lower-case name used for matching */
|
||||
needle: string;
|
||||
};
|
||||
|
||||
const MAX_LINKS_PER_ARTICLE = 12;
|
||||
|
||||
let cached: { rows: DirectoryCompany[]; expires: number } | null = null;
|
||||
const CACHE_TTL_MS = 5 * 60 * 1000; // 5 min — companies barely change
|
||||
|
||||
export async function loadDirectoryCompanies(): Promise<DirectoryCompany[]> {
|
||||
if (cached && cached.expires > Date.now()) return cached.rows;
|
||||
try {
|
||||
const svc = createAdminClient(); // bb schema default
|
||||
const { data } = await svc
|
||||
.from("tracked_companies")
|
||||
.select("company_name, slug")
|
||||
.eq("directory_visible", true)
|
||||
.not("slug", "is", null)
|
||||
.not("company_name", "is", null);
|
||||
const rows: DirectoryCompany[] = (data || [])
|
||||
.filter((r: any) => r.company_name && r.slug)
|
||||
.map((r: any) => ({
|
||||
name: String(r.company_name).trim(),
|
||||
slug: String(r.slug),
|
||||
needle: String(r.company_name).trim().toLowerCase(),
|
||||
}))
|
||||
.filter((r) => r.needle.length >= 3); // skip 2-char names — too noisy
|
||||
// Sort by longest name first so "Sony Pictures" wins over "Sony"
|
||||
rows.sort((a, b) => b.needle.length - a.needle.length);
|
||||
cached = { rows, expires: Date.now() + CACHE_TTL_MS };
|
||||
return rows;
|
||||
} catch {
|
||||
return cached?.rows || [];
|
||||
}
|
||||
}
|
||||
|
||||
function escapeRegex(s: string): string {
|
||||
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk text nodes of the parsed HTML and replace the first occurrence of
|
||||
* each company name with a link. Skips text inside <a>, <script>, <style>,
|
||||
* <code>, <pre>, headings, and any node carrying data-no-autolink="true".
|
||||
*/
|
||||
export function linkifyCompanyMentions(html: string, companies: DirectoryCompany[]): string {
|
||||
if (!html || companies.length === 0) return html;
|
||||
|
||||
const $ = cheerio.load(html, { decodeEntities: false }, false);
|
||||
const used = new Set<string>(); // slugs already linked
|
||||
let total = 0;
|
||||
|
||||
// Pre-scan existing <a> texts so we don't re-link a company already linked
|
||||
$("a").each((_, el) => {
|
||||
const t = $(el).text().toLowerCase();
|
||||
for (const c of companies) {
|
||||
if (t.includes(c.needle)) used.add(c.slug);
|
||||
}
|
||||
});
|
||||
|
||||
const SKIP_TAGS = new Set(["a", "script", "style", "code", "pre", "h1", "h2", "h3", "h4", "h5", "h6"]);
|
||||
|
||||
function processNode(node: any): void {
|
||||
if (total >= MAX_LINKS_PER_ARTICLE) return;
|
||||
if (!node) return;
|
||||
if (node.type === "tag") {
|
||||
if (SKIP_TAGS.has(node.name)) return;
|
||||
if (node.attribs && node.attribs["data-no-autolink"] === "true") return;
|
||||
const kids = node.children ? [...node.children] : [];
|
||||
for (const k of kids) processNode(k);
|
||||
return;
|
||||
}
|
||||
if (node.type !== "text") return;
|
||||
const text: string = node.data || "";
|
||||
if (!text.trim()) return;
|
||||
|
||||
// Find the earliest, longest match among unlinked companies
|
||||
let bestStart = -1;
|
||||
let bestEnd = -1;
|
||||
let bestCompany: DirectoryCompany | null = null;
|
||||
for (const c of companies) {
|
||||
if (used.has(c.slug)) continue;
|
||||
if (total >= MAX_LINKS_PER_ARTICLE) break;
|
||||
// Word-boundary, case-insensitive. \b doesn't work great for some
|
||||
// names with punctuation (e.g. "Aja.com"); we use a lookaround.
|
||||
const re = new RegExp(`(^|[^A-Za-z0-9])(${escapeRegex(c.name)})(?![A-Za-z0-9])`, "i");
|
||||
const m = re.exec(text);
|
||||
if (!m) continue;
|
||||
const matchStart = m.index + m[1].length;
|
||||
const matchEnd = matchStart + m[2].length;
|
||||
// Prefer earlier match; on tie prefer longer name (companies are sorted
|
||||
// longest-first, so first hit wins)
|
||||
if (bestStart === -1 || matchStart < bestStart || (matchStart === bestStart && matchEnd - matchStart > bestEnd - bestStart)) {
|
||||
bestStart = matchStart;
|
||||
bestEnd = matchEnd;
|
||||
bestCompany = c;
|
||||
}
|
||||
}
|
||||
|
||||
if (!bestCompany || bestStart < 0) return;
|
||||
|
||||
const before = text.slice(0, bestStart);
|
||||
const matched = text.slice(bestStart, bestEnd);
|
||||
const after = text.slice(bestEnd);
|
||||
|
||||
// Replace this text node with: before + <a> + after, then continue
|
||||
// processing the "after" portion so additional companies in the same
|
||||
// text node can also link.
|
||||
const $a = $(
|
||||
`<a href="/manufacturers/${bestCompany.slug}" data-company-slug="${bestCompany.slug}" class="company-mention">${$.text([{ type: "text", data: matched } as any])}</a>`,
|
||||
);
|
||||
const beforeNode = before ? { type: "text", data: before } : null;
|
||||
const afterNode = after ? { type: "text", data: after } : null;
|
||||
|
||||
const parent = node.parent;
|
||||
if (!parent) return;
|
||||
const idx = parent.children.indexOf(node);
|
||||
if (idx < 0) return;
|
||||
|
||||
const newChildren: any[] = [];
|
||||
if (beforeNode) newChildren.push(beforeNode);
|
||||
newChildren.push($a[0]);
|
||||
if (afterNode) newChildren.push(afterNode);
|
||||
parent.children.splice(idx, 1, ...newChildren);
|
||||
|
||||
used.add(bestCompany.slug);
|
||||
total++;
|
||||
|
||||
if (afterNode) processNode(afterNode); // recurse into the leftover text
|
||||
}
|
||||
|
||||
$.root().children().each((_, el) => processNode(el));
|
||||
|
||||
return $.html();
|
||||
}
|
||||
|
||||
/** Convenience: load companies + linkify in one call. */
|
||||
export async function linkifyArticleHtml(html: string): Promise<string> {
|
||||
const companies = await loadDirectoryCompanies();
|
||||
return linkifyCompanyMentions(html, companies);
|
||||
}
|
||||
Reference in New Issue
Block a user