File size: 2,015 Bytes
4e1096a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { detectLanguage, getLanguageInfo, isSameLang, isValidLang } from '@/utils/lang';
import type { Transformer } from './types';

export const languageTransformer: Transformer = {
  name: 'language',

  transform: async (ctx) => {
    const primaryLanguage = ctx.primaryLanguage;
    let result = ctx.content;
    const attrsMatch = result.match(/<html\b([^>]*)>/i);
    if (attrsMatch) {
      let attrs = attrsMatch[1] || '';
      const langRegex = / lang="([^"]*)"/i;
      const xmlLangRegex = / xml:lang="([^"]*)"/i;
      const xmlLangMatch = attrs.match(xmlLangRegex);
      const langMatch = attrs.match(langRegex);
      const docLang = langMatch?.[1] || xmlLangMatch?.[1];
      if (!isValidLang(docLang) || !isSameLang(docLang, primaryLanguage)) {
        const mainContent = result.replace(/<[^>]+>/g, ' ');
        const lang =
          isValidLang(primaryLanguage) && primaryLanguage !== 'en'
            ? primaryLanguage
            : detectLanguage(mainContent);
        const languageInfo = getLanguageInfo(lang || '');
        const newLangAttr = ` lang="${lang}"`;
        const newXmlLangAttr = ` xml:lang="${lang}"`;
        const dirAttr = languageInfo?.direction === 'rtl' ? ' dir="rtl"' : '';
        attrs = langMatch ? attrs.replace(langRegex, newLangAttr) : attrs + newLangAttr + dirAttr;
        attrs = xmlLangMatch
          ? attrs.replace(xmlLangRegex, newXmlLangAttr)
          : attrs + newXmlLangAttr + dirAttr;
        result = result.replace(attrsMatch[0], `<html${attrs}>`);
      }
    } else {
      const lang =
        isValidLang(primaryLanguage) && primaryLanguage !== 'en'
          ? primaryLanguage
          : detectLanguage(result.replace(/<[^>]+>/g, ' '));
      const languageInfo = getLanguageInfo(lang || '');
      const dirAttr = languageInfo?.direction === 'rtl' ? ' dir="rtl"' : '';
      const newAttrs = ` lang="${lang}" xml:lang="${lang}" ${dirAttr}`;
      result = result.replace(/<html>/i, `<html${newAttrs}>`);
    }
    return result;
  },
};