File size: 10,976 Bytes
aa1ee73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import TurndownService from "turndown";
import { DEFAULT_FIELD_ORDER } from "@/config";
import { getCustomFieldDisplayText, getCustomFieldHref, shouldShowCustomFieldLabelPrefix } from "@/lib/customField";
import { getProjectLinkMeta } from "@/lib/projectLink";
import { BasicFieldType, BasicInfo, CustomItem, MenuSection, ResumeData } from "@/types/resume";

const HTML_TAG_REGEX = /<\/?[a-z][\s\S]*>/i;
const DATA_URL_REGEX = /^data:/i;

const DEFAULT_BASIC_SECTION_TITLES = {
  basic: "Basic Info",
  skills: "Skills",
  experience: "Experience",
  projects: "Projects",
  education: "Education",
  selfEvaluation: "Self Evaluation",
  certificates: "Certificates"
} as const;

type ExportableBasicFieldKey =
  | "name"
  | "title"
  | "employementStatus"
  | "birthDate"
  | "email"
  | "phone"
  | "location";

const BASIC_FIELD_KEYS = new Set<ExportableBasicFieldKey>([
  "name",
  "title",
  "employementStatus",
  "birthDate",
  "email",
  "phone",
  "location"
]);

const DEFAULT_BASIC_FIELD_LABELS: Record<ExportableBasicFieldKey, string> = {
  name: "Name",
  title: "Title",
  employementStatus: "Employment Status",
  birthDate: "Birth Date",
  email: "Email",
  phone: "Phone",
  location: "Location"
};

export interface ResumeMarkdownOptions {
  basicFieldLabels?: Partial<Record<ExportableBasicFieldKey, string>>;
}

const normalizeText = (value?: string) => value?.trim() || "";
const normalizeDateRangeText = (value?: string) =>
  normalizeText(value)
    .split(/\s+-\s*/)
    .map((part) => part.trim())
    .filter(Boolean)
    .join(" - ");

const createTurndownService = () =>
  new TurndownService({
    headingStyle: "atx",
    bulletListMarker: "-"
  });

const markdownFromText = (value?: string) => {
  const normalized = normalizeText(value);
  if (!normalized) return "";

  if (!HTML_TAG_REGEX.test(normalized)) {
    return normalized;
  }

  return createTurndownService().turndown(normalized).trim();
};

const normalizeMarkdown = (content: string) =>
  content
    .replace(/\r\n/g, "\n")
    .replace(/[ \t]+\n/g, "\n")
    .replace(/\n{3,}/g, "\n\n")
    .trim();

const pickBasicFieldValue = (
  basic: BasicInfo,
  key: ExportableBasicFieldKey
) => normalizeText((basic[key] as string | undefined) || "");

const getOrderedEnabledSections = (resume: ResumeData): MenuSection[] => {
  const enabledSections = (resume.menuSections || [])
    .filter((section) => section.enabled)
    .sort((a, b) => a.order - b.order);

  if (enabledSections.length > 0) return enabledSections;

  return [
    { id: "basic", title: DEFAULT_BASIC_SECTION_TITLES.basic, icon: "", enabled: true, order: 0 },
    { id: "skills", title: DEFAULT_BASIC_SECTION_TITLES.skills, icon: "", enabled: true, order: 1 },
    { id: "experience", title: DEFAULT_BASIC_SECTION_TITLES.experience, icon: "", enabled: true, order: 2 },
    { id: "projects", title: DEFAULT_BASIC_SECTION_TITLES.projects, icon: "", enabled: true, order: 3 },
    { id: "education", title: DEFAULT_BASIC_SECTION_TITLES.education, icon: "", enabled: true, order: 4 },
    { id: "selfEvaluation", title: DEFAULT_BASIC_SECTION_TITLES.selfEvaluation, icon: "", enabled: true, order: 5 },
    { id: "certificates", title: DEFAULT_BASIC_SECTION_TITLES.certificates, icon: "", enabled: true, order: 6 }
  ];
};

