index.js 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. export function i18n(name, args) {
  2. return browser.i18n.getMessage(name, args) || name;
  3. }
  4. export const defaultImage = '/public/images/icon128.png';
  5. export function normalizeKeys(key) {
  6. let keys = key || [];
  7. if (!Array.isArray(keys)) keys = keys.toString().split('.');
  8. return keys;
  9. }
  10. export const object = {
  11. get(obj, rawKey, def) {
  12. const keys = normalizeKeys(rawKey);
  13. let res = obj;
  14. keys.some((key) => {
  15. if (res && typeof res === 'object' && (key in res)) {
  16. res = res[key];
  17. } else {
  18. res = def;
  19. return true;
  20. }
  21. });
  22. return res;
  23. },
  24. set(obj, rawKey, val) {
  25. const keys = normalizeKeys(rawKey);
  26. if (!keys.length) return val;
  27. const root = obj || {};
  28. let sub = root;
  29. const lastKey = keys.pop();
  30. keys.forEach((key) => {
  31. let child = sub[key];
  32. if (!child) {
  33. child = {};
  34. sub[key] = child;
  35. }
  36. sub = child;
  37. });
  38. if (val == null) {
  39. delete sub[lastKey];
  40. } else {
  41. sub[lastKey] = val;
  42. }
  43. return obj;
  44. },
  45. };
  46. export function initHooks() {
  47. const hooks = [];
  48. function fire(data) {
  49. hooks.slice().forEach((cb) => {
  50. cb(data);
  51. });
  52. }
  53. function hook(callback) {
  54. hooks.push(callback);
  55. return () => {
  56. const i = hooks.indexOf(callback);
  57. if (i >= 0) hooks.splice(i, 1);
  58. };
  59. }
  60. return { hook, fire };
  61. }
  62. export function sendMessage(payload) {
  63. const promise = browser.runtime.sendMessage(payload)
  64. .then(res => {
  65. const { data, error } = res || {};
  66. if (error) return Promise.reject(error);
  67. return data;
  68. });
  69. promise.catch((err) => {
  70. if (process.env.DEBUG) console.warn(err);
  71. });
  72. return promise;
  73. }
  74. export function debounce(func, time) {
  75. let timer;
  76. function run(thisObj, args) {
  77. timer = null;
  78. func.apply(thisObj, args);
  79. }
  80. return function debouncedFunction(...args) {
  81. if (timer) clearTimeout(timer);
  82. timer = setTimeout(run, time, this, args);
  83. };
  84. }
  85. export function noop() {}
  86. export function zfill(input, length) {
  87. let num = input.toString();
  88. while (num.length < length) num = `0${num}`;
  89. return num;
  90. }
  91. export function getUniqId() {
  92. return Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
  93. }
  94. /**
  95. * Get locale attributes such as `@name:zh-CN`
  96. */
  97. export function getLocaleString(meta, key) {
  98. const localeMeta = navigator.languages
  99. // Use `lang.toLowerCase()` since v2.6.5
  100. .map(lang => meta[`${key}:${lang}`] || meta[`${key}:${lang.toLowerCase()}`])
  101. .find(Boolean);
  102. return localeMeta || meta[key] || '';
  103. }
  104. const binaryTypes = [
  105. 'blob',
  106. 'arraybuffer',
  107. ];
  108. /**
  109. * Make a request.
  110. * @param {String} url
  111. * @param {Object} headers
  112. * @return Promise
  113. */
  114. export function request(url, options = {}) {
  115. return new Promise((resolve, reject) => {
  116. const xhr = new XMLHttpRequest();
  117. const { responseType } = options;
  118. xhr.open(options.method || 'GET', url, true);
  119. if (binaryTypes.includes(responseType)) xhr.responseType = responseType;
  120. const headers = Object.assign({}, options.headers);
  121. let { body } = options;
  122. if (body && typeof body === 'object') {
  123. headers['Content-Type'] = 'application/json';
  124. body = JSON.stringify(body);
  125. }
  126. Object.keys(headers).forEach(key => {
  127. xhr.setRequestHeader(key, headers[key]);
  128. });
  129. xhr.onload = () => {
  130. const res = getResponse(xhr, {
  131. // status for `file:` protocol will always be `0`
  132. status: xhr.status || 200,
  133. });
  134. if (res.status > 300) reject(res);
  135. else resolve(res);
  136. };
  137. xhr.onerror = () => {
  138. const res = getResponse(xhr, { status: -1 });
  139. reject(res);
  140. };
  141. xhr.onabort = xhr.onerror;
  142. xhr.ontimeout = xhr.onerror;
  143. xhr.send(body);
  144. });
  145. function getResponse(xhr, extra) {
  146. const { responseType } = options;
  147. let data;
  148. if (binaryTypes.includes(responseType)) {
  149. data = xhr.response;
  150. } else {
  151. data = xhr.responseText;
  152. }
  153. if (responseType === 'json') {
  154. try {
  155. data = JSON.parse(data);
  156. } catch (e) {
  157. // Ignore invalid JSON
  158. }
  159. }
  160. return Object.assign({
  161. url,
  162. data,
  163. xhr,
  164. }, extra);
  165. }
  166. }
  167. export function buffer2string(buffer) {
  168. const array = new window.Uint8Array(buffer);
  169. const sliceSize = 8192;
  170. let str = '';
  171. for (let i = 0; i < array.length; i += sliceSize) {
  172. str += String.fromCharCode.apply(null, array.subarray(i, i + sliceSize));
  173. }
  174. return str;
  175. }
  176. export function getFullUrl(url, base) {
  177. const obj = new URL(url, base);
  178. // Do not allow `file:` protocol
  179. if (obj.protocol === 'file:') obj.protocol = 'http:';
  180. return obj.href;
  181. }
  182. export function isRemote(url) {
  183. return url && !(/^(file|data):/.test(url));
  184. }