so://phie

outline

A web-based drawing app
git clone git://soophie.de/outline

blob: 703104d5316188e8986ecca171789edc9cde8e26 (2358 bytes)[doc][blame][raw]

1const LINE_BREAK_PATTERN = /\r\n|\r|\n/;

2const PROPERTY_PATTERN = /^([\w+.-]+)=([^=]*)$/;

3

4let lang = {};

5let default_lang;

6let current_lang;

7

8/**

9 Sets the default and current language.

10

11 @function init

12 @constructor

13 @param {string} code - The locale code;

14*/

15function init(code) {

16 default_lang = code;

17 current_lang = code;

18}

19

20/**

21 Reads all properties files in the given directory and specified locale code.

22

23 @async

24 @function load

25 @param {string} path - The path to the locale files.

26 @param {string[]} locales - The list containing all locales.

27 @return {Object} The locale object.

28*/

29async function load(path, locales) {

30 for(let code of locales) {

31 let text = await fetch(`${path}/${code}.properties`)

32 .then(function(response) {

33 if(!response.ok) {

34 throw new Error('(404) Not Found');

35 }

36 return response.text();

37 })

38 .catch(function(error) {

39 console.error(`No properties file found for locale '${code}'!`, error);

40 });

41 if(text) {

42 lang[code] = parse(text);

43 }

44 }

45}

46

47/**

48 Converts properties text to a locale object.

49

50 @function parse

51 @param {string} text - Raw properties text data.

52 @return {Object} The locale object.

53*/

54function parse(text) {

55 let result = {};

56 for(let line of text.split(LINE_BREAK_PATTERN)) {

57 let match = PROPERTY_PATTERN.exec(line);

58 if(match) {

59 result[match[1]] = match[2];

60 }

61 }

62 return result;

63}

64

65/**

66 Returns the locale object by the given locale code.

67

68 @function change

69 @return {Object} The locale object.

70*/

71function get() {

72 return lang[current_lang];

73}

74

75/**

76 Changes language text from all HTMLElements with the specified datatag.

77

78 @function change

79 @param {string} code - The local code.

80*/

81function change(code) {

82 if(lang[code]) {

83 current_lang = code;

84 let elements = document.querySelectorAll('[data-lang]');

85 for(let item of elements) {

86 let content = lang[code][item.dataset.lang];

87 if(content) {

88 let type = item.dataset.type || 'content';

89 let badge;

90 if(item.dataset.badge === 'true') {

91 badge = item.querySelector('.badge');

92 }

93 switch(type) {

94 case 'content':

95 item.textContent = content;

96 if(badge) {

97 item.append(badge);

98 }

99 break;

100 case 'tooltip':

101 item.dataset.title = content;

102 break;

103 default:

104 break;

105 }

106 }

107 }

108 }

109}

110

111export default { init, load, parse, get, change };