const renderBasicSection = (
  title: string,
  resume: ResumeData,
  options?: ResumeMarkdownOptions
) => {
  const fieldOrder = (resume.basic.fieldOrder?.length
    ? resume.basic.fieldOrder
    : DEFAULT_FIELD_ORDER) as BasicFieldType[];

  const lines: string[] = [];
  const name = pickBasicFieldValue(resume.basic, "name");
  const summaryTitle = pickBasicFieldValue(resume.basic, "title");

  if (name) lines.push(`### ${name}`);
  if (summaryTitle) lines.push(summaryTitle);

  for (const field of fieldOrder) {
    const key = field.key as ExportableBasicFieldKey;
    if (!BASIC_FIELD_KEYS.has(key)) continue;
    if (field.visible === false) continue;
    if (key === "name" || key === "title") continue;

    const value = pickBasicFieldValue(resume.basic, key);
    if (!value) continue;

    const label =
      options?.basicFieldLabels?.[key] ||
      normalizeText(field.label) ||
      DEFAULT_BASIC_FIELD_LABELS[key];

    lines.push(`- ${label}: ${value}`);
  }

  const customFieldLines = (resume.basic.customFields || [])
    .filter((field) => field.visible !== false)
    .map((field) => {
      const displayText = normalizeText(getCustomFieldDisplayText(field));
      if (!displayText) return "";

      const href = getCustomFieldHref(field);
      const normalizedLabel = normalizeText(field.label);
      const showPrefix = shouldShowCustomFieldLabelPrefix(field) && normalizedLabel;
      const markdownValue = href
        ? `[${displayText}](${href})`
        : displayText;

      return showPrefix
        ? `- ${normalizedLabel}: ${markdownValue}`
        : `- ${markdownValue}`;
    })
    .filter(Boolean);

  const sectionBlocks = [...lines, ...customFieldLines];
  if (sectionBlocks.length === 0) return "";

  return `## ${title}\n\n${sectionBlocks.join("\n")}`;
};

const renderSkillsSection = (title: string, resume: ResumeData) => {
  const content = markdownFromText(resume.skillContent);
  if (!content) return "";
  return `## ${title}\n\n${content}`;
};

const renderSelfEvaluationSection = (title: string, resume: ResumeData) => {
  const content = markdownFromText(resume.selfEvaluationContent);
  if (!content) return "";
  return `## ${title}\n\n${content}`;
};

const renderExperienceSection = (title: string, resume: ResumeData) => {
  const blocks = resume.experience
    .filter((item) => item.visible)
    .map((item) => {
      const heading = [normalizeText(item.company), normalizeText(item.position)]
        .filter(Boolean)
        .join(" | ");
      const date = normalizeDateRangeText(item.date);
      const details = markdownFromText(item.details);
      const lines: string[] = [];

      if (heading) lines.push(`### ${heading}`);
      if (date) lines.push(`_${date}_`);
      if (details) lines.push(details);

      return lines.join("\n\n");
    })
    .filter(Boolean);

  if (blocks.length === 0) return "";
  return `## ${title}\n\n${blocks.join("\n\n")}`;
};

const renderProjectSection = (title: string, resume: ResumeData) => {
  const blocks = resume.projects
    .filter((item) => item.visible)
    .map((item) => {
      const heading = normalizeText(item.name);
      const meta = [normalizeText(item.role), normalizeDateRangeText(item.date)]
        .filter(Boolean)
        .join(" | ");
      const description = markdownFromText(item.description);
      const linkMeta = getProjectLinkMeta(item, { preferFullUrl: true });
      const lines: string[] = [];

      if (heading) lines.push(`### ${heading}`);
      if (meta) lines.push(`_${meta}_`);
      if (description) lines.push(description);
      if (linkMeta?.href) {
        lines.push(`[${normalizeText(linkMeta.label) || linkMeta.href}](${linkMeta.href})`);
      }

      return lines.join("\n\n");
    })
    .filter(Boolean);

  if (blocks.length === 0) return "";
  return `## ${title}\n\n${blocks.join("\n\n")}`;
};

