add timeElement()
authorJustin Wind <justin.wind+git@gmail.com>
Sun, 11 Sep 2022 21:23:58 +0000 (14:23 -0700)
committerJustin Wind <justin.wind+git@gmail.com>
Sun, 11 Sep 2022 21:23:58 +0000 (14:23 -0700)
lib/template-helper.js
test/lib/template-helper.js

index 16a14cc4c3d0bdfd42406a03ef29d31f698eddaa..c983e80acd44329fc6c516ee874198fc2d2e6e58 100644 (file)
@@ -65,6 +65,33 @@ lazy(dateFormat, '_dtf', () => {
 });
 
 
 });
 
 
+/**
+ * Wrap a Date in a <time> block.
+ * @param {Date} date
+ * @param {Object} options
+ * @param {String=} options.title
+ */
+const timeElement = (date, options = {}) => {
+  const {
+    title,
+    pInf,
+    nInf,
+    otherwise,
+  } = options;
+  const attributes = {
+    ...(title && { title }),
+    ...(date instanceof Date && { datetime: date.toISOString() }),
+  };
+  return [
+    '<time',
+    elementAttributes(attributes),
+    '>',
+    dateFormat(date, pInf, nInf, otherwise),
+    '</time>',
+  ].join('');
+}
+
+
 /**
  * Render a duration.
  * @param {Number} seconds
 /**
  * Render a duration.
  * @param {Number} seconds
@@ -367,6 +394,7 @@ function htmlPage(pagePathLevel, ctx, options, main = []) {
 module.exports = {
   dateOrNot,
   dateFormat,
 module.exports = {
   dateOrNot,
   dateFormat,
+  timeElement,
   secondsToPeriod,
   htmlHead,
   htmlBody,
   secondsToPeriod,
   htmlHead,
   htmlBody,
index ab5533faca6695fa1328b94089b0b11f3a878501..fa3f86a33a7517bbdee59626cc6de2f92218ac55 100644 (file)
@@ -83,6 +83,26 @@ describe('Template Helper', function () {
     });
   }); // dateFormat
 
     });
   }); // dateFormat
 
+  describe('timeElement', function () {
+    it('renders a date', function () {
+      const when = new Date('2022-09-11T21:17:56.872Z');
+      const expected = '<time datetime="2022-09-11T21:17:56.872Z">Sep 11, 2022, 2:17:56 PM PDT</time>';
+      const result = th.timeElement(when);
+      assert.strictEqual(result, expected);
+    });
+    it('covers title', function () {
+      const when = new Date('2022-09-11T21:17:56.872Z');
+      const expected = '<time title="a date" datetime="2022-09-11T21:17:56.872Z">Sep 11, 2022, 2:17:56 PM PDT</time>';
+      const result = th.timeElement(when, { title: 'a date' });
+      assert.strictEqual(result, expected);
+    });
+    it('covers other', function () {
+      const expected = '<time>Mar 27, 2022, 3:28:05 PM PDT</time>';
+      const result = th.timeElement(1648420085049);
+      assert.strictEqual(result, expected);
+    });
+  }); // timeElement
+
   describe('secondsToPeriod', function () {
     it('covers seconds', function () {
       const result = th.secondsToPeriod(45);
   describe('secondsToPeriod', function () {
     it('covers seconds', function () {
       const result = th.secondsToPeriod(45);