so://phie

outline

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

blob: 0f29b3c1e66b17e73ada9a89b2e692f947b4289d (2525 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 current locale.

67

68 @function get_current

69 @return {string} The current locale.

70*/

71function get_current() {

72 return current_lang;

73}

74

75/**

76 Returns the locale object by the given locale code.

77

78 @function change

79 @return {Object} The locale object.

80*/

81function get() {

82 return lang[current_lang];

83}

84

85/**

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

87

88 @function change

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

90*/

91function change(code) {

92 if(lang[code]) {

93 current_lang = code;

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

95 for(let item of elements) {

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

97 if(content) {

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

99 let badge;

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

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

102 }

103 switch(type) {

104 case 'content':

105 item.textContent = content;

106 if(badge) {

107 item.append(badge);

108 }

109 break;

110 case 'tooltip':

111 item.dataset.title = content;

112 break;

113 default:

114 break;

115 }

116 }

117 }

118 }

119}

120

121export default {

122 init,

123 load,

124 parse,

125 get_current,

126 get,

127 change

128};