From 54f5c5ed945938b2fd0b0c4df1cdff7179f2e717 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Thuret?= Date: Mon, 7 Feb 2022 17:58:30 +0100 Subject: [PATCH] keep selected languages and text in url --- app/static/js/app.js | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/app/static/js/app.js b/app/static/js/app.js index 8e597a4..f33aca8 100644 --- a/app/static/js/app.js +++ b/app/static/js/app.js @@ -82,6 +82,24 @@ document.addEventListener('DOMContentLoaded', function(){ return; } + const sourceLanguage = self.langs.find(l => l.code === self.getQueryParam('source')) + const isSourceAuto = !sourceLanguage && self.getQueryParam('source') === "auto" + const targetLanguage = self.langs.find(l => l.code === self.getQueryParam('target')) + + if (sourceLanguage || isSourceAuto) { + self.sourceLang = isSourceAuto ? "auto" : sourceLanguage.code + } + + if (targetLanguage) { + self.targetLang = targetLanguage.code + } + + const defaultText = self.getQueryParam('q') + + if(defaultText) { + self.inputText = decodeURI(defaultText) + } + self.loading = false; } else { self.error = "Cannot load /languages"; @@ -195,9 +213,23 @@ document.addEventListener('DOMContentLoaded', function(){ dismissError: function(){ this.error = ''; }, + getQueryParam: function (key) { + const params = new URLSearchParams(window.location.search); + return params.get(key) + }, + updateQueryParam: function (key, value) { + let searchParams = new URLSearchParams(window.location.search) + searchParams.set(key, value); + let newRelativePathQuery = window.location.pathname + '?' + searchParams.toString(); + history.pushState(null, '', newRelativePathQuery); + }, handleInput: function(e){ this.closeSuggestTranslation(e) + this.updateQueryParam('source', this.sourceLang) + this.updateQueryParam('target', this.targetLang) + this.updateQueryParam('q', encodeURI(this.inputText)) + if (this.timeout) clearTimeout(this.timeout); this.timeout = null;