const renderEducationSection = (title: string, resume: ResumeData) => {
  const blocks = resume.education
    .filter((item) => item.visible)
    .map((item) => {
      const heading = [normalizeText(item.school), normalizeText(item.major)]
        .filter(Boolean)
        .join(" | ");
      const duration = [normalizeText(item.startDate), normalizeText(item.endDate)]
        .filter(Boolean)
        .join(" - ");
      const metadata = [normalizeText(item.degree), duration, item.gpa ? `GPA: ${normalizeText(item.gpa)}` : ""]
        .filter(Boolean)
        .join(" | ");
      const description = markdownFromText(item.description);
      const lines: string[] = [];

      if (heading) lines.push(`### ${heading}`);
      if (metadata) lines.push(`_${metadata}_`);
      if (description) lines.push(description);

      return lines.join("\n\n");
    })
    .filter(Boolean);

  if (blocks.length === 0) return "";
  return `## ${title}\n\n${blocks.join("\n\n")}`;
};

const renderCertificateSection = (title: string, resume: ResumeData) => {
  const lines = resume.certificates
    .map((certificate, index) => {
      const url = normalizeText(certificate.url);
      if (!url) return "";
      if (DATA_URL_REGEX.test(url)) {
        return `- Certificate ${index + 1} (embedded image omitted)`;
      }
      return `- ![Certificate ${index + 1}](${url})`;
    })
    .filter(Boolean);

  if (lines.length === 0) return "";
  return `## ${title}\n\n${lines.join("\n")}`;
};

const renderCustomSection = (title: string, items: CustomItem[]) => {
  const blocks = items
    .filter((item) => item.visible)
    .map((item, index) => {
      const heading =
        normalizeText(item.title) ||
        normalizeText(item.subtitle) ||
        `Item ${index + 1}`;
      const subtitle = normalizeText(item.subtitle);
      const dateRange = normalizeDateRangeText(item.dateRange);
      const details = markdownFromText(item.description);
      const metadata = [subtitle !== heading ? subtitle : "", dateRange]
        .filter(Boolean)
        .join(" | ");
      const lines: string[] = [];

      if (heading) lines.push(`### ${heading}`);
      if (metadata) lines.push(`_${metadata}_`);
      if (details) lines.push(details);

      return lines.join("\n\n");
    })
    .filter(Boolean);

  if (blocks.length === 0) return "";
  return `## ${title}\n\n${blocks.join("\n\n")}`;
};

export const generateResumeMarkdown = (
  resume: ResumeData,
  options?: ResumeMarkdownOptions
) => {
  const topTitle = normalizeText(resume.title) || "Resume";
  const sections = getOrderedEnabledSections(resume);
  const blocks: string[] = [`# ${topTitle}`];

  for (const section of sections) {
    const sectionTitle = normalizeText(section.title) || section.id;
    let content = "";

    switch (section.id) {
      case "basic":
        content = renderBasicSection(sectionTitle, resume, options);
        break;
      case "skills":
        content = renderSkillsSection(sectionTitle, resume);
        break;
      case "experience":
        content = renderExperienceSection(sectionTitle, resume);
        break;
      case "projects":
        content = renderProjectSection(sectionTitle, resume);
        break;
      case "education":
        content = renderEducationSection(sectionTitle, resume);
        break;
      case "selfEvaluation":
        content = renderSelfEvaluationSection(sectionTitle, resume);
        break;
      case "certificates":
        content = renderCertificateSection(sectionTitle, resume);
        break;
      default: {
        const customItems = resume.customData?.[section.id] || [];
        content = renderCustomSection(sectionTitle, customItems);
        break;
      }
    }

    if (content) blocks.push(content);
  }

  return normalizeMarkdown(blocks.join("\n\n"));
};