@jsonresume/core 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,113 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import React from 'react';
3
+ import { renderHtml } from './renderHtml.jsx';
4
+ import { Avatar, ProfileCard, SocialLinks } from '../../index.js';
5
+
6
+ describe('Avatar', () => {
7
+ it('renders an <img> when src is provided', () => {
8
+ const { html } = renderHtml(
9
+ <Avatar src="https://img.example.com/a.png" alt="Jane Doe" />
10
+ );
11
+ expect(html).toContain('<img');
12
+ expect(html).toContain('src="https://img.example.com/a.png"');
13
+ expect(html).toContain('alt="Jane Doe"');
14
+ });
15
+
16
+ it('renders a placeholder with the first initial when no src/fallback', () => {
17
+ const { html } = renderHtml(<Avatar alt="Jane" />);
18
+ expect(html).not.toContain('<img');
19
+ expect(html).toContain('J');
20
+ });
21
+
22
+ it('renders "?" placeholder when there is no src, fallback, or alt', () => {
23
+ const { html } = renderHtml(<Avatar />);
24
+ expect(html).not.toContain('<img');
25
+ expect(html).toContain('?');
26
+ });
27
+
28
+ it('uses the fallback image when src is absent but fallback is set', () => {
29
+ const { html } = renderHtml(
30
+ <Avatar fallback="https://img.example.com/f.png" alt="x" />
31
+ );
32
+ expect(html).toContain('<img');
33
+ expect(html).toContain('https://img.example.com/f.png');
34
+ });
35
+
36
+ it('uppercases the placeholder initial', () => {
37
+ const { html } = renderHtml(<Avatar alt="zara" />);
38
+ expect(html).toContain('Z');
39
+ });
40
+
41
+ it('passes className through to the rendered element', () => {
42
+ const { html } = renderHtml(<Avatar src="x.png" className="rounded" />);
43
+ expect(html).toContain('rounded');
44
+ });
45
+ });
46
+
47
+ describe('ProfileCard', () => {
48
+ it('renders name, title and summary when provided', () => {
49
+ const { html } = renderHtml(
50
+ <ProfileCard
51
+ name="Jane Doe"
52
+ title="Engineer"
53
+ summary="Builds resilient systems"
54
+ />
55
+ );
56
+ expect(html).toContain('Jane Doe');
57
+ expect(html).toContain('Engineer');
58
+ expect(html).toContain('Builds resilient systems');
59
+ });
60
+
61
+ it('renders without any fields (no crash, empty info)', () => {
62
+ const { html } = renderHtml(<ProfileCard />);
63
+ expect(html).toContain('<div');
64
+ });
65
+
66
+ it('renders a provided avatar node and children', () => {
67
+ const { html } = renderHtml(
68
+ <ProfileCard name="Jane" avatar={<span className="av">AV</span>}>
69
+ <span className="child">extra</span>
70
+ </ProfileCard>
71
+ );
72
+ expect(html).toContain('AV');
73
+ expect(html).toContain('extra');
74
+ });
75
+ });
76
+
77
+ describe('SocialLinks', () => {
78
+ it('renders an anchor per link with target/rel', () => {
79
+ const { html } = renderHtml(
80
+ <SocialLinks
81
+ links={[
82
+ {
83
+ network: 'GitHub',
84
+ username: 'jane',
85
+ url: 'https://github.com/jane',
86
+ },
87
+ { network: 'X', username: 'jane', url: 'https://x.com/jane' },
88
+ ]}
89
+ />
90
+ );
91
+ const anchors = (html.match(/<a /g) || []).length;
92
+ expect(anchors).toBe(2);
93
+ expect(html).toContain('rel="noopener noreferrer"');
94
+ expect(html).toContain('https://github.com/jane');
95
+ });
96
+
97
+ it('renders nothing meaningful for an empty links list', () => {
98
+ const { html } = renderHtml(<SocialLinks links={[]} />);
99
+ expect(html).not.toContain('<a ');
100
+ });
101
+
102
+ it('does not crash when links prop is omitted (defaults to [])', () => {
103
+ const { html } = renderHtml(<SocialLinks />);
104
+ expect(html).toContain('<div');
105
+ });
106
+
107
+ it('falls back to network when username is missing', () => {
108
+ const { html } = renderHtml(
109
+ <SocialLinks links={[{ network: 'Dribbble', url: 'https://x' }]} />
110
+ );
111
+ expect(html).toContain('Dribbble');
112
+ });
113
+ });
@@ -0,0 +1,24 @@
1
+ import React from 'react';
2
+ import { renderToStaticMarkup } from 'react-dom/server';
3
+ import { ServerStyleSheet, StyleSheetManager } from 'styled-components';
4
+
5
+ /**
6
+ * Render a @jsonresume/core component to static HTML using the same
7
+ * ServerStyleSheet path themes use for SSR. Returns both the markup and the
8
+ * collected style tags so tests can assert on output without a DOM or DB.
9
+ *
10
+ * @param {React.ReactElement} element
11
+ * @returns {{ html: string, css: string }}
12
+ */
13
+ export function renderHtml(element) {
14
+ const sheet = new ServerStyleSheet();
15
+ try {
16
+ const html = renderToStaticMarkup(
17
+ <StyleSheetManager sheet={sheet.instance}>{element}</StyleSheetManager>
18
+ );
19
+ const css = sheet.getStyleTags();
20
+ return { html, css };
21
+ } finally {
22
+ sheet.seal();
23
+ }
24
+ }
@@ -2,8 +2,12 @@ import React from 'react';
2
2
  /**
3
3
  * RelativeDate
4
4
  * Display relative date (e.g., "2 years ago", "3 months")
5
+ *
6
+ * The pure getRelativeTime / getDuration helpers now live in @jsonresume/utils
7
+ * (framework-free); this component imports them back.
5
8
  */
