import-export.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. /* global API */// msg.js
  2. /* global RX_META deepEqual isEmptyObj tryJSONparse */// toolbox.js
  3. /* global changeQueue */// manage.js
  4. /* global chromeSync */// storage-util.js
  5. /* global prefs */
  6. /* global t */// localization.js
  7. /* global
  8. $
  9. $$
  10. $create
  11. animateElement
  12. messageBoxProxy
  13. scrollElementIntoView
  14. */// dom.js
  15. 'use strict';
  16. $('#file-all-styles').onclick = exportToFile;
  17. $('#unfile-all-styles').onclick = () => importFromFile({fileTypeFilter: '.json'});
  18. Object.assign(document.body, {
  19. ondragover(event) {
  20. const hasFiles = event.dataTransfer.types.includes('Files');
  21. event.dataTransfer.dropEffect = hasFiles || event.target.type === 'search' ? 'copy' : 'none';
  22. this.classList.toggle('dropzone', hasFiles);
  23. if (hasFiles) {
  24. event.preventDefault();
  25. this.classList.remove('fadeout');
  26. }
  27. },
  28. ondragend() {
  29. animateElement(this, 'fadeout', 'dropzone');
  30. },
  31. ondragleave(event) {
  32. try {
  33. // in Firefox event.target could be XUL browser and hence there is no permission to access it
  34. if (event.target === this) {
  35. this.ondragend();
  36. }
  37. } catch (e) {
  38. this.ondragend();
  39. }
  40. },
  41. ondrop(event) {
  42. if (event.dataTransfer.files.length) {
  43. event.preventDefault();
  44. if ($('#only-updates input').checked) {
  45. $('#only-updates input').click();
  46. }
  47. importFromFile({file: event.dataTransfer.files[0]});
  48. }
  49. /* Run import first for a while, then run fadeout which is very CPU-intensive in Chrome */
  50. setTimeout(() => this.ondragend(), 250);
  51. },
  52. });
  53. function importFromFile({fileTypeFilter, file} = {}) {
  54. return new Promise(async resolve => {
  55. await require(['/js/storage-util']);
  56. const fileInput = document.createElement('input');
  57. if (file) {
  58. readFile();
  59. return;
  60. }
  61. fileInput.style.display = 'none';
  62. fileInput.type = 'file';
  63. fileInput.accept = fileTypeFilter || '.txt';
  64. fileInput.acceptCharset = 'utf-8';
  65. document.body.appendChild(fileInput);
  66. fileInput.initialValue = fileInput.value;
  67. fileInput.onchange = readFile;
  68. fileInput.click();
  69. function readFile() {
  70. if (file || fileInput.value !== fileInput.initialValue) {
  71. file = file || fileInput.files[0];
  72. if (file.size > 100e6) {
  73. messageBoxProxy.alert("100MB backup? I don't believe you.");
  74. resolve();
  75. return;
  76. }
  77. const fReader = new FileReader();
  78. fReader.onloadend = event => {
  79. fileInput.remove();
  80. const text = event.target.result;
  81. const maybeUsercss = !/^\s*\[/.test(text) && RX_META.test(text);
  82. if (maybeUsercss) {
  83. messageBoxProxy.alert(t('dragDropUsercssTabstrip'));
  84. } else {
  85. importFromString(text).then(resolve);
  86. }
  87. };
  88. fReader.readAsText(file, 'utf-8');
  89. }
  90. }
  91. });
  92. }
  93. async function importFromString(jsonString) {
  94. await require(['/js/sections-util']); /* global styleJSONseemsValid styleSectionsEqual */
  95. const json = tryJSONparse(jsonString);
  96. const oldStyles = Array.isArray(json) && json.length ? await API.styles.getAll() : [];
  97. const oldStylesById = new Map(oldStyles.map(style => [style.id, style]));
  98. const oldStylesByName = new Map(oldStyles.map(style => [style.name.trim(), style]));
  99. const items = [];
  100. const infos = [];
  101. const stats = {
  102. options: {names: [], isOptions: true, legend: 'optionsHeading'},
  103. added: {names: [], ids: [], legend: 'importReportLegendAdded', dirty: true},
  104. unchanged: {names: [], ids: [], legend: 'importReportLegendIdentical'},
  105. metaAndCode: {names: [], ids: [], legend: 'importReportLegendUpdatedBoth', dirty: true},
  106. metaOnly: {names: [], ids: [], legend: 'importReportLegendUpdatedMeta', dirty: true},
  107. codeOnly: {names: [], ids: [], legend: 'importReportLegendUpdatedCode', dirty: true},
  108. invalid: {names: [], legend: 'importReportLegendInvalid'},
  109. };
  110. await Promise.all(json.map(analyze));
  111. changeQueue.length = 0;
  112. changeQueue.time = performance.now();
  113. (await API.styles.importMany(items))
  114. .forEach((style, i) => updateStats(style, infos[i]));
  115. return done();
  116. function analyze(item, index) {
  117. if (item && !item.id && item[prefs.STORAGE_KEY]) {
  118. return analyzeStorage(item);
  119. }
  120. if (typeof item !== 'object' || !styleJSONseemsValid(item)) {
  121. stats.invalid.names.push(`#${index}: ${limitString(item && item.name || '')}`);
  122. return;
  123. }
  124. item.name = item.name.trim();
  125. const byId = oldStylesById.get(item.id);
  126. const byName = oldStylesByName.get(item.name);
  127. oldStylesByName.delete(item.name);
  128. let oldStyle;
  129. if (byId) {
  130. if (sameStyle(byId, item)) {
  131. oldStyle = byId;
  132. } else {
  133. delete item.id;
  134. }
  135. }
  136. if (!oldStyle && byName) {
  137. item.id = byName.id;
  138. oldStyle = byName;
  139. }
  140. const metaEqual = oldStyle && deepEqual(oldStyle, item, ['sections', '_rev']);
  141. const codeEqual = oldStyle && styleSectionsEqual(oldStyle, item);
  142. if (metaEqual && codeEqual) {
  143. stats.unchanged.names.push(oldStyle.name);
  144. stats.unchanged.ids.push(oldStyle.id);
  145. } else {
  146. items.push(item);
  147. infos.push({oldStyle, metaEqual, codeEqual});
  148. }
  149. }
  150. async function analyzeStorage(storage) {
  151. analyzePrefs(storage[prefs.STORAGE_KEY], prefs.knownKeys, prefs.values, true);
  152. delete storage[prefs.STORAGE_KEY];
  153. if (!isEmptyObj(storage)) {
  154. analyzePrefs(storage, Object.values(chromeSync.LZ_KEY), await chromeSync.getLZValues());
  155. }
  156. }
  157. function analyzePrefs(obj, validKeys, values, isPref) {
  158. for (const [key, val] of Object.entries(obj || {})) {
  159. const isValid = validKeys.includes(key);
  160. if (!isValid || !deepEqual(val, values[key])) {
  161. stats.options.names.push({name: key, val, isValid, isPref});
  162. }
  163. }
  164. }
  165. function sameStyle(oldStyle, newStyle) {
  166. return oldStyle.name.trim() === newStyle.name.trim() ||
  167. ['updateUrl', 'originalMd5', 'originalDigest']
  168. .some(field => oldStyle[field] && oldStyle[field] === newStyle[field]);
  169. }
  170. function updateStats(style, {oldStyle, metaEqual, codeEqual}) {
  171. if (!oldStyle) {
  172. stats.added.names.push(style.name);
  173. stats.added.ids.push(style.id);
  174. return;
  175. }
  176. if (!metaEqual && !codeEqual) {
  177. stats.metaAndCode.names.push(reportNameChange(oldStyle, style));
  178. stats.metaAndCode.ids.push(style.id);
  179. return;
  180. }
  181. if (!codeEqual) {
  182. stats.codeOnly.names.push(style.name);
  183. stats.codeOnly.ids.push(style.id);
  184. return;
  185. }
  186. stats.metaOnly.names.push(reportNameChange(oldStyle, style));
  187. stats.metaOnly.ids.push(style.id);
  188. }
  189. function done() {
  190. scrollTo(0, 0);
  191. const entries = Object.entries(stats);
  192. const numChanged = entries.reduce((sum, [, val]) =>
  193. sum + (val.dirty ? val.names.length : 0), 0);
  194. const report = entries.map(renderStats).filter(Boolean);
  195. messageBoxProxy.show({
  196. title: t('importReportTitle'),
  197. className: 'center-dialog',
  198. contents: $create('#import', report.length ? report : t('importReportUnchanged')),
  199. buttons: [t('confirmClose'), numChanged && t('undo')],
  200. onshow: bindClick,
  201. })
  202. .then(({button}) => {
  203. if (button === 1) {
  204. undo();
  205. }
  206. });
  207. }
  208. function renderStats([id, {ids, names, legend, isOptions}]) {
  209. return names.length &&
  210. $create('details', {dataset: {id}, open: isOptions}, [
  211. $create('summary',
  212. $create('b', (isOptions ? '' : names.length + ' ') + t(legend))),
  213. $create('small',
  214. names.map(ids ? listItemsWithId : isOptions ? listOptions : listItems, ids)),
  215. isOptions && names.some(_ => _.isValid) &&
  216. $create('button', {onclick: importOptions}, t('importLabel')),
  217. ]);
  218. }
  219. function listOptions({name, isValid}) {
  220. return $create(isValid ? 'div' : 'del',
  221. name + (isValid ? '' : ` (${t(stats.invalid.legend)})`));
  222. }
  223. function listItems(name) {
  224. return $create('div', name);
  225. }
  226. /** @this stats.<item>.ids */
  227. function listItemsWithId(name, i) {
  228. return $create('div', {dataset: {id: this[i]}}, name);
  229. }
  230. async function importOptions() {
  231. const oldStorage = await chromeSync.get();
  232. for (const {name, val, isValid, isPref} of stats.options.names) {
  233. if (isValid) {
  234. if (isPref) {
  235. prefs.set(name, val);
  236. } else {
  237. chromeSync.setLZValue(name, val);
  238. }
  239. }
  240. }
  241. const label = this.textContent;
  242. this.textContent = t('undo');
  243. this.onclick = async () => {
  244. const curKeys = Object.keys(await chromeSync.get());
  245. const keysToRemove = curKeys.filter(k => !oldStorage.hasOwnProperty(k));
  246. await chromeSync.set(oldStorage);
  247. await chromeSync.remove(keysToRemove);
  248. this.textContent = label;
  249. this.onclick = importOptions;
  250. };
  251. }
  252. function undo() {
  253. const newIds = [
  254. ...stats.metaAndCode.ids,
  255. ...stats.metaOnly.ids,
  256. ...stats.codeOnly.ids,
  257. ...stats.added.ids,
  258. ];
  259. let tasks = Promise.resolve();
  260. for (const id of newIds) {
  261. tasks = tasks.then(() => API.styles.delete(id));
  262. const oldStyle = oldStylesById.get(id);
  263. if (oldStyle) {
  264. tasks = tasks.then(() => API.styles.importMany([oldStyle]));
  265. }
  266. }
  267. // taskUI is superfast and updates style list only in this page,
  268. // which should account for 99.99999999% of cases, supposedly
  269. return tasks.then(() => messageBoxProxy.show({
  270. title: t('importReportUndoneTitle'),
  271. contents: newIds.length + ' ' + t('importReportUndone'),
  272. buttons: [t('confirmClose')],
  273. }));
  274. }
  275. function bindClick() {
  276. const highlightElement = event => {
  277. const styleElement = $('#style-' + event.target.dataset.id);
  278. if (styleElement) {
  279. scrollElementIntoView(styleElement);
  280. animateElement(styleElement);
  281. }
  282. };
  283. for (const block of $$('#message-box details')) {
  284. if (block.dataset.id !== 'invalid') {
  285. block.style.cursor = 'pointer';
  286. block.onclick = highlightElement;
  287. }
  288. }
  289. }
  290. function limitString(s, limit = 100) {
  291. return s.length <= limit ? s : s.substr(0, limit) + '...';
  292. }
  293. function reportNameChange(oldStyle, newStyle) {
  294. return newStyle.name !== oldStyle.name
  295. ? oldStyle.name + ' —> ' + newStyle.name
  296. : oldStyle.name;
  297. }
  298. }
  299. async function exportToFile() {
  300. await require(['/js/storage-util']);
  301. const data = [
  302. Object.assign({
  303. [prefs.STORAGE_KEY]: prefs.values,
  304. }, await chromeSync.getLZValues()),
  305. ...await API.styles.getAll(),
  306. ];
  307. const text = JSON.stringify(data, null, ' ');
  308. const type = 'application/json';
  309. $create('a', {
  310. href: URL.createObjectURL(new Blob([text], {type})),
  311. download: generateFileName(),
  312. type,
  313. }).dispatchEvent(new MouseEvent('click'));
  314. function generateFileName() {
  315. const today = new Date();
  316. const dd = ('0' + today.getDate()).substr(-2);
  317. const mm = ('0' + (today.getMonth() + 1)).substr(-2);
  318. const yyyy = today.getFullYear();
  319. return `stylus-${yyyy}-${mm}-${dd}.json`;
  320. }
  321. }