Translate page progressively - parallel chunks, swap text as each batch returns
This commit is contained in:
+13
-12
@@ -49,22 +49,23 @@
|
|||||||
var uniq=[],idx={};
|
var uniq=[],idx={};
|
||||||
nodes.forEach(function(n){ var t=n.nodeValue.trim(); if(!(t in idx)&&memo[t]==null){ idx[t]=uniq.length; uniq.push(t);} });
|
nodes.forEach(function(n){ var t=n.nodeValue.trim(); if(!(t in idx)&&memo[t]==null){ idx[t]=uniq.length; uniq.push(t);} });
|
||||||
var chunks=[]; for(var i=0;i<uniq.length;i+=20)chunks.push(uniq.slice(i,i+20));
|
var chunks=[]; for(var i=0;i<uniq.length;i+=20)chunks.push(uniq.slice(i,i+20));
|
||||||
var p=Promise.resolve();
|
function apply(){
|
||||||
chunks.forEach(function(ch){
|
|
||||||
p=p.then(function(){
|
|
||||||
return fetch('/api/public/translate',{method:'POST',headers:{'Content-Type':'application/json'},
|
|
||||||
body:JSON.stringify({tl:lang,texts:ch})}).then(function(r){return r.json()}).then(function(d){
|
|
||||||
if(d&&Array.isArray(d.t))ch.forEach(function(t,j){ memo[t]=d.t[j]; });
|
|
||||||
}).catch(function(){});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
p.then(function(){
|
|
||||||
saveMemo();
|
|
||||||
nodes.forEach(function(n){
|
nodes.forEach(function(n){
|
||||||
var raw=n.nodeValue,t=raw.trim(),tr=memo[t];
|
var raw=n.nodeValue,t=raw.trim(),tr=memo[t];
|
||||||
if(tr&&tr!==t){ n.nodeValue=raw.replace(t,tr); }
|
if(tr&&tr!==t){ n.nodeValue=raw.replace(t,tr); }
|
||||||
n.__rmcTr=lang;
|
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
apply(); // whatever the memo already covers shows instantly
|
||||||
|
// parallel chunks, each swapped in the moment it returns — a first-ever
|
||||||
|
// page+language visit translates progressively instead of all-at-the-end
|
||||||
|
Promise.all(chunks.map(function(ch){
|
||||||
|
return fetch('/api/public/translate',{method:'POST',headers:{'Content-Type':'application/json'},
|
||||||
|
body:JSON.stringify({tl:lang,texts:ch})}).then(function(r){return r.json()}).then(function(d){
|
||||||
|
if(d&&Array.isArray(d.t)){ ch.forEach(function(t,j){ memo[t]=d.t[j]; }); apply(); }
|
||||||
|
}).catch(function(){});
|
||||||
|
})).then(function(){
|
||||||
|
saveMemo();
|
||||||
|
nodes.forEach(function(n){ n.__rmcTr=lang; });
|
||||||
busy=false;
|
busy=false;
|
||||||
if(queued){queued=false;translatePage();}
|
if(queued){queued=false;translatePage();}
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user