6
9
  import styled from 'styled-components';
10
+ import { getRelativeTime, getDuration } from '@jsonresume/utils/dates';
7
11
 
8
12
  const Container = styled.time`
9
13
  font-size: ${(props) => props.$size || 'var(--resume-size-small)'};
@@ -11,78 +15,6 @@ const Container = styled.time`
11
15
  white-space: nowrap;
12
16
  `;
13
17
 
14
- /**
15
- * Calculate relative time from a date
16
- * @param {string|Date} date - Date to calculate from
17
- * @param {boolean} ago - Include "ago" suffix
18
- * @returns {string} Relative time string
19
- */
20
- function getRelativeTime(date, ago = true) {
21
- const now = new Date();
22
- const past = new Date(date);
23
- const diffMs = now - past;
24
- const diffSec = Math.floor(diffMs / 1000);
25
- const diffMin = Math.floor(diffSec / 60);
26
- const diffHour = Math.floor(diffMin / 60);
27
- const diffDay = Math.floor(diffHour / 24);
28
- const diffWeek = Math.floor(diffDay / 7);
29
- const diffMonth = Math.floor(diffDay / 30);
30
- const diffYear = Math.floor(diffDay / 365);
31
-
32
- const suffix = ago ? ' ago' : '';
33
-
34
- if (diffYear > 0) {
35
- return `${diffYear} year${diffYear !== 1 ? 's' : ''}${suffix}`;
36
- }
37
- if (diffMonth > 0) {
38
- return `${diffMonth} month${diffMonth !== 1 ? 's' : ''}${suffix}`;
39
- }
40
- if (diffWeek > 0) {
41
- return `${diffWeek} week${diffWeek !== 1 ? 's' : ''}${suffix}`;
42
- }
43
- if (diffDay > 0) {
44
- return `${diffDay} day${diffDay !== 1 ? 's' : ''}${suffix}`;
45
- }
46
- if (diffHour > 0) {
47
- return `${diffHour} hour${diffHour !== 1 ? 's' : ''}${suffix}`;
48
- }
49
- if (diffMin > 0) {
50
- return `${diffMin} minute${diffMin !== 1 ? 's' : ''}${suffix}`;
51
- }
52
- return 'just now';
53
- }
54
-
55
- /**
56
- * Calculate duration between two dates
57
- * @param {string|Date} startDate - Start date
58
- * @param {string|Date} endDate - End date (defaults to now)
59
- * @returns {string} Duration string
60
- */
61
- function getDuration(startDate, endDate = new Date()) {
62
- const start = new Date(startDate);
63
- const end = new Date(endDate);
64
- const diffMs = end - start;
65
- const diffDay = Math.floor(diffMs / (1000 * 60 * 60 * 24));
66
- const diffMonth = Math.floor(diffDay / 30);
67
- const diffYear = Math.floor(diffDay / 365);
68
-
69
- const years = diffYear;
70
- const months = diffMonth % 12;
71
-
72
- if (years > 0 && months > 0) {
73
- return `${years} year${years !== 1 ? 's' : ''}, ${months} month${
74
- months !== 1 ? 's' : ''
75
- }`;
76
- }
77
- if (years > 0) {
78
- return `${years} year${years !== 1 ? 's' : ''}`;
79
- }
80
- if (months > 0) {
81
- return `${months} month${months !== 1 ? 's' : ''}`;
82
- }
83
- return `${diffDay} day${diffDay !== 1 ? 's' : ''}`;
84
- }
85
-
86
18
  /**
87
19
  * @param {Object} props
88
20
  * @param {string|Date} props.date - Date to display relatively
@@ -4,425 +4,43 @@
4
4
  * Pure functions for computing metrics and insights from JSON Resume data.
5
5
  * Use these helpers in themes to display calculated metrics, statistics, and insights.
6
6
  *
7
- * @module @resume/core/helpers/calculations
8
- */
9
-
10
- /**
11
- * Calculate total years of professional experience from work history
12
- * @param {Array} work - Array of work experience objects with startDate and endDate
13
- * @returns {number} Total years of experience (rounded to nearest year)
14
- *
15
- * @example
16
- * const years = calculateTotalExperience(resume.work);
17
- * // => 8 (years)
18
- */
19
- export function calculateTotalExperience(work = []) {
20
- if (!Array.isArray(work) || work.length === 0) return 0;
21
-
22
- const totalYears = work.reduce((acc, job) => {
23
- if (!job.startDate) return acc;
24
-
25
- const start = new Date(job.startDate);
26
- const end = job.endDate ? new Date(job.endDate) : new Date();
27
- const years = (end - start) / (1000 * 60 * 60 * 24 * 365.25); // Use 365.25 for leap years
28
-
29
- return acc + years;
30
- }, 0);
31
-
32
- return Math.round(totalYears);
33
- }
34
-
35
- /**
36
- * Calculate years of experience for the current/most recent role
37
- * @param {Array} work - Array of work experience objects
38
- * @returns {number} Years in current role (rounded to 1 decimal)
39
- *
40
- * @example
41
- * const currentYears = calculateCurrentRoleExperience(resume.work);
42
- * // => 2.5 (years)
43
- */
44
- export function calculateCurrentRoleExperience(work = []) {
45
- if (!Array.isArray(work) || work.length === 0) return 0;
46
-
47
- // Assume first item is most recent (no endDate or latest endDate)
48
- const currentRole = work.find((job) => !job.endDate) || work[0];
49
- if (!currentRole || !currentRole.startDate) return 0;
50
-
51
- const start = new Date(currentRole.startDate);
52
- const end = currentRole.endDate ? new Date(currentRole.endDate) : new Date();
53
- const years = (end - start) / (1000 * 60 * 60 * 24 * 365.25);
54
-
55
- return Math.round(years * 10) / 10; // Round to 1 decimal
56
- }
57
-
58
- /**
59
- * Count total number of companies worked at
60
- * @param {Array} work - Array of work experience objects
61
- * @returns {number} Number of unique companies
62
- *
63
- * @example
64
- * const companies = countCompanies(resume.work);
65
- * // => 5
66
- */
67
- export function countCompanies(work = []) {
68
- if (!Array.isArray(work) || work.length === 0) return 0;
69
-
70
- const uniqueCompanies = new Set(work.map((job) => job.name).filter(Boolean));
71
-
72
- return uniqueCompanies.size;
73
- }
74
-
75
- /**
76
- * Count total number of projects
77
- * @param {Array} projects - Array of project objects
78
- * @returns {number} Number of projects
79
- *
80
- * @example
81
- * const projectCount = countProjects(resume.projects);
82
- * // => 12
83
- */
84
- export function countProjects(projects = []) {
85
- return Array.isArray(projects) ? projects.length : 0;
86
- }
87
-
88
- /**
89
- * Count total number of publications
90
- * @param {Array} publications - Array of publication objects
91
- * @returns {number} Number of publications
92
- *
93
- * @example
94
- * const pubCount = countPublications(resume.publications);
95
- * // => 8
96
- */
97
- export function countPublications(publications = []) {
98
- return Array.isArray(publications) ? publications.length : 0;
99
- }
100
-
101
- /**
102
- * Count total number of awards received
103
- * @param {Array} awards - Array of award objects
104
- * @returns {number} Number of awards
105
- *
106
- * @example
107
- * const awardCount = countAwards(resume.awards);
108
- * // => 3
109
- */
110
- export function countAwards(awards = []) {
111
- return Array.isArray(awards) ? awards.length : 0;
112
- }
113
-
114
- /**
115
- * Count total skills across all skill categories
116
- * @param {Array} skills - Array of skill objects with keywords
117
- * @returns {number} Total number of skill keywords
118
- *
119
- * @example
120
- * const skillCount = countTotalSkills(resume.skills);
121
- * // => 42
122
- */
123
- export function countTotalSkills(skills = []) {
124
- if (!Array.isArray(skills) || skills.length === 0) return 0;
125
-
126
- return skills.reduce((total, skill) => {
127
- const keywords = skill.keywords || [];
128
- return total + keywords.length;
129
- }, 0);
130
- }
131
-
132
- /**
133
- * Count skill categories
134
- * @param {Array} skills - Array of skill objects
135
- * @returns {number} Number of skill categories
136
- *
137
- * @example
138
- * const categories = countSkillCategories(resume.skills);
139
- * // => 6
140
- */
141
- export function countSkillCategories(skills = []) {
142
- return Array.isArray(skills) ? skills.length : 0;
143
- }
144
-
145
- /**
146
- * Count languages spoken
147
- * @param {Array} languages - Array of language objects
148
- * @returns {number} Number of languages
149
- *
150
- * @example
151
- * const langCount = countLanguages(resume.languages);
152
- * // => 3
153
- */
154
- export function countLanguages(languages = []) {
155
- return Array.isArray(languages) ? languages.length : 0;
156
- }
157
-
158
- /**
159
- * Calculate total volunteer hours (if duration data is available)
160
- * @param {Array} volunteer - Array of volunteer objects with startDate and endDate
161
- * @returns {number} Total volunteer years
162
- *
163
- * @example
164
- * const volunteerYears = calculateVolunteerYears(resume.volunteer);
165
- * // => 4
166
- */
167
- export function calculateVolunteerYears(volunteer = []) {
168
- if (!Array.isArray(volunteer) || volunteer.length === 0) return 0;
169
-
170
- const totalYears = volunteer.reduce((acc, vol) => {
171
- if (!vol.startDate) return acc;
172
-
173
- const start = new Date(vol.startDate);
174
- const end = vol.endDate ? new Date(vol.endDate) : new Date();
175
- const years = (end - start) / (1000 * 60 * 60 * 24 * 365.25);
176
-
177
- return acc + years;
178
- }, 0);
179
-
180
- return Math.round(totalYears);
181
- }
182
-
183
- /**
184
- * Calculate total education years
185
- * @param {Array} education - Array of education objects with startDate and endDate
186
- * @returns {number} Total years of education
187
- *
188
- * @example
189
- * const eduYears = calculateEducationYears(resume.education);
190
- * // => 6
191
- */
192
- export function calculateEducationYears(education = []) {
193
- if (!Array.isArray(education) || education.length === 0) return 0;
194
-
195
- const totalYears = education.reduce((acc, edu) => {
196
- if (!edu.startDate) return acc;
197
-
198
- const start = new Date(edu.startDate);
199
- const end = edu.endDate ? new Date(edu.endDate) : new Date();
200
- const years = (end - start) / ((1000 * 60 * 60 * 24) / 365.25);
201
-
202
- return acc + years;
203
- }, 0);
204
-
205
- return Math.round(totalYears);
206
- }
207
-
208
- /**
209
- * Get highest education level
210
- * @param {Array} education - Array of education objects with studyType
211
- * @returns {string} Highest degree (PhD, Master's, Bachelor's, etc.)
212
- *
213
- * @example
214
- * const degree = getHighestDegree(resume.education);
215
- * // => "PhD"
216
- */
217
- export function getHighestDegree(education = []) {
218
- if (!Array.isArray(education) || education.length === 0) return '';
219
-
220
- const degreeRanking = {
221
- phd: 5,
222
- doctorate: 5,
223
- doctoral: 5,
224
- master: 4,
225
- mba: 4,
226
- bachelor: 3,
227
- associate: 2,
228
- diploma: 1,
229
- certificate: 1,
230
- };
231
-
232
- let highest = { level: 0, studyType: '' };
233
-
234
- education.forEach((edu) => {
235
- if (!edu.studyType) return;
236
-
237
- const studyTypeLower = edu.studyType.toLowerCase();
238
- for (const [key, level] of Object.entries(degreeRanking)) {
239
- if (studyTypeLower.includes(key) && level > highest.level) {
240
- highest = { level, studyType: edu.studyType };
241
- }
242
- }
243
- });
244
-
245
- return highest.studyType;
246
- }
247
-
248
- /**
249
- * Calculate career trajectory (promotions/role changes)
250
- * @param {Array} work - Array of work experience objects with position
251
- * @returns {number} Number of distinct positions held
252
- *
253
- * @example
254
- * const positions = countCareerPositions(resume.work);
255
- * // => 7
256
- */
257
- export function countCareerPositions(work = []) {
258
- if (!Array.isArray(work) || work.length === 0) return 0;
259
-
260
- const uniquePositions = new Set(
261
- work.map((job) => job.position).filter(Boolean)
262
- );
263
-
264
- return uniquePositions.size;
265
- }
266
-
267
- /**
268
- * Get career progression rate (positions per year)
269
- * @param {Array} work - Array of work experience objects
270
- * @returns {number} Average years per position
271
- *
272
- * @example
273
- * const rate = getCareerProgressionRate(resume.work);
274
- * // => 2.3 (years per position)
275
- */
276
- export function getCareerProgressionRate(work = []) {
277
- const totalYears = calculateTotalExperience(work);
278
- const positions = countCareerPositions(work);
279
-
280
- if (totalYears === 0 || positions === 0) return 0;
281
-
282
- return Math.round((totalYears / positions) * 10) / 10;
283
- }
284
-
285
- /**
286
- * Calculate total highlights/achievements across work experience
287
- * @param {Array} work - Array of work experience objects with highlights
288
- * @returns {number} Total number of highlights
289
- *
290
- * @example
291
- * const achievements = countTotalHighlights(resume.work);
292
- * // => 28
293
- */
294
- export function countTotalHighlights(work = []) {
295
- if (!Array.isArray(work) || work.length === 0) return 0;
296
-
297
- return work.reduce((total, job) => {
298
- const highlights = job.highlights || [];
299
- return total + highlights.length;
300
- }, 0);
301
- }
302
-
303
- /**
304
- * Get all unique industries from work experience
305
- * @param {Array} work - Array of work experience objects with industry field
306
- * @returns {Array<string>} Array of unique industries
307
- *
308
- * @example
309
- * const industries = getUniqueIndustries(resume.work);
310
- * // => ["Technology", "Finance", "Healthcare"]
311
- */
312
- export function getUniqueIndustries(work = []) {
313
- if (!Array.isArray(work) || work.length === 0) return [];
314
-
315
- const industries = new Set(work.map((job) => job.industry).filter(Boolean));
316
-
317
- return Array.from(industries);
318
- }
319
-
320
- /**
321
- * Get most recent/current employer
322
- * @param {Array} work - Array of work experience objects
323
- * @returns {Object|null} Most recent work object
324
- *
325
- * @example
326
- * const current = getCurrentEmployer(resume.work);
327
- * // => { name: "Google", position: "Senior Engineer", ... }
328
- */
329
- export function getCurrentEmployer(work = []) {
330
- if (!Array.isArray(work) || work.length === 0) return null;
331
-
332
- // Find first job without endDate (current), or first in array
333
- return work.find((job) => !job.endDate) || work[0];
334
- }
335
-
336
- /**
337
- * Check if currently employed
338
- * @param {Array} work - Array of work experience objects
339
- * @returns {boolean} True if currently employed
340
- *
341
- * @example
342
- * const employed = isCurrentlyEmployed(resume.work);
343
- * // => true
344
- */
345
- export function isCurrentlyEmployed(work = []) {
346
- if (!Array.isArray(work) || work.length === 0) return false;
347
- return work.some((job) => !job.endDate);
348
- }
349
-
350
- /**
351
- * Calculate comprehensive Key Metrics object for dashboard displays
352
- * @param {Object} resume - Complete JSON Resume object
353
- * @returns {Array<Object>} Array of metric objects with label and value
354
- *
355
- * @example
356
- * const metrics = calculateKeyMetrics(resume);
357
- * // => [
358
- * // { label: 'Years Experience', value: 8 },
359
- * // { label: 'Companies', value: 5 },
360
- * // { label: 'Projects', value: 12 },
361
- * // { label: 'Core Skills', value: 42 }
362
- * // ]
363
- */
364
- export function calculateKeyMetrics(resume) {
365
- const metrics = [];
366
-
367
- const {
368
- work = [],
369
- projects = [],
370
- skills = [],
371
- publications = [],
372
- awards = [],
373
- education = [],
374
- volunteer = [],
375
- languages = [],
376
- } = resume;
377
-
378
- // Experience
379
- const experience = calculateTotalExperience(work);
380
- if (experience > 0) {
381
- metrics.push({ label: 'Years Experience', value: experience });
382
- }
383
-
384
- // Companies
385
- const companies = countCompanies(work);
386
- if (companies > 0) {
387
- metrics.push({ label: 'Companies', value: companies });
388
- }
389
-
390
- // Projects
391
- const projectCount = countProjects(projects);
392
- if (projectCount > 0) {
393
- metrics.push({ label: 'Projects', value: projectCount });
394
- }
395
-
396
- // Skills
397
- const skillCount = countTotalSkills(skills);
398
- if (skillCount > 0) {
399
- metrics.push({ label: 'Core Skills', value: skillCount });
400
- }
401
-
402
- // Publications
403
- const pubCount = countPublications(publications);
404
- if (pubCount > 0) {
405
- metrics.push({ label: 'Publications', value: pubCount });
406
- }
407
-
408
- // Awards
409
- const awardCount = countAwards(awards);
410
- if (awardCount > 0) {
411
- metrics.push({ label: 'Awards', value: awardCount });
412
- }
413
-
414
- // Education
415
- const degree = getHighestDegree(education);
416
- if (degree) {
417
- metrics.push({ label: 'Education', value: degree });
418
- }
419
-
420
- // Languages
421
- const langCount = countLanguages(languages);
422
- if (langCount > 1) {
423
- // Only show if multilingual
424
- metrics.push({ label: 'Languages', value: langCount });
425
- }
426
-
427
- return metrics;
428
- }
7
+ * This module is a thin re-export barrel. The implementations now live in
8
+ * @jsonresume/utils (framework-free); the sibling modules below re-export them
9
+ * so @jsonresume/core's public surface stays byte-for-byte stable:
10
+ * - ./experience.js work tenure & career progression
11
+ * - ./counts.js simple section tallies
12
+ * - ./education.js education years & highest degree
13
+ * - ./workHistory.js employment status, industries, volunteer tenure
14
+ * - ./keyMetrics.js dashboard metrics aggregation
15
+ *
16
+ * @module @jsonresume/core/helpers/calculations
17
+ */
18
+
19
+ export {
20
+ calculateTotalExperience,
21
+ calculateCurrentRoleExperience,
22
+ countCareerPositions,
23
+ getCareerProgressionRate,
24
+ countTotalHighlights,
25
+ } from './experience.js';
26
+
27
+ export {
28
+ countCompanies,
29
+ countProjects,
30
+ countPublications,
31
+ countAwards,
32
+ countTotalSkills,
33
+ countSkillCategories,
34
+ countLanguages,
35
+ } from './counts.js';
36
+
37
+ export { calculateEducationYears, getHighestDegree } from './education.js';
38
+
39
+ export {
40
+ calculateVolunteerYears,
41
+ getUniqueIndustries,
42
+ getCurrentEmployer,
43
+ isCurrentlyEmployed,
44
+ } from './workHistory.js';
45
+
46
+ export { calculateKeyMetrics } from './keyMetrics.js';