413 lines
12 KiB
JavaScript
Raw Normal View History

2020-02-21 20:05:52 -08:00
const path = require('path');
const fs = require('fs-extra');
const log = require('fancy-log');
2020-03-07 18:04:37 -08:00
const { resolve, readFile, ENGINE, TYPE } = require('./resolve');
2020-02-21 20:05:52 -08:00
2020-05-13 11:45:26 -07:00
const handybars = require('handybars');
const Kit = require('handybars/kit');
2020-02-21 20:05:52 -08:00
2020-04-07 10:32:23 -07:00
const slugify = require('./lib/slugify');
2021-02-27 20:43:09 -08:00
const { stripHtml } = require('string-strip-html');
2020-02-21 20:05:52 -08:00
const markdownIt = require('markdown-it');
const i18n = require('./lang');
2020-02-21 20:05:52 -08:00
2021-08-11 11:48:50 -07:00
const mAnchor = require('markdown-it-anchor');
2020-02-21 20:05:52 -08:00
const dateFNS = require('date-fns');
const dateFNSLocales = require('date-fns/locale');
const str2locale = {
'en': dateFNSLocales.enUS,
'zh': dateFNSLocales.zhCN,
'de': dateFNSLocales.de,
'fr': dateFNSLocales.fr,
'hu': dateFNSLocales.hu,
'pl': dateFNSLocales.pl,
'pt': dateFNSLocales.pt,
'es': dateFNSLocales.es,
Dutch translation (#136) * Add folder for Dutch translation with images Copied images from English version. No changes were made at all, _titlecard.png should be changed! * Add Dutch language to files outside language dir * Add Dutch nonpage language files and index page Added files to public/nl/ dir: _concat.json _disclaimer.hbs _menu.hbs _strings.js index.md * Add first Dutch pages Pages: wat-is-gender (what-is-gender) geschiedenis (history) euforie (euphoria) fysieke-dysforie (physical-dysphoria) * Suggestion: Add link for androgyne gender Add link for androgyne gender to the what-is-gender pages for the following languages: English Dutch French Hungarian Portuguese Missing for languages: Chinese (zh) German (de) Polish (pl) Spanish (es) * Add empty files to enable the build to run * Add language tags and fix language-menu Added the 'lang' tag to all .md files for the Dutch language Fixed bug where Dutch line in language-menu was set to Portuguese class * Fix language-menu bug for Spanish language Fixed bug where Spanish line in language-menu was set to Portuguese class * Update TWEET_DATE_FORMAT Shortened month (LLL) already contains a period, remove double period * Complete and review Dutch biochemical-dysphoria * Add&review Dutch translation for social-dysphoria * Fix contibution link in disclaimer Link to contributions page was wrongfully translated * Add&review Dutch translation of societal-dysphoria * Add&review Dutch translation for sexual-dysphoria * Fix broken link to next page Link to next page (presentationele-dysforie) was broken on newly translated page (seksuele-dysforie) * Add&review Dutch translation of presentational-dysphoria * Add comments for broken link The presentational-dysphoria page contains a broken YouTube link. This commit adds HTML comments to the Dutch and English pages notifying about the broken link. Should be reverted when https://github.com/GenderDysphoria/GenderDysphoria.fyi/issues/139 is fixed. * Add&review Dutch existential-dysphoria page * Add&review Dutch managed-dysphoria page Also rename dutch page file and rename links to the page * Check translated Dutch files for mixups Sometimes 'gender' and 'sex' were wrongfully interchanged during translation. Fix these mixups for the following pages: - index.md (index.md) - wat-is-gender.md (what-is-gender.md) - geschiedenis.md (history.md) - euforie.md (euphoria.md) - fysieke-dysforie.md (physical-dysphoria.md) - biochemische-dysforie.md (biochemical-dysphoria.md) - sociale-dysforie.md (social-dysphoria.md) - maatschappelijke-dysforie.md (societal-dysphoria.md) - seksuele-dysforie.md (sexual-dysphoria.md) - presentationele-dysforie.md (presentational-dysphoria.md) - existentiele-dysforie.md (existential-dysphoria.md) - beheerste-dysforie.md (managed-dysphoria.md) * Add&review Dutch impostor-syndrome page * Add the Dutch translation for the am-i-trans page Warning! This page hasn't been reviewed yet! * Add & review Dutch translation for diagnoses page * Revert "Add comments for broken link" This reverts commit 6692acb9f7d13663036b1e210584f844e7077046. * Update broken link in Dutch translation Fix link from Issue #139 in Dutch translation after new link was provided and other languages fixed * Review and update first half of am-i-trans page Only got to about the first half while on a plane * Update text&complete review of am-i-trans in Dutch Update headers to capitalize them correctly Update all uses of quotes to fix their use Complete last part of page * Proposed typo fix in treatment.md * Add&review Dutch translation of causes page * Add unreviewed Dutch translation of chromosomes * Add unreviewed Dutch translation of hormones page * Review&update Dutch chromosomes page * Review&update Dutch translation of hormones page * Add&review Dutch translation of treatment page * Start Dutch (manual) translation of conclusion * Update&Review Dutch translation of conclusion page * Finish reviewing Dutch translation of hormones * Add unreviewed Dutch translation of masc 2nd pub * Remove double space from second-puberty-masc page * Start reviewing Dutch translation of masc puberty * Complete reviewing translation of masc puberty * Small change in the first note on Dutch masc pub * Add&review Dutch translation of fem 2nd puberty * Resolve ToDo in Dutch geschiedenis page Did some research to confirm the meaning of the WV abbreviation in the quote on the original English page * Resolve ToDo in Dutch ben-ik-trans page Resolve ToDo about the translation of a sentence * Change page name in link to Dutch 2nd fem puberty Page link from Dutch conclusion page to the previous 2nd fem puberty page was incorrectly named * Fix link on Dutch conclusion page Dutch Conclusion page linked back to the English 2nd fem puberty page * Fix Dutch printable page view Dutch version of _concat.json was collecting the pages to the wrong output
2023-09-21 21:57:10 +02:00
'nl': dateFNSLocales.nl,
2024-10-06 11:02:18 -07:00
'ru': dateFNSLocales.ru,
};
2020-02-21 20:05:52 -08:00
const markdownEngines = {
full: markdownIt({
html: true,
linkify: true,
typographer: true,
})
.enable('image')
.use(require('markdown-it-link-attributes'), {
pattern: /^https?:/,
attrs: {
target: '_blank',
rel: 'noopener',
},
})
2021-08-11 11:48:50 -07:00
.use(mAnchor, {
slugify,
2021-08-27 11:53:38 -07:00
permalink: mAnchor.permalink.linkInsideHeader({
2021-08-11 11:48:50 -07:00
class: 'header-link',
symbol: '<img src="/images/svg/paragraph.svg">',
2021-08-27 11:53:38 -07:00
ariaHidden: true,
2021-08-11 11:48:50 -07:00
}),
2020-02-21 20:05:52 -08:00
})
.use(require('./lib/markdown-raw-html'), { debug: false }),
2020-02-21 20:05:52 -08:00
preview: markdownIt({
html: false,
linkify: false,
typographer: true,
})
2020-02-28 10:31:13 -08:00
.use(require('./lib/markdown-token-filter')),
2020-02-21 20:05:52 -08:00
};
2020-05-13 11:45:26 -07:00
function markdown (mode, input, data, hbs) {
2020-02-21 20:05:52 -08:00
if (mode === 'preview') {
2021-02-27 20:43:09 -08:00
input = stripHtml(input
2020-02-21 20:05:52 -08:00
.replace(/<!--\[[\s\S]*?\]-->/g, '')
.replace(/æææ[\s\S]*?æææ/gi, '')
.replace(/\{!\{([\s\S]*?)\}!\}/mg, '')
2020-10-12 13:30:50 -07:00
).result.trim();
2020-02-21 20:05:52 -08:00
if (input.length > 1000) input = input.slice(0, 1000) + '…';
2020-02-21 20:05:52 -08:00
} else {
input = input.replace(/\{!\{([\s\S]*?)\}!\}/mg, (match, contents) => {
2020-05-13 12:29:39 -07:00
const result = hbs(contents, data);
return 'æææ' + result + 'æææ';
});
2020-02-21 20:05:52 -08:00
input = input.replace(/<!--[[\]]-->/g, '');
}
2020-03-15 16:49:03 -07:00
try {
2020-05-13 11:45:26 -07:00
return input ? markdownEngines[mode].render(input, data) : '';
2020-03-15 16:49:03 -07:00
} catch (e) {
log(input);
throw e;
}
2020-02-21 20:05:52 -08:00
}
function stripIndent (input) {
const match = input.match(/^[^\S\n]*(?=\S)/gm);
const indent = match && Math.min(...match.map((el) => el.length));
if (indent) {
const regexp = new RegExp(`^.{${indent}}`, 'gm');
input = input.replace(regexp, '');
}
return input;
}
2020-05-13 11:45:26 -07:00
const HANDYBARS_PARTIALS = {
2020-02-21 20:05:52 -08:00
layout: 'templates/layout.hbs',
2020-05-13 11:45:26 -07:00
};
const HANDYBARS_TEMPLATES = {
2020-03-07 18:04:37 -08:00
page: 'templates/page.hbs',
post: 'templates/post.hbs',
2020-02-21 20:05:52 -08:00
};
module.exports = exports = async function (prod) {
2020-05-13 11:45:26 -07:00
const revManifest = prod && await fs.readJson(resolve('rev-manifest.json')).catch(() => {}).then((r) => r || {});
const injectables = new Injectables(prod, revManifest);
const env = { ...Kit, ...injectables.helpers() };
for (const [ name, file ] of Object.entries(HANDYBARS_PARTIALS)) {
2020-02-21 20:05:52 -08:00
try {
2020-02-25 19:37:10 -08:00
const contents = await readFile(file);
2020-05-13 11:45:26 -07:00
env[name] = handybars.partial(contents.toString('utf8'));
2020-02-21 20:05:52 -08:00
} catch (e) {
2020-05-13 11:45:26 -07:00
log.error('Could not load partial ' + file, e);
2020-02-21 20:05:52 -08:00
}
}
2020-05-13 11:45:26 -07:00
const templates = {};
for (const [ name, file ] of Object.entries(HANDYBARS_TEMPLATES)) {
try {
const contents = await readFile(file);
templates[name] = handybars(contents.toString('utf8'), env);
} catch (e) {
2020-05-13 12:29:39 -07:00
log.error('Could not load template ' + file, e);
2020-05-13 11:45:26 -07:00
}
}
2020-02-21 20:05:52 -08:00
2020-05-13 11:45:26 -07:00
const hbs = (source, data) => handybars(source, env)(data);
2020-02-21 20:05:52 -08:00
const result = {
2020-05-13 12:29:39 -07:00
[TYPE.HANDYBARS]: hbs,
2020-05-13 11:45:26 -07:00
[TYPE.MARKDOWN]: (source, data) => markdown('full', source, data, hbs),
2020-03-07 18:04:37 -08:00
[TYPE.OTHER]: (source) => source,
2020-05-13 11:45:26 -07:00
[ENGINE.PAGE]: (source, data) => templates.page({ ...data, contents: markdown('full', source, data, hbs) }),
[ENGINE.POST]: (source, data) => templates.post({ ...data, contents: markdown('full', source, data, hbs) }),
[ENGINE.HTML]: (source) => source,
2020-03-07 18:04:37 -08:00
[ENGINE.OTHER]: (source) => source,
2020-05-13 11:45:26 -07:00
preview: (source, data) => markdown('preview', source, data, hbs),
2020-02-21 20:05:52 -08:00
};
return result;
};
class Injectables {
constructor (prod, revManifest) {
this.prod = prod;
this.revManifest = revManifest;
this.injections = {};
this.languages = {};
2020-02-21 20:05:52 -08:00
}
_parsePath (tpath, local, type) {
2020-02-25 19:37:10 -08:00
if (tpath[0] === '/') tpath = resolve(tpath.slice(1));
else if (tpath[0] === '~') tpath = resolve('templates', tpath.slice(2));
2020-02-21 20:05:52 -08:00
else tpath = path.resolve(local.cwd, tpath);
if (type && !tpath.endsWith(type)) tpath += '.' + type;
return tpath;
}
_template (tpath, make) {
2020-02-27 18:57:39 -08:00
if (!tpath) throw new Error('Received an empty template path: ' + tpath);
2020-02-21 20:05:52 -08:00
if (this.injections[tpath]) return this.injections[tpath];
if (!fs.existsSync(tpath)) {
2020-02-27 18:57:39 -08:00
throw new Error('Injectable does not exist: ' + tpath);
2020-02-21 20:05:52 -08:00
}
let contents;
try {
contents = fs.readFileSync(tpath).toString('utf8');
if (make) contents = make(contents);
this.injections[tpath] = contents;
return contents;
} catch (e) {
2020-02-25 19:37:10 -08:00
log.error(e, 'An error occured while loading the injectable: ' + tpath);
2020-02-21 20:05:52 -08:00
}
return '';
}
2020-05-13 11:45:26 -07:00
helpers () {
return {
import: this.import(),
markdown: this.markdown(),
icon: this.icon(),
coalesce: this.coalesce(),
prod: this.production(),
rev: this.rev(),
lang: this.lang(),
date: this.date(),
2020-05-13 11:45:26 -07:00
};
}
2020-02-21 20:05:52 -08:00
rev () {
const self = this;
return function (url) {
if (!url) return '';
if (url[0] === '/') url = url.substr(1);
if (self.prod && self.revManifest[url]) return '/' + self.revManifest[url];
return '/' + url;
};
}
production () {
const self = this;
2020-05-13 11:45:26 -07:00
return function ({ fn, inverse }) {
if (!fn) return self.prod;
return self.prod ? fn(this) : inverse && inverse(this);
2020-02-21 20:05:52 -08:00
};
}
markdown () {
const self = this;
return function (...args) {
2020-05-13 11:45:26 -07:00
const { fn, data, resolve: rval } = args.pop();
const local = rval('@root.this.local');
2020-02-21 20:05:52 -08:00
let contents;
if (fn) {
2020-03-05 19:40:18 -08:00
contents = stripIndent(fn(data.root));
2020-02-21 20:05:52 -08:00
} else {
let tpath = args.shift();
2020-05-13 11:45:26 -07:00
tpath = self._parsePath(tpath, local, 'md');
2020-02-21 20:05:52 -08:00
contents = self._template(tpath);
}
2020-05-13 11:45:26 -07:00
contents = markdown('full', contents, data, () => { throw new Error('You went too deep!'); });
2020-02-21 20:05:52 -08:00
2020-05-13 11:45:26 -07:00
return { value: contents };
2020-02-21 20:05:52 -08:00
};
}
import () {
const self = this;
return function (tpath, ...args) {
2020-05-13 11:45:26 -07:00
const { hash, env, resolve: rval } = args.pop();
const value = args.shift() || this;
2020-05-13 11:45:26 -07:00
const frame = handybars.makeContext(value, env, { hash });
const local = rval('@root.this.local');
2020-02-21 20:05:52 -08:00
2020-05-13 11:45:26 -07:00
tpath = self._parsePath(tpath, local, 'hbs');
2020-02-21 20:05:52 -08:00
try {
2020-05-13 11:45:26 -07:00
const contents = self._template(tpath, handybars.parse).evaluate(value, frame);
return handybars.safe(contents);
2020-02-21 20:05:52 -08:00
} catch (e) {
2020-02-27 18:57:39 -08:00
log.error('Could not execute import template ' + tpath, e);
2020-02-21 20:05:52 -08:00
return '';
}
};
}
icon () {
const self = this;
return function (name, ...args) {
2020-05-13 11:45:26 -07:00
const { hash, env, resolve: rval } = args.pop();
const local = rval('@root.this.local');
const tpath = path.join(local.root, 'svg', name + '.svg');
if (hash.size && String(hash.size).match(/^\d+$/)) {
hash.size = hash.size + 'px';
}
2020-05-13 11:45:26 -07:00
const frame = handybars.makeContext(hash, env);
2020-02-21 20:05:52 -08:00
try {
const contents = self._template(tpath, (s) =>
handybars(`<span class="svg-icon" style="{{#if this.size}}width:{{this.size}};height:{{this.size}};{{/if}}{{this.style}}">${s}</span>`)
2020-05-13 11:45:26 -07:00
)(frame);
2020-02-21 20:05:52 -08:00
2020-05-13 11:45:26 -07:00
return handybars.safe(contents);
2020-02-21 20:05:52 -08:00
} catch (e) {
2020-02-27 18:57:39 -08:00
log.error('Could not execute import template ' + tpath, e);
2020-02-21 20:05:52 -08:00
return '';
}
};
}
lang () {
return function (key, ...args) {
const { resolve: rval } = args.pop();
const lang = rval('@root.this.page.lang').split('-')[0];
return i18n(lang, key, ...args);
};
}
// Given a list of arguments, returns the first that isn't undefined
coalesce () {
return function (...raw_args) {
const { arguments: args } = raw_args.pop();
for (const value of Object.values(args)) {
if (value !== undefined) {
return value;
}
}
return undefined;
};
}
// Multi tool for printing dates
//
// {{date}} -> prints current date
// {{date datestr}} -> prints date in datestr
// {{date datestr datefmt}} -> prints date in datestr in format datefmt
// {{date datestr datefmt lang}} -> prints date in datestr in format datefmt according to conventions for language lang
//
// Datestr can be the string "now", `undefined`, and anything parsable by `new Date()`.
//
// If lang is not specified, it will be extracted from the page metadata. If that is not available, English will be assumed.
// In case of errors, the date will be returned as an ISO string if possible and its raw datestr input otherwise.
// Datefmt format is available at https://date-fns.org/v2.25.0/docs/format
//
// Common formats:
// - "h:mm aa - EEE, LLL do, yyyy" = 12 hour clock, e.g. '1:28 PM - Sat, Feb 15th, 2020' (en) or '1:28 PM - sam., 15/févr./2020' (fr)
// - "hh:mm - EEE, LLL do, yyyy" = 24 hour clock, e.g. '13:28 - Sat, Feb 15th, 2020' (en) or '13:28 - sam., 15/févr./2020' (fr)
// - "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" or "iso" = ISO 8601 format, e.g. '2020-02-15T13:28:02.000Z'
date () {
return function (...args) {
const extra = args.pop();
let datestr, dateobj, datefmt, lang;
const { resolve: rval } = extra;
const filename = rval('@value.input');
lang = (rval('@root.this.page.lang') || 'en').split('-')[0];
switch (args.length) {
case 0:
datestr = 'now';
break;
case 1:
datestr = args[0];
break;
case 2:
datestr = args[0];
datefmt = args[1];
break;
case 3:
datestr = args[0];
datefmt = args[1];
lang = args[2];
break;
default:
throw new Error('wrong number of arguments for {{date}}, got ' + args.length + ' maximum is 3');
}
if (datestr === 'now' || datestr === undefined) {
dateobj = new Date();
} else {
dateobj = new Date(datestr);
}
if (!dateFNS.isValid(dateobj)) {
log.error('Invalid input for date: ', { datestr, filename, args, extra });
return datestr.toString();
}
if (datefmt === 'iso') {
return dateobj.toISOString();
}
if (lang === undefined) {
return dateobj.toISOString();
}
const locale = str2locale[lang];
if (locale === undefined) {
log.warn('Locale not found: ' + lang);
}
if (datefmt === undefined || locale === undefined) {
const options = {
weekday: 'short',
year: 'numeric',
month: 'short',
day: 'numeric',
timeZone: 'UTC',
timeZoneName: 'short',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
};
try {
return dateobj.toLocaleString(lang, options);
} catch (error) {
log.error('Something went horribly wrong while formating dates.', { error, filename, args, extra });
return dateobj.toISOString();
}
}
try {
return dateFNS.format(dateobj, datefmt, { locale });
} catch (error) {
log.error('Something went horribly wrong while formating dates.', { error, filename, args, extra });
return dateobj.toISOString();
}
};
}
2020-02-21 20:05:52 -08:00
}