From b1c39ab9dfd9990c5c07635a4fee122e678add84 Mon Sep 17 00:00:00 2001 From: Przemek Wiech Date: Fri, 20 Mar 2020 18:55:01 +0100 Subject: [PATCH] Updates --- asset-manifest.json | 6 +++--- index.html | 2 +- ... precache-manifest.4a7e1e8cb9e950bae835bcd27e7b5383.js | 8 ++++---- service-worker.js | 2 +- static/js/main.746434fe.chunk.js | 2 -- static/js/main.746434fe.chunk.js.map | 1 - static/js/main.a40a575c.chunk.js | 2 ++ static/js/main.a40a575c.chunk.js.map | 1 + 8 files changed, 12 insertions(+), 12 deletions(-) rename precache-manifest.79946525ba07b0360f1e6b3481a6571e.js => precache-manifest.4a7e1e8cb9e950bae835bcd27e7b5383.js (92%) delete mode 100644 static/js/main.746434fe.chunk.js delete mode 100644 static/js/main.746434fe.chunk.js.map create mode 100644 static/js/main.a40a575c.chunk.js create mode 100644 static/js/main.a40a575c.chunk.js.map diff --git a/asset-manifest.json b/asset-manifest.json index 8960212..8ddaaf0 100644 --- a/asset-manifest.json +++ b/asset-manifest.json @@ -1,15 +1,15 @@ { "files": { "main.css": "./static/css/main.0089abb2.chunk.css", - "main.js": "./static/js/main.746434fe.chunk.js", - "main.js.map": "./static/js/main.746434fe.chunk.js.map", + "main.js": "./static/js/main.a40a575c.chunk.js", + "main.js.map": "./static/js/main.a40a575c.chunk.js.map", "runtime~main.js": "./static/js/runtime~main.d653cc00.js", "runtime~main.js.map": "./static/js/runtime~main.d653cc00.js.map", "static/css/2.9c7c3dac.chunk.css": "./static/css/2.9c7c3dac.chunk.css", "static/js/2.f2cc1826.chunk.js": "./static/js/2.f2cc1826.chunk.js", "static/js/2.f2cc1826.chunk.js.map": "./static/js/2.f2cc1826.chunk.js.map", "index.html": "./index.html", - "precache-manifest.79946525ba07b0360f1e6b3481a6571e.js": "./precache-manifest.79946525ba07b0360f1e6b3481a6571e.js", + "precache-manifest.4a7e1e8cb9e950bae835bcd27e7b5383.js": "./precache-manifest.4a7e1e8cb9e950bae835bcd27e7b5383.js", "service-worker.js": "./service-worker.js", "static/css/2.9c7c3dac.chunk.css.map": "./static/css/2.9c7c3dac.chunk.css.map", "static/css/main.0089abb2.chunk.css.map": "./static/css/main.0089abb2.chunk.css.map", diff --git a/index.html b/index.html index ad0dab8..c84376b 100644 --- a/index.html +++ b/index.html @@ -1 +1 @@ -Topola Genealogy Viewer
\ No newline at end of file +Topola Genealogy Viewer
\ No newline at end of file diff --git a/precache-manifest.79946525ba07b0360f1e6b3481a6571e.js b/precache-manifest.4a7e1e8cb9e950bae835bcd27e7b5383.js similarity index 92% rename from precache-manifest.79946525ba07b0360f1e6b3481a6571e.js rename to precache-manifest.4a7e1e8cb9e950bae835bcd27e7b5383.js index d691eb9..58b3a9a 100644 --- a/precache-manifest.79946525ba07b0360f1e6b3481a6571e.js +++ b/precache-manifest.4a7e1e8cb9e950bae835bcd27e7b5383.js @@ -1,6 +1,6 @@ self.__precacheManifest = (self.__precacheManifest || []).concat([ { - "revision": "77e50d732c8e852933ffd6c3682a4363", + "revision": "d507a45742137ae145794f6559260530", "url": "./index.html" }, { @@ -8,7 +8,7 @@ self.__precacheManifest = (self.__precacheManifest || []).concat([ "url": "./static/css/2.9c7c3dac.chunk.css" }, { - "revision": "207f7065139c45d9e6b0", + "revision": "a5a53895eca199630fb5", "url": "./static/css/main.0089abb2.chunk.css" }, { @@ -16,8 +16,8 @@ self.__precacheManifest = (self.__precacheManifest || []).concat([ "url": "./static/js/2.f2cc1826.chunk.js" }, { - "revision": "207f7065139c45d9e6b0", - "url": "./static/js/main.746434fe.chunk.js" + "revision": "a5a53895eca199630fb5", + "url": "./static/js/main.a40a575c.chunk.js" }, { "revision": "8c97409f0ee389fe75da", diff --git a/service-worker.js b/service-worker.js index 6f0a277..917b1b2 100644 --- a/service-worker.js +++ b/service-worker.js @@ -14,7 +14,7 @@ importScripts("https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js"); importScripts( - "./precache-manifest.79946525ba07b0360f1e6b3481a6571e.js" + "./precache-manifest.4a7e1e8cb9e950bae835bcd27e7b5383.js" ); self.addEventListener('message', (event) => { diff --git a/static/js/main.746434fe.chunk.js b/static/js/main.746434fe.chunk.js deleted file mode 100644 index c644447..0000000 --- a/static/js/main.746434fe.chunk.js +++ /dev/null @@ -1,2 +0,0 @@ -(window.webpackJsonp=window.webpackJsonp||[]).push([[0],{252:function(e){e.exports={"menu.load_from_url":"Otw\xf3rz URL","menu.load_from_file":"Otw\xf3rz plik","menu.print":"Drukuj","menu.download":"Pobierz","menu.pdf_file":"Plik PDF","menu.png_file":"Plik PNG","menu.svg_file":"Plik SVG","menu.view":"Widok","menu.hourglass":"Wykres klepsydrowy","menu.relatives":"Wszyscy krewni","menu.fancy":"Ozdobne drzewo (eksperymentalne)","menu.wikitree_login":"Zaloguj do WikiTree","menu.wikitree_logged_in":"Zalogowano","menu.wikitree_popup_username":"Zalogowano do WikiTree jako {username}","menu.wikitree_popup":"Zalogowano do WikiTree","menu.github":"\u0179r\xf3d\u0142a na GitHub","menu.powered_by":"Topola Genealogy","menu.search.placeholder":"Szukaj osoby","menu.search.no_results":"Brak wynik\xf3w","intro.title":"Topola Genealogy","intro.description":"Topola Genealogy pozwala przegl\u0105da\u0107 drzewo genealogiczne w interaktywny spos\xf3b.","intro.instructions":"Kliknij OTW\xd3RZ URL lub OTW\xd3RZ PLIK, aby za\u0142adowa\u0107 plik GEDCOM. Wi\u0119kszo\u015b\u0107 program\xf3w genealogicznych posiada funkcj\u0119 eksportu do pliku GEDCOM.","intro.examples":"Poni\u017cej jest kilka przyk\u0142ad\xf3w znalezionych w Internecie:","intro.from":"\u017ar\xf3d\u0142o:","intro.privacy":"Prywatno\u015b\u0107","intro.privacy_note":'U\u017cywaj\u0105c funkcji "Otw\xf3rz plik", Twoje dane nie s\u0105 nigdzie wysy\u0142ane i pozostaj\u0105 na Twoim komputerze. U\u017cywaj\u0105c funkcji "Otw\xf3rz URL", dane z podanego adresu przesy\u0142ane s\u0105 przez us\u0142ug\u0119 {link} w celu umo\u017cliwienia za\u0142adowania danych z innej domeny (CORS).',"load_from_url.title":"Otw\xf3rz z adresu URL","load_from_url.comment":"Dane z podanego adresu URL zostan\u0105 za\u0142adowane poprzez us\u0142ug\u0119 {link} w celu unikni\u0119cia problem\xf3w z CORS.","load_from_url.cancel":"Anuluj","load_from_url.load":"Otw\xf3rz","gedcom.BAPM":"Chrzest","gedcom.BIRT":"Narodziny","gedcom.BURI":"Pogrzeb","gedcom.CHR":"Chrzest","gedcom.DEAT":"\u015amier\u0107","gedcom.EMAIL":"E-mail","gedcom.EVEN":"Wydarzenie","gedcom.OCCU":"Zaw\xf3d","gedcom.TITL":"Tytu\u0142","gedcom.WWW":"Strona WWW","date.abt":"oko\u0142o","date.cal":"wyliczone","date.est":"oszacowane","date.between":"mi\u0119dzy {from} a {to}","date.after":"po {from}","date.before":"przed {to}","error.error":"B\u0142\u0105d","error.failed_pdf":"Nie uda\u0142o si\u0119 utworzy\u0107 pliku PDF. Spr\xf3buj jeszcze raz z mniejszym diagramem lub pobierz plik SVG.","error.failed_png":"Nie uda\u0142o si\u0119 utworzy\u0107 pliku PNG. Spr\xf3buj jeszcze raz z mniejszym diagramem lub pobierz plik SVG.","error.failed_to_load_file":"B\u0142\u0105d wczytywania pliku"}},253:function(e,t){},260:function(e,t,n){e.exports=n.p+"static/media/topola.060eef13.jpg"},297:function(e,t,n){e.exports=n(528)},309:function(e,t){},315:function(e,t){},525:function(e,t,n){},528:function(e,t,n){"use strict";n.r(t);var a=n(44),r=n(250),i=n(251),o=n(0),s=n(64),c=n(252),l=n(16),u=n(39),d=n(37),f=n(40),m=n(65),p=n(14),h=n.n(p),g=n(18),v=n(27),w=n(28),b=n(32);function E(e,t){window.gtag("event",e,t)}var y,k=n(17),O=n(255),x=n.n(O),S=n(168),D=n(33),j=n(553);function M(e){var t=new FileReader;return t.readAsDataURL(e),new Promise(function(e,n){t.onload=function(t){return e(t.target.result)}})}function _(e){return T.apply(this,arguments)}function T(){return(T=Object(g.a)(h.a.mark(function e(t){var n,a,r,i;return h.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(n=t.href.baseVal){e.next=3;break}return e.abrupt("return");case 3:return e.prev=3,e.next=6,fetch(n);case 6:return a=e.sent,e.next=9,a.blob();case 9:return r=e.sent,e.next=12,M(r);case 12:i=e.sent,t.href.baseVal=i,e.next=19;break;case 16:e.prev=16,e.t0=e.catch(3),console.warn("Failed to load image:",e.t0);case 19:case"end":return e.stop()}},e,null,[[3,16]])}))).apply(this,arguments)}function R(e){return N.apply(this,arguments)}function N(){return(N=Object(g.a)(h.a.mark(function e(t){var n;return h.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=Array.from(t.getElementsByTagName("image")),e.next=3,Promise.all(n.map(_));case 3:case"end":return e.stop()}},e)}))).apply(this,arguments)}function L(e){var t=new Image;return t.src=URL.createObjectURL(e),new Promise(function(e,n){t.addEventListener("load",function(){return e(t)})})}function C(e){var t=document.createElement("canvas");t.width=2*e.width,t.height=2*e.height;var n=t.getContext("2d"),a=n.fillStyle;return n.fillStyle="white",n.fillRect(0,0,t.width,t.height),n.fillStyle=a,n.drawImage(e,0,0,t.width,t.height),t}function z(e,t){return new Promise(function(n,a){e.toBlob(function(e){e?n(e):a()},t)})}!function(e){e[e.Hourglass=0]="Hourglass",e[e.Relatives=1]="Relatives",e[e.Fancy=2]="Fancy"}(y||(y={}));var I=function(e){function t(){var e,n;Object(v.a)(this,t);for(var a=arguments.length,r=new Array(a),i=0;i0&&void 0!==arguments[0]?arguments[0]:{initialRender:!1};if(t.initialRender||!this.animating){t.initialRender?(k.select("#chart").node().innerHTML="",this.chart=Object(D.createChart)({json:this.props.data,chartType:this.getChartType(),renderer:this.getRendererType(),svgSelector:"#chart",indiCallback:function(t){return e.props.onSelection(t)},animate:!0,updateSvgSize:!1,locale:this.context.intl.locale})):this.chart.setData(this.props.data);var n=this.chart.render({startIndi:this.props.selection.id,baseGeneration:this.props.selection.generation}),a=k.select("#chartSvg"),r=k.select("#svgContainer").node(),i=this.props.enableZoom?k.zoomTransform(r).k:1,o=k.min([1,i,r.clientWidth/n.size[0],r.clientHeight/n.size[1]]),s=this.props.enableZoom?[k.max([.1,o]),2]:[1,1];this.zoomBehavior=k.zoom().scaleExtent(s).translateExtent([[0,0],n.size]).on("zoom",function(){return function(e,t){var n=k.select("#svgContainer").node();if(t){var a=k.event.transform.k,r=k.max([0,(n.clientWidth-e[0]*a)/2]),i=k.max([0,(n.clientHeight-e[1]*a)/2]);k.select("#chartSvg").attr("width",e[0]*a).attr("height",e[1]*a).attr("transform","translate(".concat(r,", ").concat(i,")")),k.select("#chart").attr("transform","scale(".concat(a,")"))}n.scrollLeft=-k.event.transform.x,n.scrollTop=-k.event.transform.y}(n.size,e.props.enableZoom)}),k.select(r).on("scroll",function(){return function(e){var t=k.select("#svgContainer").node(),n=t.scrollLeft+t.clientWidth/2,a=t.scrollTop+t.clientHeight/2,r=e?k.zoomTransform(t).k:1;k.select(t).call(k.zoom().translateTo,n/r,a/r)}(e.props.enableZoom)}).call(this.zoomBehavior);var c,l,u=r.clientWidth/2-n.origin[0]*i,d=r.clientHeight/2-n.origin[1]*i,f=k.max([0,(r.clientWidth-n.size[0]*i)/2]),m=k.max([0,(r.clientHeight-n.size[1]*i)/2]),p=a.transition().delay(200).duration(500);(t.initialRender?a:p).attr("transform","translate(".concat(f,", ").concat(m,")")).attr("width",n.size[0]*i).attr("height",n.size[1]*i),t.initialRender?(r.scrollLeft=-u,r.scrollTop=-d):p.tween("scrollLeft",(l=-u,function(){var e=k.interpolateNumber(r.scrollLeft,l);return function(t){r.scrollLeft=e(t)}})).tween("scrollTop",(c=-d,function(){var e=k.interpolateNumber(r.scrollTop,c);return function(t){r.scrollTop=e(t)}})),this.animating=!0,n.animationPromise.then(function(){e.animating=!1,e.rerenderRequired&&(e.rerenderRequired=!1,e.renderChart({initialRender:!1}))})}else this.rerenderRequired=!0}},{key:"componentDidMount",value:function(){this.renderChart({initialRender:!0})}},{key:"componentDidUpdate",value:function(e){var t=this.props.chartType!==e.chartType;this.renderChart({initialRender:t})}},{key:"render",value:function(){var e=this;return o.createElement("div",{id:"svgContainer"},this.props.enableZoom?o.createElement(j.a,{minWidth:768,className:"zoom"},o.createElement("button",{className:"zoom-in",onClick:function(){return e.zoom(1.3)}},"+"),o.createElement("button",{className:"zoom-out",onClick:function(){return e.zoom(1/1.3)}},"\u2212")):null,o.createElement("svg",{id:"chartSvg"},o.createElement("g",{id:"chart"})))}},{key:"getStrippedSvg",value:function(){var e=document.getElementById("chartSvg").cloneNode(!0);if(e.removeAttribute("transform"),this.props.enableZoom){var t=k.select("#svgContainer").node(),n=k.zoomTransform(t).k;e.setAttribute("width",String(Number(e.getAttribute("width"))/n)),e.setAttribute("height",String(Number(e.getAttribute("height"))/n)),e.querySelector("#chart").removeAttribute("transform")}return e}},{key:"getSvgContents",value:function(){return(new XMLSerializer).serializeToString(this.getStrippedSvg())}},{key:"getSvgContentsWithInlinedImages",value:function(){var e=Object(g.a)(h.a.mark(function e(){var t;return h.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.getStrippedSvg(),e.next=3,R(t);case 3:return e.abrupt("return",(new XMLSerializer).serializeToString(t));case 4:case"end":return e.stop()}},e,this)}));return function(){return e.apply(this,arguments)}}()},{key:"print",value:function(){var e=this,t=document.createElement("iframe");t.style.position="absolute",t.style.top="-1000px",t.style.left="-1000px",t.onload=function(){t.contentDocument.open(),t.contentDocument.write(e.getSvgContents()),t.contentDocument.close(),setTimeout(function(){t.contentWindow.focus(),t.contentWindow.print(),t.parentNode.removeChild(t)},500)},document.body.appendChild(t)}},{key:"downloadSvg",value:function(){var e=Object(g.a)(h.a.mark(function e(){var t,n;return h.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getSvgContentsWithInlinedImages();case 2:t=e.sent,n=new Blob([t],{type:"image/svg+xml"}),Object(S.saveAs)(n,"topola.svg");case 5:case"end":return e.stop()}},e,this)}));return function(){return e.apply(this,arguments)}}()},{key:"drawOnCanvas",value:function(){var e=Object(g.a)(h.a.mark(function e(){var t,n;return h.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getSvgContentsWithInlinedImages();case 2:return t=e.sent,n=new Blob([t],{type:"image/svg+xml"}),e.t0=C,e.next=7,L(n);case 7:return e.t1=e.sent,e.next=10,(0,e.t0)(e.t1);case 10:return e.abrupt("return",e.sent);case 11:case"end":return e.stop()}},e,this)}));return function(){return e.apply(this,arguments)}}()},{key:"downloadPng",value:function(){var e=Object(g.a)(h.a.mark(function e(){var t,n;return h.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.drawOnCanvas();case 2:return t=e.sent,e.next=5,z(t,"image/png");case 5:n=e.sent,Object(S.saveAs)(n,"topola.png");case 7:case"end":return e.stop()}},e,this)}));return function(){return e.apply(this,arguments)}}()},{key:"downloadPdf",value:function(){var e=Object(g.a)(h.a.mark(function e(){var t,n;return h.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.drawOnCanvas();case 2:t=e.sent,(n=new x.a({orientation:t.width>t.height?"l":"p",unit:"pt",format:[t.width,t.height]})).addImage(t,"PNG",0,0,t.width,t.height,"NONE"),n.save("topola.pdf");case 6:case"end":return e.stop()}},e,this)}));return function(){return e.apply(this,arguments)}}()}]),t}(o.PureComponent);I.contextTypes={intl:l.d};var P=n(258),W=n.n(P),U=n(259),A=n.n(U),F=n(164);function G(e){return e.substring(1,e.length-1)}function B(e){var t=e.find(function(e){return"HEAD"===e.tag}),n={},a={},r={};return e.forEach(function(e){"INDI"===e.tag?n[G(e.pointer)]=e:"FAM"===e.tag?a[G(e.pointer)]=e:e.pointer&&(r[G(e.pointer)]=e)}),{head:t,indis:n,fams:a,other:r}}function H(e,t){return et?1:0}function Z(e,t){var n=e&&(e.date||e.dateRange&&e.dateRange.from),a=t&&(t.date||t.dateRange&&t.dateRange.from);return n&&n.year&&a&&a.year?n.year!==a.year?n.year-a.year:n.month&&a.month?n.month!==a.month?n.month-a.month:n.day&&a.day&&n.day!==a.day?n.month-a.month:0:0:0}function V(e){var t=function(e){var t=new Map;return e.indis.forEach(function(e){t[e.id]=e}),function(e,n){var a=t[e],r=t[n];return Z(a&&a.birth,r&&r.birth)||H(e,n)}}(e),n=e.fams.map(function(e){return function(e,t){if(!e.children)return e;var n=e.children.sort(t);return Object.assign({},e,{children:n})}(e,t)});return Object.assign({},e,{fams:n})}function K(e){var t=function(e){var t=new Map;return e.fams.forEach(function(e){t[e.id]=e}),function(e,n){var a=t[e],r=t[n];return Z(a&&a.marriage,r&&r.marriage)||H(e,n)}}(e),n=e.indis.map(function(e){return function(e,t){if(!e.fams)return e;var n=e.fams.sort(t);return Object.assign({},e,{fams:n})}(e,t)});return Object.assign({},e,{indis:n})}function J(e){return K(V(e))}var q=[".jpg",".png",".gif"];function Y(e,t){if(!e.images||0===e.images.length)return e;var n=[];return e.images.forEach(function(e){var a=e.url.match(/[^/\\]*$/)[0];t.has(a)?n.push({url:t.get(a),title:e.title}):e.url.startsWith("http")&&function(e){var t=e.toLowerCase();return q.some(function(e){return t.endsWith(e)})}(e.url)&&n.push(e)}),Object.assign({},e,{images:n})}function X(e,t){var n=e.indis.map(function(e){return Y(e,t)});return Object.assign({},e,{indis:n})}function $(e){var t=e&&e.tree&&e.tree.find(function(e){return"SOUR"===e.tag}),n=t&&t.tree&&t.tree.find(function(e){return"NAME"===e.tag});return n&&n.data||null}var Q=new Map([["abt","about"],["cal","calculated"],["est","estimated"]]);function ee(e,t){var n=void 0!==e.day,a=void 0!==e.month,r=void 0!==e.year;if(!n&&!a&&!r)return e.text||"";var i=new Date(r?e.year:0,a?e.month-1:0,n?e.day:1),o=e.qualifier&&e.qualifier.toLowerCase(),s={day:n?"numeric":void 0,month:a?"long":void 0,year:r?"numeric":void 0};return[o&&t.formatMessage({id:"date.".concat(o),defaultMessage:Q.get(o)||o}),new Intl.DateTimeFormat(t.locale,s).format(i)].join(" ")}function te(e,t){var n=Object(D.getDate)(e);return n?n.date?ee(n.date,t):n.dateRange?function(e,t){var n=e.from,a=e.to,r=n&&ee(n,t),i=a&&ee(a,t);return r&&i?t.formatMessage({id:"date.between",defaultMessage:"between {from} and {to}"},{from:r,to:i}):r?t.formatMessage({id:"date.after",defaultMessage:"after {from}"},{from:r}):i?t.formatMessage({id:"date.before",defaultMessage:"before {to}"},{to:i}):""}(n.dateRange,t):"":""}var ne=["BIRT","BAPM","CHR","DEAT","BURI","EVEN"],ae=["NAME","SEX","FAMC","FAMS","NOTE","SOUR"],re=new Map([["BAPM","Baptism"],["BIRT","Birth"],["BURI","Burial"],["CHR","Christening"],["DEAT","Death"],["EMAIL","E-mail"],["EVEN","Event"],["OCCU","Occupation"],["TITL","Title"],["WWW","WWW"]]);function ie(e){return o.createElement(l.a,{id:"gedcom.".concat(e),defaultMessage:re.get(e)||e})}function oe(e){return o.createElement(o.Fragment,null,e.map(function(e,t){return o.createElement("div",{key:t},o.createElement(A.a,{properties:{target:"_blank"}},e),o.createElement("br",null))}))}function se(e){var t=[e.data];return e.tree.forEach(function(e){if("CONC"===e.tag&&e.data){var n=t.length-1;t[n]+=e.data}else"CONT"===e.tag&&e.data&&t.push(e.data)}),t}function ce(e){return oe(se(e).map(function(e,t){return o.createElement("i",{key:t},e)}))}function le(e){return o.createElement("h2",{className:"ui header"},e.data.split("/").filter(function(e){return!!e}).map(function(e,t){return o.createElement("div",{key:t},e,o.createElement("br",null))}))}function ue(e,t,n){return W()(t,function(t){return e.filter(function(e){return e.tag===t}).map(function(e){return n(e)})}).filter(function(e){return null!==e}).map(function(e,t){return o.createElement("div",{className:"ui segment",key:t},e)})}function de(e){return e.tree.length>0||e.data&&!e.data.startsWith("@")}function fe(e){return e.filter(function(e){return!ae.includes(e.tag)&&!ne.includes(e.tag)}).filter(de).map(function(e){return function(e){var t=[];return e.data&&t.push.apply(t,Object(a.a)(se(e))),e.tree.filter(function(e){return"NOTE"===e.tag}).forEach(function(e){return se(e).forEach(function(e){return t.push(o.createElement("i",null,e))})}),t.length?o.createElement(o.Fragment,null,o.createElement("div",{className:"ui sub header"},ie(e.tag)),o.createElement("span",null,oe(t))):null}(e)}).filter(function(e){return null!==e}).map(function(e,t){return o.createElement("div",{className:"ui segment",key:t},e)})}var me=function(e){function t(){return Object(v.a)(this,t),Object(u.a)(this,Object(d.a)(t).apply(this,arguments))}return Object(f.a)(t,e),Object(w.a)(t,[{key:"render",value:function(){var e=this,t=this.props.gedcom.indis[this.props.indi].tree,n=t.map(function(t){return function(e,t){if(e.data){var n=t.other[G(e.data)];if(n)return n}return e}(t,e.props.gedcom)}).filter(de);return o.createElement("div",{className:"ui segments",id:"details"},ue(t,["NAME"],le),ue(t,ne,function(t){return function(e,t){var n=[];e.data&&e.data.length>1&&n.push(o.createElement("i",null,e.data));var r=e.tree.find(function(e){return"DATE"===e.tag});r&&r.data&&n.push(te(r.data,t));var i=e.tree.find(function(e){return"PLAC"===e.tag});return i&&i.data&&n.push.apply(n,Object(a.a)(se(i))),e.tree.filter(function(e){return"NOTE"===e.tag}).forEach(function(e){return se(e).forEach(function(e){return n.push(o.createElement("i",null,e))})}),n.length?o.createElement(o.Fragment,null,o.createElement("div",{className:"ui sub header"},ie(e.tag)),o.createElement("span",null,oe(n))):null}(t,e.context.intl)}),fe(n),ue(n,["NOTE"],ce))}}]),t}(o.Component);function pe(e,t,n){return{id:t&&e.indis.some(function(e){return e.id===t})?t:e.indis[0].id,generation:n||0}}function he(e,t,n){var a=function(e,t){var n=Object(F.parse)(e),a=Object(D.gedcomEntriesToJson)(n);if(!a||!a.indis||!a.indis.length||!a.fams||!a.fams.length)throw new Error("Failed to read GEDCOM file");return{chartData:X(J(a),t),gedcom:B(n)}}(e,n||new Map),r=JSON.stringify(a);try{sessionStorage.setItem(t,r)}catch(i){console.warn("Failed to store data in session storage: "+i)}return a}function ge(e,t){return ve.apply(this,arguments)}function ve(){return(ve=Object(g.a)(h.a.mark(function e(t,n){var a,r,i,o;return h.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,!(a=sessionStorage.getItem(t))){e.next=4;break}return e.abrupt("return",JSON.parse(a));case 4:e.next=9;break;case 6:e.prev=6,e.t0=e.catch(0),console.warn("Failed to load data from session storage: "+e.t0);case 9:return r=n?"https://cors-anywhere.herokuapp.com/"+t:t,e.next=12,window.fetch(r);case 12:if(200===(i=e.sent).status){e.next=15;break}throw new Error(i.statusText);case 15:return e.next=17,i.text();case 17:return o=e.sent,e.abrupt("return",he(o,t));case 19:case"end":return e.stop()}},e,null,[[0,6]])}))).apply(this,arguments)}function we(e,t,n){return be.apply(this,arguments)}function be(){return(be=Object(g.a)(h.a.mark(function e(t,n,a){var r;return h.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,!(r=sessionStorage.getItem(t))){e.next=4;break}return e.abrupt("return",JSON.parse(r));case 4:e.next=9;break;case 6:e.prev=6,e.t0=e.catch(0),console.warn("Failed to load data from session storage: "+e.t0);case 9:if(n){e.next=11;break}throw new Error("Error loading data. Please upload your file again.");case 11:return e.abrupt("return",he(n,t,a));case 12:case"end":return e.stop()}},e,null,[[0,6]])}))).apply(this,arguments)}me.contextTypes={intl:l.d};var Ee=n(260),ye=n.n(Ee),ke=n(543),Oe=n(549),xe=n(286),Se=n(536);function De(e){return o.createElement(Se.a,{to:{pathname:"/view",search:b.stringify({url:e.url})}},e.text)}function je(){return o.createElement("div",{id:"content"},o.createElement("div",{className:"backgroundImage"}),o.createElement(ke.a,{className:"intro"},o.createElement(ke.a.Content,null,o.createElement(ke.a.Header,null,o.createElement(l.a,{id:"intro.title",defaultMessage:"Topola Genealogy Viewer"}))),o.createElement(ke.a.Content,null,o.createElement(Oe.a,null,o.createElement(Oe.a.Row,null,o.createElement(Oe.a.Column,{width:5},o.createElement(xe.a,{src:ye.a,alt:"Topola logo"})),o.createElement(Oe.a.Column,{width:11},o.createElement("p",null,o.createElement(l.a,{id:"intro.description",defaultMessage:"Topola Genealogy is a genealogy tree viewer that lets you browse the structure of the family."})),o.createElement("p",null,o.createElement(l.a,{id:"intro.instructions",defaultMessage:"Use the LOAD FROM URL or LOAD FROM FILE buttons above to load a GEDCOM file. You can export a GEDCOM file from most of the existing genealogy programs and web sites."})),o.createElement("p",null,o.createElement(l.a,{id:"intro.examples",defaultMessage:"Here are some examples from the web that you can view:"})),o.createElement("ul",null,o.createElement("li",null,o.createElement(De,{url:"http://genpol.com/module-Downloads-prep_hand_out-lid-32.html",text:"Karol Wojty\u0142a"})," ","(",o.createElement(l.a,{id:"intro.from",defaultMessage:"from"})," ",o.createElement("a",{href:"http://genpol.com/module-Downloads-display-lid-32.html"},"GENPOL"),")"),o.createElement("li",null,o.createElement(De,{url:"https://webtreeprint.com/tp_downloader.php?path=famous_gedcoms/shakespeare.ged",text:"Shakespeare"})," ","(",o.createElement(l.a,{id:"intro.from",defaultMessage:"from"})," ",o.createElement("a",{href:"https://webtreeprint.com/tp_famous_gedcoms.php"},"webtreeprint.com"),")"),o.createElement("li",null,o.createElement(De,{url:"http://genealogyoflife.com/tng/gedcom/HarryPotter.ged",text:"Harry Potter"})," ","(",o.createElement(l.a,{id:"intro.from",defaultMessage:"from"})," ",o.createElement("a",{href:"http://famousfamilytrees.blogspot.com/"},"Famous Family Trees"),")")),o.createElement("p",null,o.createElement("b",null,o.createElement(l.a,{id:"intro.privacy",defaultMessage:"Privacy"})),": ",o.createElement(l.a,{id:"intro.privacy_note",defaultMessage:'When using the "load from file" option, this site does not send your data anywhere and files loaded from disk do not leave your computer. When using "load from URL", data is passed through the {link} service to deal with an issue with cross-site file loading in the browser (CORS).',values:{link:o.createElement("a",{href:"https://cors-anywhere.herokuapp.com/"},"cors-anywhere")}})),o.createElement("p",{className:"ui right aligned version"},"version: ","2020-03-18 23:31:21 +0100".slice(0,16)," (",o.createElement("a",{href:"https://github.com/PeWu/topola-viewer/commit/".concat("8b38155")},"8b38155"),")"))," ")," "))))}var Me=n(544),_e=n(554),Te=n(539),Re=n(87),Ne=n.n(Re);function Le(e,t){return Ce.apply(this,arguments)}function Ce(){return(Ce=Object(g.a)(h.a.mark(function e(t,n){var a,r,i,o,s;return h.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:for(r in(a=new FormData).append("format","json"),t)a.append(r,t[r]);return i=n?"https://cors-anywhere.herokuapp.com/https://apps.wikitree.com/api.php":"https://apps.wikitree.com/api.php",e.next=6,window.fetch(i,{method:"POST",body:a});case 6:return o=e.sent,e.next=9,o.text();case 9:return s=e.sent,e.abrupt("return",JSON.parse(s));case 11:case"end":return e.stop()}},e)}))).apply(this,arguments)}function ze(e,t){return Ie.apply(this,arguments)}function Ie(){return(Ie=Object(g.a)(h.a.mark(function e(t,n){var a,r,i,o;return h.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(a="wikitree:ancestors:".concat(t),!(r=sessionStorage.getItem(a))){e.next=4;break}return e.abrupt("return",JSON.parse(r));case 4:return e.next=6,Le({action:"getAncestors",key:t,fields:"*"},n);case 6:return i=e.sent,o=i[0].ancestors,sessionStorage.setItem(a,JSON.stringify(o)),e.abrupt("return",o);case 10:case"end":return e.stop()}},e)}))).apply(this,arguments)}function Pe(e,t){return We.apply(this,arguments)}function We(){return(We=Object(g.a)(h.a.mark(function e(t,n){var a,r,i,o;return h.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(a=[],r=[],t.forEach(function(e){var t=sessionStorage.getItem("wikitree:relatives:".concat(e));t?a.push(JSON.parse(t)):r.push(e)}),0!==r.length){e.next=5;break}return e.abrupt("return",a);case 5:return e.next=7,Le({action:"getRelatives",keys:r.join(","),getChildren:!0,getSpouses:!0},n);case 7:if(null!==(i=e.sent)[0].items){e.next=10;break}throw new Error("WikiTree profile ".concat(r[0]," not found."));case 10:return(o=i[0].items.map(function(e){return e.person})).forEach(function(e){sessionStorage.setItem("wikitree:relatives:".concat(e.Name),JSON.stringify(e))}),e.abrupt("return",a.concat(o));case 13:case"end":return e.stop()}},e)}))).apply(this,arguments)}function Ue(e){return Ae.apply(this,arguments)}function Ae(){return(Ae=Object(g.a)(h.a.mark(function e(t){var n;return h.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,Le({action:"clientLogin",authcode:t},!1);case 2:return n=e.sent,e.abrupt("return",n.clientLogin);case 4:case"end":return e.stop()}},e)}))).apply(this,arguments)}function Fe(e,t){return Ge.apply(this,arguments)}function Ge(){return(Ge=Object(g.a)(h.a.mark(function e(t,n){var r,i,o,s,c,l,u,d,f,p,g,v,w,b,E,y,k,O,x,S,D;return h.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if((r="apps.wikitree.com"!==window.location.hostname)||Ne.a.get("wikidb_wtb_UserID")||!n){e.next=6;break}return e.next=4,Ue(n);case 4:"Success"===e.sent.result&&sessionStorage.clear();case 6:return i=[],e.next=9,Pe([t],r);case 9:if((o=e.sent)[0].Name){e.next=12;break}throw new Error("WikiTree profile ".concat(t," is not accessible. Try logging in."));case 12:return s=Object.values(o[0].Spouses).map(function(e){return e.Name}),e.next=15,Promise.all([t].concat(s).map(function(e){return ze(e,r)}));case 15:return c=e.sent,l=c.flat().map(function(e){return e.Name}).filter(function(e){return!!e}),e.next=19,Pe(l,r);case 19:u=e.sent,i.push.apply(i,Object(a.a)(u)),d=5,f=[t],p=0;case 24:if(!(f.length>0&&p<=d)){e.next=35;break}return e.next=27,Pe(f,r);case 27:g=e.sent,i.push.apply(i,Object(a.a)(g)),v=g.flatMap(function(e){return Object.values(e.Spouses)}),i.push.apply(i,Object(a.a)(v)),f=g.flatMap(function(e){return Object.values(e.Children).map(function(e){return e.Name})}),p++,e.next=24;break;case 35:return w=new Map,b=new Map,E=new Map,y=new Map,i.forEach(function(e){if(y.set(e.Id,e.Name),e.Mother||e.Father){var t=Be(e.Mother,e.Father);Ke(w,e.Mother).add(t),Ke(w,e.Father).add(t),Ke(b,t).add(e.Id),E.set(t,{wife:e.Mother||void 0,husband:e.Father||void 0})}}),k=[],O=new Set,i.forEach(function(e){if(!O.has(e.Id)){O.add(e.Id);var t=He(e);console.log(e,t),e.Spouses&&Object.values(e.Spouses).forEach(function(t){var n=Be(e.Id,t.Id);Ke(w,e.Id).add(n),Ke(w,t.Id).add(n);var a="Male"===e.Gender?{wife:t.Id,husband:e.Id,spouse:t}:{wife:e.Id,husband:t.Id,spouse:t};E.set(n,a)}),t.fams=Array.from(Ke(w,e.Id)),k.push(t)}}),x=Array.from(E.entries()).map(function(e){var t=Object(m.a)(e,2),n=t[0],a=t[1],r={id:n},i=a.wife&&y.get(a.wife);i&&(r.wife=i);var o=a.husband&&y.get(a.husband);if(o&&(r.husb=o),r.children=Array.from(Ke(b,n)).map(function(e){return y.get(e)}),a.spouse&&(a.spouse.marriage_date&&"0000-00-00"!==a.spouse.marriage_date||a.spouse.marriage_location)){var s=Ze(a.spouse.marriage_date);r.marriage=Object.assign({},s,{place:a.spouse.marriage_location})}return r}),S=J({indis:k,fams:x}),D=Ve(k),e.abrupt("return",{chartData:S,gedcom:D});case 47:case"end":return e.stop()}},e)}))).apply(this,arguments)}function Be(e,t){return t>e?"".concat(e,"_").concat(t):"".concat(t,"_").concat(e)}function He(e){var t={id:e.Name};if("Unknown"!==e.FirstName&&(t.firstName=e.FirstName),"Unknown"!==e.LastNameAtBirth&&(t.lastName=e.LastNameAtBirth),(e.Mother||e.Father)&&(t.famc=Be(e.Mother,e.Father)),"Male"===e.Gender?t.sex="M":"Female"===e.Gender&&(t.sex="F"),e.BirthDate&&"0000-00-00"!==e.BirthDate||e.BirthLocation){var n=Ze(e.BirthDate,e.DataStatus&&e.DataStatus.BirthDate);t.birth=Object.assign({},n,{place:e.BirthLocation})}if(e.DeathDate&&"0000-00-00"!==e.DeathDate||e.DeathLocation){var a=Ze(e.DeathDate,e.DataStatus&&e.DataStatus.DeathDate);t.death=Object.assign({},a,{place:e.DeathLocation})}return e.PhotoData&&(t.images=[{url:"https://wikitree.com".concat(e.PhotoData.path)}]),t}function Ze(e,t){if(e){var n=e.match(/(\d\d\d\d)-(\d\d)-(\d\d)/);if(!n)return{date:{text:e}};var a={};return"0000"!==n[1]&&(a.year=~~n[1]),"00"!==n[2]&&(a.month=~~n[2]),"00"!==n[3]&&(a.day=~~n[3]),"after"===t?{dateRange:{from:a}}:"before"===t?{dateRange:{to:a}}:("guess"===t&&(a.qualifier="abt"),{date:a})}}function Ve(e){var t={};return e.forEach(function(e){var n=e.id.replace(/ /g,"_");t[e.id]={level:0,pointer:"@".concat(e.id,"@"),tag:"INDI",data:"",tree:[{level:1,pointer:"",tag:"NAME",data:"".concat(e.firstName||""," /").concat(e.lastName||"","/"),tree:[]},{level:1,pointer:"",tag:"WWW",data:"https://www.wikitree.com/wiki/".concat(n),tree:[]}]}}),{head:{level:0,pointer:"",tag:"HEAD",data:"",tree:[]},indis:t,fams:{},other:{}}}function Ke(e,t){var n=e.get(t);if(n)return n;var a=new Set;return e.set(t,a),a}var Je=n(551),qe=n(552),Ye=n(547),Xe=n(264),$e=n.n(Xe),Qe=n(169),et=n.n(Qe),tt=n(265),nt=n.n(tt),at=n(266),rt=n.n(at);function it(e){return e.toLocaleLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/\u0142/g,"l")}function ot(e,t){return e.score!==t.score?t.score-e.score:nt()(e.ref,t.ref)}function st(e,t){return e.tree.filter(function(e){return"FAMS"===e.tag}).map(function(e){return t.fams[G(e.data)]}).filter(function(e){return!!e}).map(function(n){var a=n.tree.find(function(e){return"HUSB"===e.tag}),r=a&&G(a.data);return r&&r!==G(e.pointer)&&t.indis[r]}).filter(function(e){return!!e}).flatMap(function(e){return e.tree.filter(function(e){return"NAME"===e.tag}).map(function(e){var t=e.data.split("/");return t.length>=2?t[1]:""})}).join(" ")}var ct=function(){function e(t){Object(v.a)(this,e),this.gedcom=t,this.index=void 0}return Object(w.a)(e,[{key:"initialize",value:function(){var e=this;this.index=rt()(function(){for(var t in this.ref("id"),this.field("id"),this.field("name",{boost:10}),this.field("normalizedName",{boost:8}),this.field("spouseLastName",{boost:2}),this.field("normalizedSpouseLastName",{boost:2}),e.gedcom.indis){var n=e.gedcom.indis[t],a=n.tree.filter(function(e){return"NAME"===e.tag}).map(function(e){return e.data}).join(" "),r=st(n,e.gedcom);this.add({id:t,name:a,normalizedName:it(a),spouseLastName:r,normalizedSpouseLastName:it(r)})}})}},{key:"search",value:function(e){var t=this,n=e.split(" ").filter(function(e){return!!e}).map(function(e){return"+".concat(e,"*")}).join(" ");return this.index.search(n).sort(ot).slice(0,8).map(function(e){return{id:e.ref,indi:t.gedcom.indis[e.ref]}})}}]),e}();function lt(e){var t=e.indi.tree.find(function(e){return"NAME"===e.tag}),n=t&&t.data.split("/").filter(function(e){return!!e}).join(" ");return e.id.length>8?n:o.createElement(o.Fragment,null,n," ",o.createElement("i",null,"(",e.id,")"))}function ut(e,t,n){var a=e.tree.find(function(e){return e.tag===t}),r=a&&a.tree.find(function(e){return"DATE"===e.tag});return r&&te(r.data,n)||""}function dt(e,t){var n=ut(e,"BIRT",t),a=ut(e,"DEAT",t);return a?"".concat(n," \u2013 ").concat(a):n}var ft,mt=n(541),pt=n(550),ht=n(66),gt=n(540),vt=n(538),wt=n(530),bt=n(545),Et=n(542),yt=n(546);function kt(e){return new Promise(function(t,n){var a=new FileReader;a.onload=function(e){t(e.target.result)},a.readAsText(e)})}function Ot(e){var t=e.toLowerCase();return t.endsWith(".jpg")||t.endsWith(".png")}!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.NOT_LOGGED_IN=1]="NOT_LOGGED_IN",e[e.LOGGED_IN=2]="LOGGED_IN"}(ft||(ft={}));var xt,St=function(e){function t(){var e,n;Object(v.a)(this,t);for(var a=arguments.length,r=new Array(a),i=0;i {\n const reader = new FileReader();\n reader.readAsDataURL(blob);\n return new Promise((resolve, reject) => {\n reader.onload = (e) => resolve((e.target as FileReader).result as string);\n });\n}\n\nasync function inlineImage(image: SVGImageElement) {\n const href = image.href.baseVal;\n if (!href) {\n return;\n }\n try {\n const response = await fetch(href);\n const blob = await response.blob();\n const dataUrl = await loadAsDataUrl(blob);\n image.href.baseVal = dataUrl;\n } catch (e) {\n console.warn('Failed to load image:', e);\n }\n}\n\n/**\n * Fetches all images in the SVG and replaces them with inlined images as data\n * URLs. Images are replaced in place. The replacement is done, the returned\n * promise is resolved.\n */\nasync function inlineImages(svg: Element): Promise {\n const images = Array.from(svg.getElementsByTagName('image'));\n await Promise.all(images.map(inlineImage));\n}\n\n/** Loads a blob into an image object. */\nfunction loadImage(blob: Blob): Promise {\n const image = new Image();\n image.src = URL.createObjectURL(blob);\n return new Promise((resolve, reject) => {\n image.addEventListener('load', () => resolve(image));\n });\n}\n\n/** Draw image on a new canvas and return the canvas. */\nfunction drawOnCanvas(image: HTMLImageElement) {\n const canvas = document.createElement('canvas');\n // Scale image for better quality.\n canvas.width = image.width * 2;\n canvas.height = image.height * 2;\n\n const ctx = canvas.getContext('2d')!;\n const oldFill = ctx.fillStyle;\n ctx.fillStyle = 'white';\n ctx.fillRect(0, 0, canvas.width, canvas.height);\n ctx.fillStyle = oldFill;\n\n ctx.drawImage(image, 0, 0, canvas.width, canvas.height);\n return canvas;\n}\n\nfunction canvasToBlob(canvas: HTMLCanvasElement, type: string) {\n return new Promise((resolve, reject) => {\n canvas.toBlob((blob) => {\n if (blob) {\n resolve(blob);\n } else {\n reject();\n }\n }, type);\n });\n}\n\n/** Supported chart types. */\nexport enum ChartType {\n Hourglass,\n Relatives,\n Fancy,\n}\n\nexport interface ChartProps {\n data: JsonGedcomData;\n selection: IndiInfo;\n chartType: ChartType;\n onSelection: (indiInfo: IndiInfo) => void;\n enableZoom: boolean;\n}\n\n/** Component showing the genealogy chart and handling transition animations. */\nexport class Chart extends React.PureComponent {\n private chart?: ChartHandle;\n /** Animation is in progress. */\n private animating = false;\n /** Rendering is required after the current animation finishes. */\n private rerenderRequired = false;\n /** The d3 zoom behavior object. */\n private zoomBehavior?: d3.ZoomBehavior;\n\n private getChartType() {\n switch (this.props.chartType) {\n case ChartType.Hourglass:\n return HourglassChart;\n case ChartType.Relatives:\n return RelativesChart;\n case ChartType.Fancy:\n return FancyChart;\n default:\n // Fall back to hourglass chart.\n return HourglassChart;\n }\n }\n\n private getRendererType() {\n switch (this.props.chartType) {\n case ChartType.Fancy:\n return CircleRenderer;\n default:\n // Use DetailedRenderer by default.\n return DetailedRenderer;\n }\n }\n\n private zoom(factor: number) {\n const parent = d3.select('#svgContainer') as d3.Selection<\n Element,\n any,\n any,\n any\n >;\n this.zoomBehavior!.scaleBy(parent, factor);\n }\n\n /**\n * Renders the chart or performs a transition animation to a new state.\n * If indiInfo is not given, it means that it is the initial render and no\n * animation is performed.\n */\n private renderChart(args: {initialRender: boolean} = {initialRender: false}) {\n // Wait for animation to finish if animation is in progress.\n if (!args.initialRender && this.animating) {\n this.rerenderRequired = true;\n return;\n }\n\n if (args.initialRender) {\n (d3.select('#chart').node() as HTMLElement).innerHTML = '';\n this.chart = createChart({\n json: this.props.data,\n chartType: this.getChartType(),\n renderer: this.getRendererType(),\n svgSelector: '#chart',\n indiCallback: (info) => this.props.onSelection(info),\n animate: true,\n updateSvgSize: false,\n locale: this.context.intl.locale,\n });\n } else {\n this.chart!.setData(this.props.data);\n }\n const chartInfo = this.chart!.render({\n startIndi: this.props.selection.id,\n baseGeneration: this.props.selection.generation,\n });\n const svg = d3.select('#chartSvg');\n const parent = d3.select('#svgContainer').node() as Element;\n\n const scale = this.props.enableZoom ? d3.zoomTransform(parent).k : 1;\n const zoomOutFactor = d3.min([\n 1,\n scale,\n parent.clientWidth / chartInfo.size[0],\n parent.clientHeight / chartInfo.size[1],\n ])!;\n const extent: [number, number] = this.props.enableZoom\n ? [d3.max([0.1, zoomOutFactor])!, 2]\n : [1, 1];\n\n this.zoomBehavior = d3\n .zoom()\n .scaleExtent(extent)\n .translateExtent([[0, 0], chartInfo.size])\n .on('zoom', () => zoomed(chartInfo.size, this.props.enableZoom));\n d3.select(parent)\n .on('scroll', () => scrolled(this.props.enableZoom))\n .call(this.zoomBehavior);\n\n const scrollTopTween = (scrollTop: number) => {\n return () => {\n const i = d3.interpolateNumber(parent.scrollTop, scrollTop);\n return (t: number) => {\n parent.scrollTop = i(t);\n };\n };\n };\n const scrollLeftTween = (scrollLeft: number) => {\n return () => {\n const i = d3.interpolateNumber(parent.scrollLeft, scrollLeft);\n return (t: number) => {\n parent.scrollLeft = i(t);\n };\n };\n };\n\n const dx = parent.clientWidth / 2 - chartInfo.origin[0] * scale;\n const dy = parent.clientHeight / 2 - chartInfo.origin[1] * scale;\n const offsetX = d3.max([\n 0,\n (parent.clientWidth - chartInfo.size[0] * scale) / 2,\n ]);\n const offsetY = d3.max([\n 0,\n (parent.clientHeight - chartInfo.size[1] * scale) / 2,\n ]);\n const svgTransition = svg\n .transition()\n .delay(200)\n .duration(500);\n const transition = args.initialRender ? svg : svgTransition;\n transition\n .attr('transform', `translate(${offsetX}, ${offsetY})`)\n .attr('width', chartInfo.size[0] * scale)\n .attr('height', chartInfo.size[1] * scale);\n if (args.initialRender) {\n parent.scrollLeft = -dx;\n parent.scrollTop = -dy;\n } else {\n svgTransition\n .tween('scrollLeft', scrollLeftTween(-dx))\n .tween('scrollTop', scrollTopTween(-dy));\n }\n\n // After the animation is finished, rerender the chart if required.\n this.animating = true;\n chartInfo.animationPromise.then(() => {\n this.animating = false;\n if (this.rerenderRequired) {\n this.rerenderRequired = false;\n this.renderChart({initialRender: false});\n }\n });\n }\n\n componentDidMount() {\n this.renderChart({initialRender: true});\n }\n\n componentDidUpdate(prevProps: ChartProps) {\n const initialRender = this.props.chartType !== prevProps.chartType;\n this.renderChart({initialRender});\n }\n\n /** Make intl appear in this.context. */\n static contextTypes = {\n intl: intlShape,\n };\n\n render() {\n return (\n
\n {this.props.enableZoom ? (\n \n \n this.zoom(1 / ZOOM_FACTOR)}\n >\n −\n \n \n ) : null}\n \n \n \n
\n );\n }\n\n /** Return a copy of the SVG chart but without scaling and positioning. */\n private getStrippedSvg() {\n const svg = document.getElementById('chartSvg')!.cloneNode(true) as Element;\n\n svg.removeAttribute('transform');\n if (this.props.enableZoom) {\n const parent = d3.select('#svgContainer').node() as Element;\n const scale = d3.zoomTransform(parent).k;\n svg.setAttribute(\n 'width',\n String(Number(svg.getAttribute('width')) / scale),\n );\n svg.setAttribute(\n 'height',\n String(Number(svg.getAttribute('height')) / scale),\n );\n svg.querySelector('#chart')!.removeAttribute('transform');\n }\n return svg;\n }\n\n private getSvgContents() {\n return new XMLSerializer().serializeToString(this.getStrippedSvg());\n }\n\n private async getSvgContentsWithInlinedImages() {\n const svg = this.getStrippedSvg();\n await inlineImages(svg);\n return new XMLSerializer().serializeToString(svg);\n }\n\n /** Shows the print dialog to print the currently displayed chart. */\n print() {\n const printWindow = document.createElement('iframe');\n printWindow.style.position = 'absolute';\n printWindow.style.top = '-1000px';\n printWindow.style.left = '-1000px';\n printWindow.onload = () => {\n printWindow.contentDocument!.open();\n printWindow.contentDocument!.write(this.getSvgContents());\n printWindow.contentDocument!.close();\n // Doesn't work on Firefox without the setTimeout.\n setTimeout(() => {\n printWindow.contentWindow!.focus();\n printWindow.contentWindow!.print();\n printWindow.parentNode!.removeChild(printWindow);\n }, 500);\n };\n document.body.appendChild(printWindow);\n }\n\n async downloadSvg() {\n const contents = await this.getSvgContentsWithInlinedImages();\n const blob = new Blob([contents], {type: 'image/svg+xml'});\n saveAs(blob, 'topola.svg');\n }\n\n private async drawOnCanvas(): Promise {\n const contents = await this.getSvgContentsWithInlinedImages();\n const blob = new Blob([contents], {type: 'image/svg+xml'});\n return await drawOnCanvas(await loadImage(blob));\n }\n\n async downloadPng() {\n const canvas = await this.drawOnCanvas();\n const blob = await canvasToBlob(canvas, 'image/png');\n saveAs(blob, 'topola.png');\n }\n\n async downloadPdf() {\n const canvas = await this.drawOnCanvas();\n const doc = new jsPDF({\n orientation: canvas.width > canvas.height ? 'l' : 'p',\n unit: 'pt',\n format: [canvas.width, canvas.height],\n });\n doc.addImage(canvas, 'PNG', 0, 0, canvas.width, canvas.height, 'NONE');\n doc.save('topola.pdf');\n }\n}\n","import {\n JsonFam,\n JsonGedcomData,\n JsonIndi,\n gedcomEntriesToJson,\n JsonImage,\n JsonEvent,\n} from 'topola';\nimport {GedcomEntry, parse as parseGedcom} from 'parse-gedcom';\n\nexport interface GedcomData {\n /** The HEAD entry. */\n head: GedcomEntry;\n /** INDI entries mapped by id. */\n indis: {[key: string]: GedcomEntry};\n /** FAM entries mapped by id. */\n fams: {[key: string]: GedcomEntry};\n /** Other entries mapped by id, e.g. NOTE, SOUR. */\n other: {[key: string]: GedcomEntry};\n}\n\nexport interface TopolaData {\n chartData: JsonGedcomData;\n gedcom: GedcomData;\n}\n\n/**\n * Returns the identifier extracted from a pointer string.\n * E.g. '@I123@' -> 'I123'\n */\nexport function pointerToId(pointer: string): string {\n return pointer.substring(1, pointer.length - 1);\n}\n\nfunction prepareGedcom(entries: GedcomEntry[]): GedcomData {\n const head = entries.find((entry) => entry.tag === 'HEAD')!;\n const indis: {[key: string]: GedcomEntry} = {};\n const fams: {[key: string]: GedcomEntry} = {};\n const other: {[key: string]: GedcomEntry} = {};\n entries.forEach((entry) => {\n if (entry.tag === 'INDI') {\n indis[pointerToId(entry.pointer)] = entry;\n } else if (entry.tag === 'FAM') {\n fams[pointerToId(entry.pointer)] = entry;\n } else if (entry.pointer) {\n other[pointerToId(entry.pointer)] = entry;\n }\n });\n return {head, indis, fams, other};\n}\n\nfunction strcmp(a: string, b: string) {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n}\n\n/** Compares dates of the given events. */\nfunction compareDates(\n event1: JsonEvent | undefined,\n event2: JsonEvent | undefined,\n): number {\n const date1 =\n event1 && (event1.date || (event1.dateRange && event1.dateRange.from));\n const date2 =\n event2 && (event2.date || (event2.dateRange && event2.dateRange.from));\n if (!date1 || !date1.year || !date2 || !date2.year) {\n return 0;\n }\n if (date1.year !== date2.year) {\n return date1.year - date2.year;\n }\n if (!date1.month || !date2.month) {\n return 0;\n }\n if (date1.month !== date2.month) {\n return date1.month - date2.month;\n }\n if (date1.day && date2.day && date1.day !== date2.day) {\n return date1.month - date2.month;\n }\n return 0;\n}\n\n/** Birth date comparator for individuals. */\nfunction birthDatesComparator(gedcom: JsonGedcomData) {\n const idToIndiMap = new Map();\n gedcom.indis.forEach((indi) => {\n idToIndiMap[indi.id] = indi;\n });\n\n return (indiId1: string, indiId2: string) => {\n const indi1: JsonIndi = idToIndiMap[indiId1];\n const indi2: JsonIndi = idToIndiMap[indiId2];\n return (\n compareDates(indi1 && indi1.birth, indi2 && indi2.birth) ||\n strcmp(indiId1, indiId2)\n );\n };\n}\n\n/** Marriage date comparator for families. */\nfunction marriageDatesComparator(gedcom: JsonGedcomData) {\n const idToFamMap = new Map();\n gedcom.fams.forEach((fam) => {\n idToFamMap[fam.id] = fam;\n });\n\n return (famId1: string, famId2: string) => {\n const fam1: JsonFam = idToFamMap[famId1];\n const fam2: JsonFam = idToFamMap[famId2];\n return (\n compareDates(fam1 && fam1.marriage, fam2 && fam2.marriage) ||\n strcmp(famId1, famId2)\n );\n };\n}\n\n/**\n * Sorts children by birth date in the given family.\n * Does not modify the input objects.\n */\nfunction sortFamilyChildren(\n fam: JsonFam,\n comparator: (id1: string, id2: string) => number,\n): JsonFam {\n if (!fam.children) {\n return fam;\n }\n const newChildren = fam.children.sort(comparator);\n return Object.assign({}, fam, {children: newChildren});\n}\n\n/**\n * Sorts children by birth date.\n * Does not modify the input object.\n */\nfunction sortChildren(gedcom: JsonGedcomData): JsonGedcomData {\n const comparator = birthDatesComparator(gedcom);\n const newFams = gedcom.fams.map((fam) => sortFamilyChildren(fam, comparator));\n return Object.assign({}, gedcom, {fams: newFams});\n}\n\n/**\n * Sorts spouses by marriage date.\n * Does not modify the input objects.\n */\nfunction sortIndiSpouses(\n indi: JsonIndi,\n comparator: (id1: string, id2: string) => number,\n): JsonFam {\n if (!indi.fams) {\n return indi;\n }\n const newFams = indi.fams.sort(comparator);\n return Object.assign({}, indi, {fams: newFams});\n}\n\nfunction sortSpouses(gedcom: JsonGedcomData): JsonGedcomData {\n const comparator = marriageDatesComparator(gedcom);\n const newIndis = gedcom.indis.map((indi) =>\n sortIndiSpouses(indi, comparator),\n );\n return Object.assign({}, gedcom, {indis: newIndis});\n}\n\n/** Sorts children and spouses. */\nexport function normalizeGedcom(gedcom: JsonGedcomData): JsonGedcomData {\n return sortSpouses(sortChildren(gedcom));\n}\n\nconst IMAGE_EXTENSIONS = ['.jpg', '.png', '.gif'];\n\n/** Returns true if the given file name has a known image extension. */\nfunction isImageFile(fileName: string): boolean {\n const lowerName = fileName.toLowerCase();\n return IMAGE_EXTENSIONS.some((ext) => lowerName.endsWith(ext));\n}\n\n/**\n * Removes images that are not HTTP links or do not have known image extensions.\n * Does not modify the input object.\n */\nfunction filterImage(indi: JsonIndi, images: Map): JsonIndi {\n if (!indi.images || indi.images.length === 0) {\n return indi;\n }\n const newImages: JsonImage[] = [];\n indi.images.forEach((image) => {\n const fileName = image.url.match(/[^/\\\\]*$/)![0];\n // If the image file has been loaded into memory, use it.\n if (images.has(fileName)) {\n newImages.push({url: images.get(fileName)!, title: image.title});\n } else if (image.url.startsWith('http') && isImageFile(image.url)) {\n newImages.push(image);\n }\n });\n return Object.assign({}, indi, {images: newImages});\n}\n\n/**\n * Removes images that are not HTTP links.\n * Does not modify the input object.\n */\nfunction filterImages(\n gedcom: JsonGedcomData,\n images: Map,\n): JsonGedcomData {\n const newIndis = gedcom.indis.map((indi) => filterImage(indi, images));\n return Object.assign({}, gedcom, {indis: newIndis});\n}\n\n/**\n * Converts GEDCOM file into JSON data performing additional transformations:\n * - sort children by birth date\n * - remove images that are not HTTP links and aren't mapped in `images`.\n *\n * @param images Map from file name to image URL. This is used to pass in\n * uploaded images.\n */\nexport function convertGedcom(\n gedcom: string,\n images: Map,\n): TopolaData {\n const entries = parseGedcom(gedcom);\n const json = gedcomEntriesToJson(entries);\n if (\n !json ||\n !json.indis ||\n !json.indis.length ||\n !json.fams ||\n !json.fams.length\n ) {\n throw new Error('Failed to read GEDCOM file');\n }\n\n return {\n chartData: filterImages(normalizeGedcom(json), images),\n gedcom: prepareGedcom(entries),\n };\n}\n\nexport function getSoftware(head: GedcomEntry): string | null {\n const sour =\n head && head.tree && head.tree.find((entry) => entry.tag === 'SOUR');\n const name =\n sour && sour.tree && sour.tree.find((entry) => entry.tag === 'NAME');\n return (name && name.data) || null;\n}\n","import {Date as TopolaDate, DateRange, getDate} from 'topola';\nimport {InjectedIntl} from 'react-intl';\n\nconst DATE_QUALIFIERS = new Map([\n ['abt', 'about'],\n ['cal', 'calculated'],\n ['est', 'estimated'],\n]);\n\nfunction formatDate(date: TopolaDate, intl: InjectedIntl) {\n const hasDay = date.day !== undefined;\n const hasMonth = date.month !== undefined;\n const hasYear = date.year !== undefined;\n if (!hasDay && !hasMonth && !hasYear) {\n return date.text || '';\n }\n const dateObject = new Date(\n hasYear ? date.year! : 0,\n hasMonth ? date.month! - 1 : 0,\n hasDay ? date.day! : 1,\n );\n\n const qualifier = date.qualifier && date.qualifier.toLowerCase();\n const translatedQualifier =\n qualifier &&\n intl.formatMessage({\n id: `date.${qualifier}`,\n defaultMessage: DATE_QUALIFIERS.get(qualifier) || qualifier,\n });\n\n const formatOptions = {\n day: hasDay ? 'numeric' : undefined,\n month: hasMonth ? 'long' : undefined,\n year: hasYear ? 'numeric' : undefined,\n };\n const translatedDate = new Intl.DateTimeFormat(\n intl.locale,\n formatOptions,\n ).format(dateObject);\n\n return [translatedQualifier, translatedDate].join(' ');\n}\n\nfunction formatDateRage(dateRange: DateRange, intl: InjectedIntl) {\n const fromDate = dateRange.from;\n const toDate = dateRange.to;\n const translatedFromDate = fromDate && formatDate(fromDate, intl);\n const translatedToDate = toDate && formatDate(toDate, intl);\n if (translatedFromDate && translatedToDate) {\n return intl.formatMessage(\n {\n id: 'date.between',\n defaultMessage: 'between {from} and {to}',\n },\n {from: translatedFromDate, to: translatedToDate},\n );\n }\n if (translatedFromDate) {\n return intl.formatMessage(\n {\n id: 'date.after',\n defaultMessage: 'after {from}',\n },\n {from: translatedFromDate},\n );\n }\n if (translatedToDate) {\n return intl.formatMessage(\n {\n id: 'date.before',\n defaultMessage: 'before {to}',\n },\n {to: translatedToDate},\n );\n }\n return '';\n}\n\n/** Formats a date given in GEDCOM format. */\nexport function translateDate(gedcomDate: string, intl: InjectedIntl) {\n const dateOrRange = getDate(gedcomDate);\n if (!dateOrRange) {\n return '';\n }\n if (dateOrRange.date) {\n return formatDate(dateOrRange.date, intl);\n }\n if (dateOrRange.dateRange) {\n return formatDateRage(dateOrRange.dateRange, intl);\n }\n return '';\n}\n","import * as React from 'react';\nimport flatMap from 'array.prototype.flatmap';\nimport Linkify from 'react-linkify';\nimport {FormattedMessage, InjectedIntl} from 'react-intl';\nimport {GedcomData, pointerToId} from './gedcom_util';\nimport {GedcomEntry} from 'parse-gedcom';\nimport {intlShape} from 'react-intl';\nimport {translateDate} from './date_util';\n\ninterface Props {\n gedcom: GedcomData;\n indi: string;\n}\n\nconst EVENT_TAGS = ['BIRT', 'BAPM', 'CHR', 'DEAT', 'BURI', 'EVEN'];\nconst EXCLUDED_TAGS = ['NAME', 'SEX', 'FAMC', 'FAMS', 'NOTE', 'SOUR'];\nconst TAG_DESCRIPTIONS = new Map([\n ['BAPM', 'Baptism'],\n ['BIRT', 'Birth'],\n ['BURI', 'Burial'],\n ['CHR', 'Christening'],\n ['DEAT', 'Death'],\n ['EMAIL', 'E-mail'],\n ['EVEN', 'Event'],\n ['OCCU', 'Occupation'],\n ['TITL', 'Title'],\n ['WWW', 'WWW'],\n]);\n\nfunction translateTag(tag: string) {\n return (\n \n );\n}\n\nfunction joinLines(lines: (JSX.Element | string)[]) {\n return (\n <>\n {lines.map((line, index) => (\n
\n {line}\n
\n
\n ))}\n \n );\n}\n\n/**\n * Returns the data for the given GEDCOM entry as an array of lines. Supports\n * continuations with CONT and CONC.\n */\nfunction getData(entry: GedcomEntry) {\n const result = [entry.data];\n entry.tree.forEach((subentry) => {\n if (subentry.tag === 'CONC' && subentry.data) {\n const last = result.length - 1;\n result[last] += subentry.data;\n } else if (subentry.tag === 'CONT' && subentry.data) {\n result.push(subentry.data);\n }\n });\n return result;\n}\n\nfunction eventDetails(entry: GedcomEntry, intl: InjectedIntl) {\n const lines = [];\n if (entry.data && entry.data.length > 1) {\n lines.push({entry.data});\n }\n const date = entry.tree.find((subentry) => subentry.tag === 'DATE');\n if (date && date.data) {\n lines.push(translateDate(date.data, intl));\n }\n const place = entry.tree.find((subentry) => subentry.tag === 'PLAC');\n if (place && place.data) {\n lines.push(...getData(place));\n }\n entry.tree\n .filter((subentry) => subentry.tag === 'NOTE')\n .forEach((note) =>\n getData(note).forEach((line) => lines.push({line})),\n );\n if (!lines.length) {\n return null;\n }\n return (\n <>\n
{translateTag(entry.tag)}
\n {joinLines(lines)}\n \n );\n}\n\nfunction dataDetails(entry: GedcomEntry) {\n const lines = [];\n if (entry.data) {\n lines.push(...getData(entry));\n }\n entry.tree\n .filter((subentry) => subentry.tag === 'NOTE')\n .forEach((note) =>\n getData(note).forEach((line) => lines.push({line})),\n );\n if (!lines.length) {\n return null;\n }\n return (\n <>\n
{translateTag(entry.tag)}
\n {joinLines(lines)}\n \n );\n}\n\nfunction noteDetails(entry: GedcomEntry) {\n return joinLines(\n getData(entry).map((line, index) => {line}),\n );\n}\n\nfunction nameDetails(entry: GedcomEntry) {\n return (\n

\n {entry.data\n .split('/')\n .filter((name) => !!name)\n .map((name, index) => (\n
\n {name}\n
\n
\n ))}\n

\n );\n}\n\nfunction getDetails(\n entries: GedcomEntry[],\n tags: string[],\n detailsFunction: (entry: GedcomEntry) => JSX.Element | null,\n): JSX.Element[] {\n return flatMap(tags, (tag) =>\n entries\n .filter((entry) => entry.tag === tag)\n .map((entry) => detailsFunction(entry)),\n )\n .filter((element) => element !== null)\n .map((element, index) => (\n
\n {element}\n
\n ));\n}\n\n/**\n * Returns true if there is displayable information in this entry.\n * Returns false if there is no data in this entry or this is only a reference\n * to another entry.\n */\nfunction hasData(entry: GedcomEntry) {\n return entry.tree.length > 0 || (entry.data && !entry.data.startsWith('@'));\n}\n\nfunction getOtherDetails(entries: GedcomEntry[]) {\n return entries\n .filter(\n (entry) =>\n !EXCLUDED_TAGS.includes(entry.tag) && !EVENT_TAGS.includes(entry.tag),\n )\n .filter(hasData)\n .map((entry) => dataDetails(entry))\n .filter((element) => element !== null)\n .map((element, index) => (\n
\n {element}\n
\n ));\n}\n\n/**\n * If the entry is a reference to a top-level entry, the referenced entry is\n * returned. Otherwise, returns the given entry unmodified.\n */\nfunction dereference(entry: GedcomEntry, gedcom: GedcomData) {\n if (entry.data) {\n const dereferenced = gedcom.other[pointerToId(entry.data)];\n if (dereferenced) {\n return dereferenced;\n }\n }\n return entry;\n}\n\nexport class Details extends React.Component {\n /** Make intl appear in this.context. */\n static contextTypes = {\n intl: intlShape,\n };\n\n render() {\n const entries = this.props.gedcom.indis[this.props.indi].tree;\n const entriesWithData = entries\n .map((entry) => dereference(entry, this.props.gedcom))\n .filter(hasData);\n\n return (\n
\n {getDetails(entries, ['NAME'], nameDetails)}\n {getDetails(entries, EVENT_TAGS, (entry) =>\n eventDetails(entry, this.context.intl as InjectedIntl),\n )}\n {getOtherDetails(entriesWithData)}\n {getDetails(entriesWithData, ['NOTE'], noteDetails)}\n
\n );\n }\n}\n","import {convertGedcom, TopolaData} from './gedcom_util';\nimport {IndiInfo, JsonGedcomData} from 'topola';\n\n/**\n * Returns a valid IndiInfo object, either with the given indi and generation\n * or with an individual taken from the data and generation 0.\n */\nexport function getSelection(\n data: JsonGedcomData,\n indi?: string,\n generation?: number,\n): IndiInfo {\n // If ID is not given or it doesn't exist in the data, use the first ID in\n // the data.\n const id =\n indi && data.indis.some((i) => i.id === indi) ? indi : data.indis[0].id;\n return {id, generation: generation || 0};\n}\n\nfunction prepareData(\n gedcom: string,\n cacheId: string,\n images?: Map,\n): TopolaData {\n const data = convertGedcom(gedcom, images || new Map());\n const serializedData = JSON.stringify(data);\n try {\n sessionStorage.setItem(cacheId, serializedData);\n } catch (e) {\n console.warn('Failed to store data in session storage: ' + e);\n }\n return data;\n}\n\n/** Fetches data from the given URL. Uses cors-anywhere if handleCors is true. */\nexport async function loadFromUrl(\n url: string,\n handleCors: boolean,\n): Promise {\n try {\n const cachedData = sessionStorage.getItem(url);\n if (cachedData) {\n return JSON.parse(cachedData);\n }\n } catch (e) {\n console.warn('Failed to load data from session storage: ' + e);\n }\n const urlToFetch = handleCors\n ? 'https://cors-anywhere.herokuapp.com/' + url\n : url;\n\n const response = await window.fetch(urlToFetch);\n if (response.status !== 200) {\n throw new Error(response.statusText);\n }\n const gedcom = await response.text();\n return prepareData(gedcom, url);\n}\n\n/** Loads data from the given GEDCOM file contents. */\nexport async function loadGedcom(\n hash: string,\n gedcom?: string,\n images?: Map,\n): Promise {\n try {\n const cachedData = sessionStorage.getItem(hash);\n if (cachedData) {\n return JSON.parse(cachedData);\n }\n } catch (e) {\n console.warn('Failed to load data from session storage: ' + e);\n }\n if (!gedcom) {\n throw new Error('Error loading data. Please upload your file again.');\n }\n return prepareData(gedcom, hash, images);\n}\n","import * as queryString from 'query-string';\nimport * as React from 'react';\nimport logo from './topola.jpg';\nimport {Card, Grid, Image} from 'semantic-ui-react';\nimport {FormattedMessage} from 'react-intl';\nimport {Link} from 'react-router-dom';\n\n/** Link that loads a GEDCOM file from URL. */\nfunction GedcomLink(props: {url: string; text: string}) {\n return (\n \n {props.text}\n \n );\n}\n\nfunction formatBuildDate(dateString: string) {\n return dateString.slice(0, 16);\n}\n\n/** The intro page. */\nexport function Intro() {\n return (\n
\n
\n \n \n \n \n \n \n \n \n \n \n \"Topola\n \n \n

\n \n

\n

\n \n

\n

\n \n

\n \n

\n \n \n \n {': '}\n \n cors-anywhere\n \n ),\n }}\n />\n

\n

\n version: {formatBuildDate(process.env.REACT_APP_GIT_TIME!)} (\n \n {process.env.REACT_APP_GIT_SHA}\n \n )\n

\n
{' '}\n
{' '}\n
\n
\n
\n
\n );\n}\n","import Cookies from 'js-cookie';\nimport {Date, JsonFam, JsonIndi, DateOrRange} from 'topola';\nimport {GedcomData, TopolaData, normalizeGedcom} from './gedcom_util';\nimport {GedcomEntry} from 'parse-gedcom';\n\n/** WikiTree API getAncestors request. */\ninterface GetAncestorsRequest {\n action: 'getAncestors';\n key: string;\n fields: string;\n}\n\n/** WikiTree API getRelatives request. */\ninterface GetRelatives {\n action: 'getRelatives';\n keys: string;\n getChildren?: true;\n getSpouses?: true;\n}\n\ninterface ClientLogin {\n action: 'clientLogin';\n authcode: string;\n}\n\ntype WikiTreeRequest = GetAncestorsRequest | GetRelatives | ClientLogin;\n\n/** Person structure returned from WikiTree API. */\ninterface Person {\n Id: number;\n Name: string;\n FirstName: string;\n LastNameAtBirth: string;\n Spouses: {[key: number]: Person};\n Children: {[key: number]: Person};\n Mother: number;\n Father: number;\n Gender: string;\n BirthDate: string;\n DeathDate: string;\n BirthLocation: string;\n DeathLocation: string;\n marriage_location: string;\n marriage_date: string;\n DataStatus?: {\n BirthDate: string;\n DeathDate: string;\n };\n PhotoData?: {\n path: string;\n };\n}\n\n/** Sends a request to the WikiTree API. Returns the parsed response JSON. */\nasync function wikiTreeGet(request: WikiTreeRequest, handleCors: boolean) {\n const requestData = new FormData();\n requestData.append('format', 'json');\n for (const key in request) {\n requestData.append(key, request[key]);\n }\n const apiUrl = handleCors\n ? 'https://cors-anywhere.herokuapp.com/https://apps.wikitree.com/api.php'\n : 'https://apps.wikitree.com/api.php';\n const response = await window.fetch(apiUrl, {\n method: 'POST',\n body: requestData,\n });\n const responseBody = await response.text();\n return JSON.parse(responseBody);\n}\n\n/**\n * Retrieves ancestors from WikiTree for the given person ID.\n * Uses sessionStorage for caching responses.\n */\nasync function getAncestors(key: string, handleCors: boolean) {\n const cacheKey = `wikitree:ancestors:${key}`;\n const cachedData = sessionStorage.getItem(cacheKey);\n if (cachedData) {\n return JSON.parse(cachedData);\n }\n const response = await wikiTreeGet(\n {\n action: 'getAncestors',\n key: key,\n fields: '*',\n },\n handleCors,\n );\n const result = response[0].ancestors as Person[];\n sessionStorage.setItem(cacheKey, JSON.stringify(result));\n return result;\n}\n\n/**\n * Retrieves relatives from WikiTree for the given array of person IDs.\n * Uses sessionStorage for caching responses.\n */\nasync function getRelatives(keys: string[], handleCors: boolean) {\n const result: Person[] = [];\n const keysToFetch: string[] = [];\n keys.forEach((key) => {\n const cachedData = sessionStorage.getItem(`wikitree:relatives:${key}`);\n if (cachedData) {\n result.push(JSON.parse(cachedData));\n } else {\n keysToFetch.push(key);\n }\n });\n if (keysToFetch.length === 0) {\n return result;\n }\n const response = await wikiTreeGet(\n {\n action: 'getRelatives',\n keys: keysToFetch.join(','),\n getChildren: true,\n getSpouses: true,\n },\n handleCors,\n );\n if (response[0].items === null) {\n throw new Error(`WikiTree profile ${keysToFetch[0]} not found.`);\n }\n const fetchedResults = response[0].items.map(\n (x: {person: Person}) => x.person,\n ) as Person[];\n fetchedResults.forEach((person) => {\n sessionStorage.setItem(\n `wikitree:relatives:${person.Name}`,\n JSON.stringify(person),\n );\n });\n return result.concat(fetchedResults);\n}\n\nexport async function clientLogin(authcode: string) {\n const response = await wikiTreeGet(\n {\n action: 'clientLogin',\n authcode,\n },\n false,\n );\n return response.clientLogin;\n}\n\n/**\n * Loads data from WikiTree to populate an hourglass chart starting from the\n * given person ID.\n */\nexport async function loadWikiTree(\n key: string,\n authcode?: string,\n): Promise {\n // Work around CORS if not in apps.wikitree.com domain.\n const handleCors = window.location.hostname !== 'apps.wikitree.com';\n\n if (!handleCors && !Cookies.get('wikidb_wtb_UserID') && authcode) {\n const loginResult = await clientLogin(authcode);\n if (loginResult.result === 'Success') {\n sessionStorage.clear();\n }\n }\n\n const everyone: Person[] = [];\n\n // Fetch the ancestors of the input person and ancestors of his/her spouses.\n const firstPerson = await getRelatives([key], handleCors);\n if (!firstPerson[0].Name) {\n throw new Error(\n `WikiTree profile ${key} is not accessible. Try logging in.`,\n );\n }\n\n const spouseKeys = Object.values(firstPerson[0].Spouses).map((s) => s.Name);\n const ancestors = await Promise.all(\n [key]\n .concat(spouseKeys)\n .map((personId) => getAncestors(personId, handleCors)),\n );\n const ancestorKeys = ancestors\n .flat()\n .map((person) => person.Name)\n .filter((key) => !!key);\n const ancestorDetails = await getRelatives(ancestorKeys, handleCors);\n everyone.push(...ancestorDetails);\n\n // Limit the number of generations of descendants because there may be tens of\n // generations for some profiles.\n const descendantGenerationLimit = 5;\n\n // Fetch descendants recursively.\n let toFetch = [key];\n let generation = 0;\n while (toFetch.length > 0 && generation <= descendantGenerationLimit) {\n const people = await getRelatives(toFetch, handleCors);\n everyone.push(...people);\n const allSpouses = people.flatMap((person) =>\n Object.values(person.Spouses),\n );\n everyone.push(...allSpouses);\n // Fetch all children.\n toFetch = people.flatMap((person) =>\n Object.values(person.Children).map((c) => c.Name),\n );\n generation++;\n }\n\n // Map from person id to the set of families where they are a spouse.\n const families = new Map>();\n // Map from family id to the set of children.\n const children = new Map>();\n // Map from famliy id to the spouses.\n const spouses = new Map<\n string,\n {wife?: number; husband?: number; spouse?: Person}\n >();\n // Map from numerical id to human-readable id.\n const idToName = new Map();\n\n everyone.forEach((person) => {\n idToName.set(person.Id, person.Name);\n if (person.Mother || person.Father) {\n const famId = getFamilyId(person.Mother, person.Father);\n getSet(families, person.Mother).add(famId);\n getSet(families, person.Father).add(famId);\n getSet(children, famId).add(person.Id);\n spouses.set(famId, {\n wife: person.Mother || undefined,\n husband: person.Father || undefined,\n });\n }\n });\n\n const indis: JsonIndi[] = [];\n const converted = new Set();\n everyone.forEach((person) => {\n if (converted.has(person.Id)) {\n return;\n }\n converted.add(person.Id);\n const indi = convertPerson(person);\n console.log(person, indi);\n if (person.Spouses) {\n Object.values(person.Spouses).forEach((spouse) => {\n const famId = getFamilyId(person.Id, spouse.Id);\n getSet(families, person.Id).add(famId);\n getSet(families, spouse.Id).add(famId);\n const familySpouses =\n person.Gender === 'Male'\n ? {wife: spouse.Id, husband: person.Id, spouse}\n : {wife: person.Id, husband: spouse.Id, spouse};\n spouses.set(famId, familySpouses);\n });\n }\n indi.fams = Array.from(getSet(families, person.Id));\n indis.push(indi);\n });\n\n const fams = Array.from(spouses.entries()).map(([key, value]) => {\n const fam: JsonFam = {\n id: key,\n };\n const wife = value.wife && idToName.get(value.wife);\n if (wife) {\n fam.wife = wife;\n }\n const husband = value.husband && idToName.get(value.husband);\n if (husband) {\n fam.husb = husband;\n }\n fam.children = Array.from(getSet(children, key)).map(\n (child) => idToName.get(child)!,\n );\n if (\n value.spouse &&\n ((value.spouse.marriage_date &&\n value.spouse.marriage_date !== '0000-00-00') ||\n value.spouse.marriage_location)\n ) {\n const parsedDate = parseDate(value.spouse.marriage_date);\n fam.marriage = Object.assign({}, parsedDate, {\n place: value.spouse.marriage_location,\n });\n }\n return fam;\n });\n\n const chartData = normalizeGedcom({indis, fams});\n const gedcom = buildGedcom(indis);\n return {chartData, gedcom};\n}\n\n/** Creates a family identifier given 2 spouse identifiers. */\nfunction getFamilyId(spouse1: number, spouse2: number) {\n if (spouse2 > spouse1) {\n return `${spouse1}_${spouse2}`;\n }\n return `${spouse2}_${spouse1}`;\n}\n\nfunction convertPerson(person: Person): JsonIndi {\n const indi: JsonIndi = {\n id: person.Name,\n };\n if (person.FirstName !== 'Unknown') {\n indi.firstName = person.FirstName;\n }\n if (person.LastNameAtBirth !== 'Unknown') {\n indi.lastName = person.LastNameAtBirth;\n }\n if (person.Mother || person.Father) {\n indi.famc = getFamilyId(person.Mother, person.Father);\n }\n if (person.Gender === 'Male') {\n indi.sex = 'M';\n } else if (person.Gender === 'Female') {\n indi.sex = 'F';\n }\n if (\n (person.BirthDate && person.BirthDate !== '0000-00-00') ||\n person.BirthLocation\n ) {\n const parsedDate = parseDate(\n person.BirthDate,\n person.DataStatus && person.DataStatus.BirthDate,\n );\n indi.birth = Object.assign({}, parsedDate, {place: person.BirthLocation});\n }\n if (\n (person.DeathDate && person.DeathDate !== '0000-00-00') ||\n person.DeathLocation\n ) {\n const parsedDate = parseDate(\n person.DeathDate,\n person.DataStatus && person.DataStatus.DeathDate,\n );\n indi.death = Object.assign({}, parsedDate, {place: person.DeathLocation});\n }\n if (person.PhotoData) {\n indi.images = [{url: `https://wikitree.com${person.PhotoData.path}`}];\n }\n return indi;\n}\n\n/**\n * Parses a date in the format returned by WikiTree and converts in to\n * the format defined by Topola.\n */\nfunction parseDate(date: string, dataStatus?: string): DateOrRange | undefined {\n if (!date) {\n return undefined;\n }\n const matchedDate = date.match(/(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)/);\n if (!matchedDate) {\n return {date: {text: date}};\n }\n const parsedDate: Date = {};\n if (matchedDate[1] !== '0000') {\n parsedDate.year = ~~matchedDate[1];\n }\n if (matchedDate[2] !== '00') {\n parsedDate.month = ~~matchedDate[2];\n }\n if (matchedDate[3] !== '00') {\n parsedDate.day = ~~matchedDate[3];\n }\n if (dataStatus === 'after') {\n return {dateRange: {from: parsedDate}};\n }\n if (dataStatus === 'before') {\n return {dateRange: {to: parsedDate}};\n }\n if (dataStatus === 'guess') {\n parsedDate.qualifier = 'abt';\n }\n return {date: parsedDate};\n}\n\n/**\n * Creates a GEDCOM structure for the purpose of displaying the details\n * panel.\n */\nfunction buildGedcom(indis: JsonIndi[]): GedcomData {\n const gedcomIndis: {[key: string]: GedcomEntry} = {};\n indis.forEach((indi) => {\n // WikiTree URLs replace spaces with underscores.\n const escapedId = indi.id.replace(/ /g, '_');\n gedcomIndis[indi.id] = {\n level: 0,\n pointer: `@${indi.id}@`,\n tag: 'INDI',\n data: '',\n tree: [\n {\n level: 1,\n pointer: '',\n tag: 'NAME',\n data: `${indi.firstName || ''} /${indi.lastName || ''}/`,\n tree: [],\n },\n {\n level: 1,\n pointer: '',\n tag: 'WWW',\n data: `https://www.wikitree.com/wiki/${escapedId}`,\n tree: [],\n },\n ],\n };\n });\n\n return {\n head: {level: 0, pointer: '', tag: 'HEAD', data: '', tree: []},\n indis: gedcomIndis,\n fams: {},\n other: {},\n };\n}\n\n/**\n * Returns a set which is a value from a SetMultimap. If the key doesn't exist,\n * an empty set is added to the map.\n */\nfunction getSet(map: Map>, key: K): Set {\n const set = map.get(key);\n if (set) {\n return set;\n }\n const newSet = new Set();\n map.set(key, newSet);\n return newSet;\n}\n","import naturalSort from 'javascript-natural-sort';\nimport lunr from 'lunr';\nimport {GedcomData, pointerToId} from './gedcom_util';\nimport {GedcomEntry} from 'parse-gedcom';\n\nconst MAX_RESULTS = 8;\n\nexport interface SearchResult {\n id: string;\n indi: GedcomEntry;\n}\n\nexport interface SearchIndex {\n search(input: string): SearchResult[];\n}\n\n/** Removes accents from letters, e.g. ó->o, ę->e. */\nfunction normalize(input: string) {\n return input\n .toLocaleLowerCase()\n .normalize('NFD')\n .replace(/[\\u0300-\\u036f]/g, '')\n .replace(/\\u0142/g, 'l'); // Special case: ł is not affected by NFD.\n}\n\n/** Comparator to sort by score first, then by id. */\nfunction compare(a: lunr.Index.Result, b: lunr.Index.Result) {\n if (a.score !== b.score) {\n return b.score - a.score;\n }\n return naturalSort(a.ref, b.ref);\n}\n\n/** Returns all last names of all husbands as a space-separated string. */\nfunction getHusbandLastName(indi: GedcomEntry, gedcom: GedcomData): string {\n return indi.tree\n .filter((entry) => entry.tag === 'FAMS')\n .map((entry) => gedcom.fams[pointerToId(entry.data)])\n .filter((entry) => !!entry)\n .map((entry) => {\n const husband = entry.tree.find((entry) => entry.tag === 'HUSB');\n const husbandId = husband && pointerToId(husband.data);\n return (\n husbandId &&\n husbandId !== pointerToId(indi.pointer) &&\n gedcom.indis[husbandId]\n );\n })\n .filter((entry) => !!entry)\n .flatMap((husband) =>\n (husband as GedcomEntry).tree\n .filter((entry) => entry.tag === 'NAME')\n .map((entry) => {\n const names = entry.data.split('/');\n return names.length >= 2 ? names[1] : '';\n }),\n )\n .join(' ');\n}\n\nclass LunrSearchIndex implements SearchIndex {\n private index: lunr.Index | undefined;\n\n constructor(private gedcom: GedcomData) {}\n\n initialize() {\n const self = this;\n this.index = lunr(function() {\n this.ref('id');\n this.field('id');\n this.field('name', {boost: 10});\n this.field('normalizedName', {boost: 8});\n this.field('spouseLastName', {boost: 2});\n this.field('normalizedSpouseLastName', {boost: 2});\n\n for (let id in self.gedcom.indis) {\n const indi = self.gedcom.indis[id];\n const name = indi.tree\n .filter((entry) => entry.tag === 'NAME')\n .map((entry) => entry.data)\n .join(' ');\n const spouseLastName = getHusbandLastName(indi, self.gedcom);\n this.add({\n id,\n name,\n normalizedName: normalize(name),\n spouseLastName,\n normalizedSpouseLastName: normalize(spouseLastName),\n });\n }\n });\n }\n\n public search(input: string) {\n const query = input\n .split(' ')\n .filter((s) => !!s)\n .map((s) => `+${s}*`)\n .join(' ');\n const results = this.index!.search(query);\n return results\n .sort(compare)\n .slice(0, MAX_RESULTS)\n .map((result) => ({id: result.ref, indi: this.gedcom.indis[result.ref]}));\n }\n}\n\n/** Builds a search index from data. */\nexport function buildSearchIndex(gedcom: GedcomData): SearchIndex {\n const index = new LunrSearchIndex(gedcom);\n index.initialize();\n return index;\n}\n","import * as React from 'react';\nimport {GedcomEntry} from 'parse-gedcom';\nimport {InjectedIntl} from 'react-intl';\nimport {SearchResult} from './search_index';\nimport {translateDate} from './date_util';\n\nfunction getNameLine(result: SearchResult) {\n const nameTag = result.indi.tree.find((entry) => entry.tag === 'NAME');\n const name =\n nameTag &&\n nameTag.data\n .split('/')\n .filter((s) => !!s)\n .join(' ');\n if (result.id.length > 8) {\n return name;\n }\n return (\n <>\n {name} ({result.id})\n \n );\n}\n\nfunction getDate(indi: GedcomEntry, tag: string, intl: InjectedIntl) {\n const eventEntry = indi.tree.find((entry) => entry.tag === tag);\n const dateEntry =\n eventEntry && eventEntry.tree.find((entry) => entry.tag === 'DATE');\n return (dateEntry && translateDate(dateEntry.data, intl)) || '';\n}\n\nfunction getDescriptionLine(indi: GedcomEntry, intl: InjectedIntl) {\n const birthDate = getDate(indi, 'BIRT', intl);\n const deathDate = getDate(indi, 'DEAT', intl);\n if (!deathDate) {\n return birthDate;\n }\n return `${birthDate} – ${deathDate}`;\n}\n\n/** Produces an object that is displayed in the Semantic UI Search results. */\nexport function displaySearchResult(result: SearchResult, intl: InjectedIntl) {\n return {\n id: result.id,\n key: result.id,\n title: getNameLine(result),\n description: getDescriptionLine(result.indi, intl),\n };\n}\n","import * as queryString from 'query-string';\nimport * as React from 'react';\nimport Cookies from 'js-cookie';\nimport debounce from 'debounce';\nimport md5 from 'md5';\nimport {analyticsEvent} from './analytics';\nimport {buildSearchIndex, SearchIndex} from './search_index';\nimport {displaySearchResult} from './search_util';\nimport {FormattedMessage, intlShape} from 'react-intl';\nimport {GedcomData} from './gedcom_util';\nimport {IndiInfo} from 'topola';\nimport {Link} from 'react-router-dom';\nimport {RouteComponentProps} from 'react-router-dom';\nimport {\n Header,\n Button,\n Icon,\n Menu,\n Modal,\n Input,\n Form,\n Dropdown,\n Search,\n SearchProps,\n SearchResultProps,\n} from 'semantic-ui-react';\n\nenum WikiTreeLoginState {\n UNKNOWN,\n NOT_LOGGED_IN,\n LOGGED_IN,\n}\n\n/** Menus and dialogs state. */\ninterface State {\n loadUrlDialogOpen: boolean;\n url?: string;\n wikiTreeLoginState: WikiTreeLoginState;\n wikiTreeLoginUsername?: string;\n searchResults: SearchResultProps[];\n}\n\ninterface EventHandlers {\n onSelection: (indiInfo: IndiInfo) => void;\n onPrint: () => void;\n onDownloadPdf: () => void;\n onDownloadPng: () => void;\n onDownloadSvg: () => void;\n}\n\ninterface Props {\n /** True if the application is currently showing a chart. */\n showingChart: boolean;\n /** Data used for the search index. */\n gedcom?: GedcomData;\n standalone: boolean;\n /** Whether to show the \"All relatives\" chart type in the menu. */\n allowAllRelativesChart: boolean;\n eventHandlers: EventHandlers;\n /** Whether to show the 'Log in to WikiTree' button. */\n showWikiTreeLogin: boolean;\n}\n\nfunction loadFileAsText(file: File): Promise {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = (evt: ProgressEvent) => {\n resolve((evt.target as FileReader).result as string);\n };\n reader.readAsText(file);\n });\n}\n\nfunction isImageFileName(fileName: string) {\n const lower = fileName.toLowerCase();\n return lower.endsWith('.jpg') || lower.endsWith('.png');\n}\n\nexport class TopBar extends React.Component<\n RouteComponentProps & Props,\n State\n> {\n state: State = {\n loadUrlDialogOpen: false,\n searchResults: [],\n wikiTreeLoginState: WikiTreeLoginState.UNKNOWN,\n };\n /** Make intl appear in this.context. */\n static contextTypes = {\n intl: intlShape,\n };\n\n urlInputRef: React.RefObject = React.createRef();\n wikiTreeLoginFormRef: React.RefObject = React.createRef();\n wikiTreeReturnUrlRef: React.RefObject = React.createRef();\n searchRef?: {setValue(value: string): void};\n searchIndex?: SearchIndex;\n\n /** Handles the \"Upload file\" button. */\n private async handleUpload(event: React.SyntheticEvent) {\n const files = (event.target as HTMLInputElement).files;\n if (!files || !files.length) {\n return;\n }\n const filesArray = Array.from(files);\n (event.target as HTMLInputElement).value = ''; // Reset the file input.\n analyticsEvent('upload_files_selected', {\n event_value: files.length,\n });\n\n const gedcomFile =\n filesArray.length === 1\n ? filesArray[0]\n : filesArray.find((file) => file.name.toLowerCase().endsWith('.ged')) ||\n filesArray[0];\n\n // Convert uploaded images to object URLs.\n const images = filesArray\n .filter(\n (file) => file.name !== gedcomFile.name && isImageFileName(file.name),\n )\n .map((file) => ({\n name: file.name,\n url: URL.createObjectURL(file),\n }));\n const imageMap = new Map(\n images.map((entry) => [entry.name, entry.url] as [string, string]),\n );\n\n const data = await loadFileAsText(gedcomFile);\n const imageFileNames = images\n .map((image) => image.name)\n .sort()\n .join('|');\n // Hash GEDCOM contents with uploaded image file names.\n const hash = md5(md5(data) + imageFileNames);\n\n // Use history.replace() when reuploading the same file and history.push() when loading\n // a new file.\n const search = queryString.parse(this.props.location.search);\n const historyPush =\n search.file === hash\n ? this.props.history.replace\n : this.props.history.push;\n\n historyPush({\n pathname: '/view',\n search: queryString.stringify({file: hash}),\n state: {data, images: imageMap},\n });\n }\n\n /** Opens the \"Load from URL\" dialog. */\n private openLoadUrlDialog() {\n this.setState(\n Object.assign({}, this.state, {loadUrlDialogOpen: true}),\n () => this.urlInputRef.current!.focus(),\n );\n }\n\n /** Cancels the \"Load from URL\" dialog. */\n private handleClose() {\n this.setState(Object.assign({}, this.state, {loadUrlDialogOpen: false}));\n }\n\n /** Upload button clicked in the \"Load from URL\" dialog. */\n private handleLoad() {\n this.setState(\n Object.assign({}, this.state, {\n loadUrlDialogOpen: false,\n }),\n );\n if (this.state.url) {\n analyticsEvent('url_selected');\n this.props.history.push({\n pathname: '/view',\n search: queryString.stringify({url: this.state.url}),\n });\n }\n }\n\n /** Called when the URL input is typed into. */\n private handleUrlChange(event: React.SyntheticEvent) {\n this.setState(\n Object.assign({}, this.state, {\n url: (event.target as HTMLInputElement).value,\n }),\n );\n }\n\n /** On search input change. */\n private handleSearch(input: string | undefined) {\n if (!input) {\n return;\n }\n const results = this.searchIndex!.search(input).map((result) =>\n displaySearchResult(result, this.context.intl),\n );\n this.setState(Object.assign({}, this.state, {searchResults: results}));\n }\n\n /** On search result selected. */\n private handleResultSelect(id: string) {\n analyticsEvent('search_result_selected');\n this.props.eventHandlers.onSelection({id, generation: 0});\n this.searchRef!.setValue('');\n }\n\n private initializeSearchIndex() {\n if (this.props.gedcom) {\n this.searchIndex = buildSearchIndex(this.props.gedcom);\n }\n }\n\n changeView(view: string) {\n const location = this.props.location;\n const search = queryString.parse(location.search);\n if (search.view !== view) {\n search.view = view;\n location.search = queryString.stringify(search);\n this.props.history.push(location);\n }\n }\n\n /**\n * Redirect to the WikiTree Apps login page with a return URL pointing to\n * Topola Viewer hosted on apps.wikitree.com.\n */\n private wikiTreeLogin() {\n const wikiTreeTopolaUrl =\n 'https://apps.wikitree.com/apps/wiech13/topola-viewer';\n // Append '&' because the login page appends '?authcode=...' to this URL.\n // TODO: remove ?authcode if it is in the current URL.\n const returnUrl = `${wikiTreeTopolaUrl}${window.location.hash}&`;\n this.wikiTreeReturnUrlRef.current!.value = returnUrl;\n this.wikiTreeLoginFormRef.current!.submit();\n }\n\n private checkWikiTreeLoginState() {\n const wikiTreeLoginState =\n Cookies.get('wikidb_wtb_UserID') !== undefined\n ? WikiTreeLoginState.LOGGED_IN\n : WikiTreeLoginState.NOT_LOGGED_IN;\n if (this.state.wikiTreeLoginState !== wikiTreeLoginState) {\n const wikiTreeLoginUsername = Cookies.get('wikidb_wtb_UserName');\n this.setState(\n Object.assign({}, this.state, {\n wikiTreeLoginState,\n wikiTreeLoginUsername,\n }),\n );\n }\n }\n\n async componentDidMount() {\n this.checkWikiTreeLoginState();\n this.initializeSearchIndex();\n }\n\n componentDidUpdate(prevProps: Props) {\n this.checkWikiTreeLoginState();\n if (prevProps.gedcom !== this.props.gedcom) {\n this.initializeSearchIndex();\n }\n }\n\n private loadFromUrlModal() {\n return (\n this.handleClose()}\n centered={false}\n >\n
\n \n txt}\n />\n
\n \n
this.handleLoad()}>\n this.handleUrlChange(e)}\n ref={this.urlInputRef}\n />\n

\n \n cors-anywhere.herokuapp.com\n \n ),\n }}\n />\n

\n \n
\n \n \n \n \n \n );\n }\n\n private chartMenus() {\n if (!this.props.showingChart) {\n return null;\n }\n return (\n <>\n this.props.eventHandlers.onPrint()}>\n \n \n \n\n \n \n \n
\n }\n className=\"item\"\n >\n \n this.props.eventHandlers.onDownloadPdf()}\n >\n \n \n this.props.eventHandlers.onDownloadPng()}\n >\n \n \n this.props.eventHandlers.onDownloadSvg()}\n >\n \n \n \n \n\n \n \n \n \n }\n className=\"item\"\n >\n \n this.changeView('hourglass')}>\n \n \n \n {this.props.allowAllRelativesChart ? (\n this.changeView('relatives')}>\n \n \n \n ) : null}\n this.changeView('fancy')}>\n \n \n \n \n \n\n , data: SearchProps) =>\n this.handleSearch(data.value),\n 200,\n )}\n onResultSelect={(_, data) => this.handleResultSelect(data.result.id)}\n results={this.state.searchResults}\n noResultsMessage={this.context.intl.formatMessage({\n id: 'menu.search.no_results',\n defaultMessage: 'No results found',\n })}\n placeholder={this.context.intl.formatMessage({\n id: 'menu.search.placeholder',\n defaultMessage: 'Search for people',\n })}\n selectFirstResult={true}\n ref={(ref) =>\n (this.searchRef = (ref as unknown) as {\n setValue(value: string): void;\n })\n }\n />\n \n );\n }\n\n private fileMenus() {\n if (!this.props.standalone) {\n return null;\n }\n return (\n <>\n \n \n Topola Genealogy\n \n \n this.openLoadUrlDialog()}>\n \n \n \n this.handleUpload(e)}\n />\n \n \n );\n }\n\n private wikiTreeLoginMenu() {\n if (!this.props.showWikiTreeLogin) {\n return null;\n }\n const wikiTreeLogoUrl =\n 'https://www.wikitree.com/photo.php/a/a5/WikiTree_Images.png';\n switch (this.state.wikiTreeLoginState) {\n case WikiTreeLoginState.NOT_LOGGED_IN:\n return (\n this.wikiTreeLogin()}>\n \n \n \n \n \n \n \n );\n case WikiTreeLoginState.LOGGED_IN:\n const tooltip = this.state.wikiTreeLoginUsername\n ? this.context.intl.formatMessage(\n {\n id: 'menu.wikitree_popup_username',\n defaultMessage: 'Logged in to WikiTree as {username}',\n },\n {username: this.state.wikiTreeLoginUsername},\n )\n : this.context.intl.formatMessage({\n id: 'menu.wikitree_popup',\n defaultMessage: 'Logged in to WikiTree',\n });\n return (\n \n \n \n \n );\n default:\n return null;\n }\n }\n\n private sourceLink() {\n return (\n \n \n \n );\n }\n\n private poweredByLink() {\n return (\n \n \n \n );\n }\n\n render() {\n return (\n \n {this.fileMenus()}\n {this.chartMenus()}\n \n {this.wikiTreeLoginMenu()}\n {this.props.standalone ? this.sourceLink() : this.poweredByLink()}\n \n {this.loadFromUrlModal()}\n \n );\n }\n}\n","import * as H from 'history';\nimport * as queryString from 'query-string';\nimport * as React from 'react';\nimport {analyticsEvent} from './analytics';\nimport {Chart, ChartType} from './chart';\nimport {Details} from './details';\nimport {FormattedMessage} from 'react-intl';\nimport {getSelection, loadFromUrl, loadGedcom} from './load_data';\nimport {getSoftware, TopolaData} from './gedcom_util';\nimport {IndiInfo} from 'topola';\nimport {intlShape} from 'react-intl';\nimport {Intro} from './intro';\nimport {Loader, Message, Portal, Responsive} from 'semantic-ui-react';\nimport {loadWikiTree} from './wikitree';\nimport {Redirect, Route, RouteComponentProps, Switch} from 'react-router-dom';\nimport {TopBar} from './top_bar';\n\n/** Shows an error message in the middle of the screen. */\nfunction ErrorMessage(props: {message?: string}) {\n return (\n \n \n \n \n

{props.message}

\n
\n );\n}\n\ninterface ErrorPopupProps {\n message?: string;\n open: boolean;\n onDismiss: () => void;\n}\n\n/**\n * Shows a dismissable error message in the bottom left corner of the screen.\n */\nfunction ErrorPopup(props: ErrorPopupProps) {\n return (\n \n \n \n \n \n

{props.message}

\n
\n
\n );\n}\n\n/**\n * Message types used in embedded mode.\n * When the parent is ready to receive messages, it sends PARENT_READY.\n * When the child (this app) is ready to receive messages, it sends READY.\n * When the child receives PARENT_READY, it sends READY.\n * When the parent receives READY, it sends data in a GEDCOM message.\n */\nenum EmbeddedMessageType {\n GEDCOM = 'gedcom',\n READY = 'ready',\n PARENT_READY = 'parent_ready',\n}\n\n/** Message sent to parent or received from parent in embedded mode. */\ninterface EmbeddedMessage {\n message: EmbeddedMessageType;\n}\n\ninterface GedcomMessage extends EmbeddedMessage {\n message: EmbeddedMessageType.GEDCOM;\n gedcom?: string;\n}\n\n/** Interface encapsulating functions specific for a data source. */\ninterface DataSource {\n /**\n * Returns true if the application is now loading a completely new data set\n * and the existing one should be wiped.\n */\n isNewData(args: Arguments, state: State): boolean;\n /** Loads data from the data source. */\n loadData(args: Arguments): Promise;\n}\n\n/** Files opened from the local computer. */\nclass UploadedDataSource implements DataSource {\n isNewData(args: Arguments, state: State): boolean {\n return (\n args.hash !== state.hash ||\n !!(args.gedcom && !state.loading && !state.data)\n );\n }\n\n async loadData(args: Arguments): Promise {\n try {\n const data = await loadGedcom(args.hash!, args.gedcom, args.images);\n const software = getSoftware(data.gedcom.head);\n analyticsEvent('upload_file_loaded', {\n event_label: software,\n event_value: (args.images && args.images.size) || 0,\n });\n return data;\n } catch (error) {\n analyticsEvent('upload_file_error');\n throw error;\n }\n }\n}\n\n/** GEDCOM file loaded by pointing to a URL. */\nclass GedcomUrlDataSource implements DataSource {\n isNewData(args: Arguments, state: State): boolean {\n return args.url !== state.url;\n }\n\n async loadData(args: Arguments): Promise {\n try {\n const data = await loadFromUrl(args.url!, args.handleCors);\n const software = getSoftware(data.gedcom.head);\n analyticsEvent('upload_file_loaded', {event_label: software});\n return data;\n } catch (error) {\n analyticsEvent('url_file_error');\n throw error;\n }\n }\n}\n\n/** Loading data from the WikiTree API. */\nclass WikiTreeDataSource implements DataSource {\n isNewData(args: Arguments, state: State): boolean {\n // WikiTree is always a single data source.\n return false;\n }\n\n async loadData(args: Arguments): Promise {\n try {\n const data = await loadWikiTree(args.indi!, args.authcode);\n analyticsEvent('wikitree_loaded');\n return data;\n } catch (error) {\n analyticsEvent('wikitree_error');\n throw error;\n }\n }\n}\n\n/** Supported data sources. */\nenum DataSourceEnum {\n UPLOADED,\n GEDCOM_URL,\n WIKITREE,\n}\n\n/** Mapping from data source identifier to data source handler functions. */\nconst DATA_SOURCES = new Map([\n [DataSourceEnum.UPLOADED, new UploadedDataSource()],\n [DataSourceEnum.GEDCOM_URL, new GedcomUrlDataSource()],\n [DataSourceEnum.WIKITREE, new WikiTreeDataSource()],\n]);\n\n/** Arguments passed to the application, primarily through URL parameters. */\ninterface Arguments {\n showSidePanel: boolean;\n embedded: boolean;\n url?: string;\n indi?: string;\n generation?: number;\n hash?: string;\n handleCors: boolean;\n standalone: boolean;\n source?: DataSourceEnum;\n authcode?: string;\n chartType: ChartType;\n gedcom?: string;\n images?: Map;\n enableZoom: boolean;\n}\n\n/**\n * Retrieve arguments passed into the application through the URL and uploaded\n * data.\n */\nfunction getArguments(location: H.Location): Arguments {\n const search = queryString.parse(location.search);\n const getParam = (name: string) => {\n const value = search[name];\n return typeof value === 'string' ? value : undefined;\n };\n\n const parsedGen = Number(getParam('gen'));\n const view = getParam('view');\n const chartTypes = new Map([\n ['relatives', ChartType.Relatives],\n ['fancy', ChartType.Fancy],\n ]);\n const hash = getParam('file');\n const url = getParam('url');\n const source =\n getParam('source') === 'wikitree'\n ? DataSourceEnum.WIKITREE\n : hash\n ? DataSourceEnum.UPLOADED\n : url\n ? DataSourceEnum.GEDCOM_URL\n : undefined;\n return {\n showSidePanel: getParam('sidePanel') !== 'false', // True by default.\n embedded: getParam('embedded') === 'true', // False by default.\n url,\n indi: getParam('indi'),\n generation: !isNaN(parsedGen) ? parsedGen : undefined,\n hash,\n handleCors: getParam('handleCors') !== 'false', // True by default.\n standalone: getParam('standalone') !== 'false', // True by default.\n source,\n authcode: getParam('?authcode'),\n\n // Hourglass is the default view.\n chartType: chartTypes.get(view) || ChartType.Hourglass,\n\n gedcom: location.state && location.state.data,\n images: location.state && location.state.images,\n enableZoom: getParam('enableZoom') !== 'false', // True by default.\n };\n}\n\n/** Returs true if the changes object has values that are different than those in state. */\nfunction hasUpdatedValues(state: T, changes: Partial | undefined) {\n if (!changes) {\n return false;\n }\n return Object.entries(changes).some(\n ([key, value]) => value !== undefined && state[key] !== value,\n );\n}\n\ninterface State {\n /** Loaded data. */\n data?: TopolaData;\n /** Selected individual. */\n selection?: IndiInfo;\n /** Hash of the GEDCOM contents. */\n hash?: string;\n /** Error to display. */\n error?: string;\n /** True if data is currently being loaded. */\n loading: boolean;\n /** URL of the data that is loaded or is being loaded. */\n url?: string;\n /** Whether the side panel is shown. */\n showSidePanel?: boolean;\n /** Whether the app is in embedded mode, i.e. embedded in an iframe. */\n embedded: boolean;\n /** Whether the app is in standalone mode, i.e. showing 'open file' menus. */\n standalone: boolean;\n /** Type of displayed chart. */\n chartType: ChartType;\n /** Whether to show the error popup. */\n showErrorPopup: boolean;\n /** Source of the data. */\n source?: DataSourceEnum;\n loadingMore?: boolean;\n /** Whether the zoom functionality is enabled. */\n enableZoom: boolean;\n}\n\nexport class App extends React.Component {\n state: State = {\n loading: false,\n embedded: false,\n standalone: true,\n chartType: ChartType.Hourglass,\n showErrorPopup: false,\n enableZoom: false,\n };\n chartRef: Chart | null = null;\n\n /** Make intl appear in this.context. */\n static contextTypes = {\n intl: intlShape,\n };\n\n /** Sets the state with a new individual selection and chart type. */\n private updateDisplay(\n selection: IndiInfo,\n otherStateChanges?: Partial,\n ) {\n if (\n !this.state.selection ||\n this.state.selection.id !== selection.id ||\n this.state.selection!.generation !== selection.generation ||\n hasUpdatedValues(this.state, otherStateChanges)\n ) {\n this.setState(\n Object.assign({}, this.state, {selection}, otherStateChanges),\n );\n }\n }\n\n /** Sets error message after data load failure. */\n private setError(error: string) {\n this.setState(\n Object.assign({}, this.state, {\n error: error,\n loading: false,\n }),\n );\n }\n\n private async onMessage(message: EmbeddedMessage) {\n if (message.message === EmbeddedMessageType.PARENT_READY) {\n // Parent didn't receive the first 'ready' message, so we need to send it again.\n window.parent.postMessage({message: EmbeddedMessageType.READY}, '*');\n } else if (message.message === EmbeddedMessageType.GEDCOM) {\n const gedcom = (message as GedcomMessage).gedcom;\n if (!gedcom) {\n return;\n }\n try {\n const data = await loadGedcom('', gedcom);\n const software = getSoftware(data.gedcom.head);\n analyticsEvent('embedded_file_loaded', {\n event_label: software,\n });\n // Set state with data.\n this.setState(\n Object.assign({}, this.state, {\n data,\n selection: getSelection(data.chartData),\n error: undefined,\n loading: false,\n }),\n );\n } catch (error) {\n analyticsEvent('embedded_file_error');\n this.setError(error.message);\n }\n }\n }\n\n componentDidMount() {\n this.componentDidUpdate();\n }\n\n async componentDidUpdate() {\n if (this.props.location.pathname !== '/view') {\n return;\n }\n\n const args = getArguments(this.props.location);\n\n if (args.embedded && !this.state.embedded) {\n this.setState(\n Object.assign({}, this.state, {\n embedded: true,\n standalone: false,\n showSidePanel: args.showSidePanel,\n }),\n );\n // Notify the parent window that we are ready.\n window.parent.postMessage('ready', '*');\n window.addEventListener('message', (data) => this.onMessage(data.data));\n }\n if (args.embedded) {\n // If the app is embedded, do not run the normal loading code.\n return;\n }\n\n const dataSource = DATA_SOURCES.get(args.source!);\n\n if (!dataSource) {\n this.props.history.replace({pathname: '/'});\n } else if (\n (!this.state.loading && !this.state.data && !this.state.error) ||\n args.source !== this.state.source ||\n dataSource.isNewData(args, this.state)\n ) {\n // Set loading state.\n this.setState(\n Object.assign({}, this.state, {\n data: undefined,\n selection: undefined,\n hash: args.hash,\n error: undefined,\n loading: true,\n url: args.url,\n standalone: args.standalone,\n chartType: args.chartType,\n source: args.source,\n enableZoom: args.enableZoom,\n }),\n );\n try {\n const data = await dataSource.loadData(args);\n\n // Set state with data.\n this.setState(\n Object.assign({}, this.state, {\n data,\n hash: args.hash,\n selection: getSelection(data.chartData, args.indi, args.generation),\n error: undefined,\n loading: false,\n url: args.url,\n showSidePanel: args.showSidePanel,\n standalone: args.standalone,\n chartType: args.chartType,\n source: args.source,\n enableZoom: args.enableZoom,\n }),\n );\n } catch (error) {\n this.setError(error.message);\n }\n } else if (this.state.data && this.state.selection) {\n // Update selection if it has changed in the URL.\n const selection = getSelection(\n this.state.data.chartData,\n args.indi,\n args.generation,\n );\n const loadMoreFromWikitree =\n args.source === DataSourceEnum.WIKITREE &&\n (!this.state.selection || this.state.selection.id !== selection.id);\n this.updateDisplay(selection, {\n chartType: args.chartType,\n loadingMore: loadMoreFromWikitree || undefined,\n });\n if (loadMoreFromWikitree) {\n const data = await loadWikiTree(args.indi!);\n this.setState(\n Object.assign({}, this.state, {\n data,\n hash: args.hash,\n selection: getSelection(data.chartData, args.indi, args.generation),\n error: undefined,\n loading: false,\n url: args.url,\n showSidePanel: args.showSidePanel,\n standalone: args.standalone,\n chartType: args.chartType,\n source: args.source,\n enableZoom: args.enableZoom,\n loadingMore: false,\n }),\n );\n }\n }\n }\n\n /**\n * Called when the user clicks an individual box in the chart.\n * Updates the browser URL.\n */\n private onSelection = (selection: IndiInfo) => {\n analyticsEvent('selection_changed');\n if (this.state.embedded) {\n // In embedded mode the URL doesn't change.\n this.updateDisplay(selection);\n return;\n }\n const location = this.props.location;\n const search = queryString.parse(location.search);\n search.indi = selection.id;\n search.gen = String(selection.generation);\n location.search = queryString.stringify(search);\n this.props.history.push(location);\n };\n\n private onPrint = () => {\n analyticsEvent('print');\n this.chartRef && this.chartRef.print();\n };\n\n private showErrorPopup(message: string) {\n this.setState(\n Object.assign({}, this.state, {\n showErrorPopup: true,\n error: message,\n }),\n );\n }\n\n private onDownloadPdf = async () => {\n analyticsEvent('download_pdf');\n try {\n this.chartRef && (await this.chartRef.downloadPdf());\n } catch (e) {\n this.showErrorPopup(\n this.context.intl.formatMessage({\n id: 'error.failed_pdf',\n defaultMessage:\n 'Failed to generate PDF file.' +\n ' Please try with a smaller diagram or download an SVG file.',\n }),\n );\n }\n };\n\n private onDownloadPng = async () => {\n analyticsEvent('download_png');\n try {\n this.chartRef && (await this.chartRef.downloadPng());\n } catch (e) {\n this.showErrorPopup(\n this.context.intl.formatMessage({\n id: 'error.failed_png',\n defaultMessage:\n 'Failed to generate PNG file.' +\n ' Please try with a smaller diagram or download an SVG file.',\n }),\n );\n }\n };\n\n private onDownloadSvg = () => {\n analyticsEvent('download_svg');\n this.chartRef && this.chartRef.downloadSvg();\n };\n\n onDismissErrorPopup = () => {\n this.setState(\n Object.assign({}, this.state, {\n showErrorPopup: false,\n }),\n );\n };\n\n private renderMainArea = () => {\n if (this.state.data && this.state.selection) {\n return (\n
\n \n {this.state.loadingMore ? (\n \n ) : null}\n (this.chartRef = ref)}\n enableZoom={this.state.enableZoom}\n />\n {this.state.showSidePanel ? (\n \n \n \n ) : null}\n
\n );\n }\n if (this.state.error) {\n return ;\n }\n return ;\n };\n\n render() {\n return (\n <>\n (\n \n )}\n />\n \n \n \n \n \n \n );\n }\n}\n","import * as locale_en from 'react-intl/locale-data/en';\nimport * as locale_pl from 'react-intl/locale-data/pl';\nimport * as React from 'react';\nimport * as ReactDOM from 'react-dom';\nimport messages_pl from './translations/pl.json';\nimport {addLocaleData} from 'react-intl';\nimport {App} from './app';\nimport {detect} from 'detect-browser';\nimport {HashRouter as Router, Route} from 'react-router-dom';\nimport {IntlProvider} from 'react-intl';\nimport './index.css';\nimport 'semantic-ui-css/semantic.min.css';\nimport 'canvas-toBlob';\n\naddLocaleData([...locale_en, ...locale_pl]);\n\nconst messages = {\n pl: messages_pl,\n};\nconst language = navigator.language && navigator.language.split(/[-_]/)[0];\n\nconst browser = detect();\n\nif (browser && browser.name === 'ie') {\n ReactDOM.render(\n

\n Topola Genealogy Viewer does not support Internet Explorer. Please try a\n different browser.\n

,\n document.querySelector('#root'),\n );\n} else {\n ReactDOM.render(\n \n \n \n \n ,\n document.querySelector('#root'),\n );\n}\n"],"sourceRoot":""} \ No newline at end of file diff --git a/static/js/main.a40a575c.chunk.js b/static/js/main.a40a575c.chunk.js new file mode 100644 index 0000000..6e49c2e --- /dev/null +++ b/static/js/main.a40a575c.chunk.js @@ -0,0 +1,2 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[0],{252:function(e){e.exports={"menu.load_from_url":"Otw\xf3rz URL","menu.load_from_file":"Otw\xf3rz plik","menu.print":"Drukuj","menu.download":"Pobierz","menu.pdf_file":"Plik PDF","menu.png_file":"Plik PNG","menu.svg_file":"Plik SVG","menu.view":"Widok","menu.hourglass":"Wykres klepsydrowy","menu.relatives":"Wszyscy krewni","menu.fancy":"Ozdobne drzewo (eksperymentalne)","menu.wikitree_login":"Zaloguj do WikiTree","menu.wikitree_logged_in":"Zalogowano","menu.wikitree_popup_username":"Zalogowano do WikiTree jako {username}","menu.wikitree_popup":"Zalogowano do WikiTree","menu.github":"\u0179r\xf3d\u0142a na GitHub","menu.powered_by":"Topola Genealogy","menu.search.placeholder":"Szukaj osoby","menu.search.no_results":"Brak wynik\xf3w","intro.title":"Topola Genealogy","intro.description":"Topola Genealogy pozwala przegl\u0105da\u0107 drzewo genealogiczne w interaktywny spos\xf3b.","intro.instructions":"Kliknij OTW\xd3RZ URL lub OTW\xd3RZ PLIK, aby za\u0142adowa\u0107 plik GEDCOM. Wi\u0119kszo\u015b\u0107 program\xf3w genealogicznych posiada funkcj\u0119 eksportu do pliku GEDCOM.","intro.examples":"Poni\u017cej jest kilka przyk\u0142ad\xf3w znalezionych w Internecie:","intro.from":"\u017ar\xf3d\u0142o:","intro.privacy":"Prywatno\u015b\u0107","intro.privacy_note":'U\u017cywaj\u0105c funkcji "Otw\xf3rz plik", Twoje dane nie s\u0105 nigdzie wysy\u0142ane i pozostaj\u0105 na Twoim komputerze. U\u017cywaj\u0105c funkcji "Otw\xf3rz URL", dane z podanego adresu przesy\u0142ane s\u0105 przez us\u0142ug\u0119 {link} w celu umo\u017cliwienia za\u0142adowania danych z innej domeny (CORS).',"load_from_url.title":"Otw\xf3rz z adresu URL","load_from_url.comment":"Dane z podanego adresu URL zostan\u0105 za\u0142adowane poprzez us\u0142ug\u0119 {link} w celu unikni\u0119cia problem\xf3w z CORS.","load_from_url.cancel":"Anuluj","load_from_url.load":"Otw\xf3rz","gedcom.BAPM":"Chrzest","gedcom.BIRT":"Narodziny","gedcom.BURI":"Pogrzeb","gedcom.CHR":"Chrzest","gedcom.DEAT":"\u015amier\u0107","gedcom.EMAIL":"E-mail","gedcom.EVEN":"Wydarzenie","gedcom.OCCU":"Zaw\xf3d","gedcom.TITL":"Tytu\u0142","gedcom.WWW":"Strona WWW","date.abt":"oko\u0142o","date.cal":"wyliczone","date.est":"oszacowane","date.between":"mi\u0119dzy {from} a {to}","date.after":"po {from}","date.before":"przed {to}","error.error":"B\u0142\u0105d","error.failed_pdf":"Nie uda\u0142o si\u0119 utworzy\u0107 pliku PDF. Spr\xf3buj jeszcze raz z mniejszym diagramem lub pobierz plik SVG.","error.failed_png":"Nie uda\u0142o si\u0119 utworzy\u0107 pliku PNG. Spr\xf3buj jeszcze raz z mniejszym diagramem lub pobierz plik SVG.","error.failed_to_load_file":"B\u0142\u0105d wczytywania pliku"}},253:function(e,t){},260:function(e,t,n){e.exports=n.p+"static/media/topola.060eef13.jpg"},297:function(e,t,n){e.exports=n(528)},309:function(e,t){},315:function(e,t){},525:function(e,t,n){},528:function(e,t,n){"use strict";n.r(t);var a=n(44),r=n(250),i=n(251),o=n(0),s=n(64),c=n(252),l=n(16),u=n(39),d=n(37),f=n(40),m=n(65),h=n(14),p=n.n(h),g=n(18),v=n(27),w=n(28),b=n(32);function y(e,t){window.gtag("event",e,t)}var E,k=n(17),O=n(255),x=n.n(O),D=n(168),S=n(33),j=n(553);function M(e){var t=new FileReader;return t.readAsDataURL(e),new Promise(function(e,n){t.onload=function(t){return e(t.target.result)}})}function _(e){return T.apply(this,arguments)}function T(){return(T=Object(g.a)(p.a.mark(function e(t){var n,a,r,i;return p.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(n=t.href.baseVal){e.next=3;break}return e.abrupt("return");case 3:return e.prev=3,e.next=6,fetch(n);case 6:return a=e.sent,e.next=9,a.blob();case 9:return r=e.sent,e.next=12,M(r);case 12:i=e.sent,t.href.baseVal=i,e.next=19;break;case 16:e.prev=16,e.t0=e.catch(3),console.warn("Failed to load image:",e.t0);case 19:case"end":return e.stop()}},e,null,[[3,16]])}))).apply(this,arguments)}function R(e){return N.apply(this,arguments)}function N(){return(N=Object(g.a)(p.a.mark(function e(t){var n;return p.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=Array.from(t.getElementsByTagName("image")),e.next=3,Promise.all(n.map(_));case 3:case"end":return e.stop()}},e)}))).apply(this,arguments)}function L(e){var t=new Image;return t.src=URL.createObjectURL(e),new Promise(function(e,n){t.addEventListener("load",function(){return e(t)})})}function C(e){var t=document.createElement("canvas");t.width=2*e.width,t.height=2*e.height;var n=t.getContext("2d"),a=n.fillStyle;return n.fillStyle="white",n.fillRect(0,0,t.width,t.height),n.fillStyle=a,n.drawImage(e,0,0,t.width,t.height),t}function z(e,t){return new Promise(function(n,a){e.toBlob(function(e){e?n(e):a()},t)})}!function(e){e[e.Hourglass=0]="Hourglass",e[e.Relatives=1]="Relatives",e[e.Fancy=2]="Fancy"}(E||(E={}));var I=function(e){function t(){var e,n;Object(v.a)(this,t);for(var a=arguments.length,r=new Array(a),i=0;i0&&void 0!==arguments[0]?arguments[0]:{initialRender:!1};if(t.initialRender||!this.animating){t.initialRender?(k.select("#chart").node().innerHTML="",this.chart=Object(S.createChart)({json:this.props.data,chartType:this.getChartType(),renderer:this.getRendererType(),svgSelector:"#chart",indiCallback:function(t){return e.props.onSelection(t)},animate:!0,updateSvgSize:!1,locale:this.context.intl.locale})):this.chart.setData(this.props.data);var n=this.chart.render({startIndi:this.props.selection.id,baseGeneration:this.props.selection.generation}),a=k.select("#chartSvg"),r=k.select("#svgContainer").node(),i=this.props.enableZoom?k.zoomTransform(r).k:1,o=k.min([1,i,r.clientWidth/n.size[0],r.clientHeight/n.size[1]]),s=this.props.enableZoom?[k.max([.1,o]),2]:[1,1];this.zoomBehavior=k.zoom().scaleExtent(s).translateExtent([[0,0],n.size]).on("zoom",function(){return function(e,t){var n=k.select("#svgContainer").node();if(t){var a=k.event.transform.k,r=k.max([0,(n.clientWidth-e[0]*a)/2]),i=k.max([0,(n.clientHeight-e[1]*a)/2]);k.select("#chartSvg").attr("width",e[0]*a).attr("height",e[1]*a).attr("transform","translate(".concat(r,", ").concat(i,")")),k.select("#chart").attr("transform","scale(".concat(a,")"))}n.scrollLeft=-k.event.transform.x,n.scrollTop=-k.event.transform.y}(n.size,e.props.enableZoom)}),k.select(r).on("scroll",function(){return function(e){var t=k.select("#svgContainer").node(),n=t.scrollLeft+t.clientWidth/2,a=t.scrollTop+t.clientHeight/2,r=e?k.zoomTransform(t).k:1;k.select(t).call(k.zoom().translateTo,n/r,a/r)}(e.props.enableZoom)}).call(this.zoomBehavior);var c,l,u=r.clientWidth/2-n.origin[0]*i,d=r.clientHeight/2-n.origin[1]*i,f=k.max([0,(r.clientWidth-n.size[0]*i)/2]),m=k.max([0,(r.clientHeight-n.size[1]*i)/2]),h=a.transition().delay(200).duration(500);(t.initialRender?a:h).attr("transform","translate(".concat(f,", ").concat(m,")")).attr("width",n.size[0]*i).attr("height",n.size[1]*i),t.initialRender?(r.scrollLeft=-u,r.scrollTop=-d):h.tween("scrollLeft",(l=-u,function(){var e=k.interpolateNumber(r.scrollLeft,l);return function(t){r.scrollLeft=e(t)}})).tween("scrollTop",(c=-d,function(){var e=k.interpolateNumber(r.scrollTop,c);return function(t){r.scrollTop=e(t)}})),this.animating=!0,n.animationPromise.then(function(){e.animating=!1,e.rerenderRequired&&(e.rerenderRequired=!1,e.renderChart({initialRender:!1}))})}else this.rerenderRequired=!0}},{key:"componentDidMount",value:function(){this.renderChart({initialRender:!0})}},{key:"componentDidUpdate",value:function(e){var t=this.props.chartType!==e.chartType;this.renderChart({initialRender:t})}},{key:"render",value:function(){var e=this;return o.createElement("div",{id:"svgContainer"},this.props.enableZoom?o.createElement(j.a,{minWidth:768,className:"zoom"},o.createElement("button",{className:"zoom-in",onClick:function(){return e.zoom(1.3)}},"+"),o.createElement("button",{className:"zoom-out",onClick:function(){return e.zoom(1/1.3)}},"\u2212")):null,o.createElement("svg",{id:"chartSvg"},o.createElement("g",{id:"chart"})))}},{key:"getStrippedSvg",value:function(){var e=document.getElementById("chartSvg").cloneNode(!0);if(e.removeAttribute("transform"),this.props.enableZoom){var t=k.select("#svgContainer").node(),n=k.zoomTransform(t).k;e.setAttribute("width",String(Number(e.getAttribute("width"))/n)),e.setAttribute("height",String(Number(e.getAttribute("height"))/n)),e.querySelector("#chart").removeAttribute("transform")}return e}},{key:"getSvgContents",value:function(){return(new XMLSerializer).serializeToString(this.getStrippedSvg())}},{key:"getSvgContentsWithInlinedImages",value:function(){var e=Object(g.a)(p.a.mark(function e(){var t;return p.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=this.getStrippedSvg(),e.next=3,R(t);case 3:return e.abrupt("return",(new XMLSerializer).serializeToString(t));case 4:case"end":return e.stop()}},e,this)}));return function(){return e.apply(this,arguments)}}()},{key:"print",value:function(){var e=this,t=document.createElement("iframe");t.style.position="absolute",t.style.top="-1000px",t.style.left="-1000px",t.onload=function(){t.contentDocument.open(),t.contentDocument.write(e.getSvgContents()),t.contentDocument.close(),setTimeout(function(){t.contentWindow.focus(),t.contentWindow.print(),t.parentNode.removeChild(t)},500)},document.body.appendChild(t)}},{key:"downloadSvg",value:function(){var e=Object(g.a)(p.a.mark(function e(){var t,n;return p.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getSvgContentsWithInlinedImages();case 2:t=e.sent,n=new Blob([t],{type:"image/svg+xml"}),Object(D.saveAs)(n,"topola.svg");case 5:case"end":return e.stop()}},e,this)}));return function(){return e.apply(this,arguments)}}()},{key:"drawOnCanvas",value:function(){var e=Object(g.a)(p.a.mark(function e(){var t,n;return p.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getSvgContentsWithInlinedImages();case 2:return t=e.sent,n=new Blob([t],{type:"image/svg+xml"}),e.t0=C,e.next=7,L(n);case 7:return e.t1=e.sent,e.next=10,(0,e.t0)(e.t1);case 10:return e.abrupt("return",e.sent);case 11:case"end":return e.stop()}},e,this)}));return function(){return e.apply(this,arguments)}}()},{key:"downloadPng",value:function(){var e=Object(g.a)(p.a.mark(function e(){var t,n;return p.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.drawOnCanvas();case 2:return t=e.sent,e.next=5,z(t,"image/png");case 5:n=e.sent,Object(D.saveAs)(n,"topola.png");case 7:case"end":return e.stop()}},e,this)}));return function(){return e.apply(this,arguments)}}()},{key:"downloadPdf",value:function(){var e=Object(g.a)(p.a.mark(function e(){var t,n;return p.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.drawOnCanvas();case 2:t=e.sent,(n=new x.a({orientation:t.width>t.height?"l":"p",unit:"pt",format:[t.width,t.height]})).addImage(t,"PNG",0,0,t.width,t.height,"NONE"),n.save("topola.pdf");case 6:case"end":return e.stop()}},e,this)}));return function(){return e.apply(this,arguments)}}()}]),t}(o.PureComponent);I.contextTypes={intl:l.d};var P=n(258),W=n.n(P),U=n(259),A=n.n(U),F=n(164);function G(e){return e.substring(1,e.length-1)}function B(e){var t=e.find(function(e){return"HEAD"===e.tag}),n={},a={},r={};return e.forEach(function(e){"INDI"===e.tag?n[G(e.pointer)]=e:"FAM"===e.tag?a[G(e.pointer)]=e:e.pointer&&(r[G(e.pointer)]=e)}),{head:t,indis:n,fams:a,other:r}}function H(e,t){return et?1:0}function Z(e,t){var n=e&&(e.date||e.dateRange&&e.dateRange.from),a=t&&(t.date||t.dateRange&&t.dateRange.from);return n&&n.year&&a&&a.year?n.year!==a.year?n.year-a.year:n.month&&a.month?n.month!==a.month?n.month-a.month:n.day&&a.day&&n.day!==a.day?n.month-a.month:0:0:0}function V(e){var t=function(e){var t=new Map;return e.indis.forEach(function(e){t[e.id]=e}),function(e,n){var a=t[e],r=t[n];return Z(a&&a.birth,r&&r.birth)||H(e,n)}}(e),n=e.fams.map(function(e){return function(e,t){if(!e.children)return e;var n=e.children.sort(t);return Object.assign({},e,{children:n})}(e,t)});return Object.assign({},e,{fams:n})}function K(e){var t=function(e){var t=new Map;return e.fams.forEach(function(e){t[e.id]=e}),function(e,n){var a=t[e],r=t[n];return Z(a&&a.marriage,r&&r.marriage)||H(e,n)}}(e),n=e.indis.map(function(e){return function(e,t){if(!e.fams)return e;var n=e.fams.sort(t);return Object.assign({},e,{fams:n})}(e,t)});return Object.assign({},e,{indis:n})}function J(e){return K(V(e))}var q=[".jpg",".png",".gif"];function Y(e,t){if(!e.images||0===e.images.length)return e;var n=[];return e.images.forEach(function(e){var a=e.url.match(/[^/\\]*$/)[0];t.has(a)?n.push({url:t.get(a),title:e.title}):e.url.startsWith("http")&&function(e){var t=e.toLowerCase();return q.some(function(e){return t.endsWith(e)})}(e.url)&&n.push(e)}),Object.assign({},e,{images:n})}function X(e,t){var n=e.indis.map(function(e){return Y(e,t)});return Object.assign({},e,{indis:n})}function $(e){var t=e&&e.tree&&e.tree.find(function(e){return"SOUR"===e.tag}),n=t&&t.tree&&t.tree.find(function(e){return"NAME"===e.tag});return n&&n.data||null}var Q=new Map([["abt","about"],["cal","calculated"],["est","estimated"]]);function ee(e,t){var n=void 0!==e.day,a=void 0!==e.month,r=void 0!==e.year;if(!n&&!a&&!r)return e.text||"";var i=new Date(r?e.year:0,a?e.month-1:0,n?e.day:1),o=e.qualifier&&e.qualifier.toLowerCase(),s={day:n?"numeric":void 0,month:a?"long":void 0,year:r?"numeric":void 0};return[o&&t.formatMessage({id:"date.".concat(o),defaultMessage:Q.get(o)||o}),new Intl.DateTimeFormat(t.locale,s).format(i)].join(" ")}function te(e,t){var n=Object(S.getDate)(e);return n?n.date?ee(n.date,t):n.dateRange?function(e,t){var n=e.from,a=e.to,r=n&&ee(n,t),i=a&&ee(a,t);return r&&i?t.formatMessage({id:"date.between",defaultMessage:"between {from} and {to}"},{from:r,to:i}):r?t.formatMessage({id:"date.after",defaultMessage:"after {from}"},{from:r}):i?t.formatMessage({id:"date.before",defaultMessage:"before {to}"},{to:i}):""}(n.dateRange,t):"":""}var ne=["BIRT","BAPM","CHR","DEAT","BURI","EVEN"],ae=["NAME","SEX","FAMC","FAMS","NOTE","SOUR"],re=new Map([["BAPM","Baptism"],["BIRT","Birth"],["BURI","Burial"],["CHR","Christening"],["DEAT","Death"],["EMAIL","E-mail"],["EVEN","Event"],["OCCU","Occupation"],["TITL","Title"],["WWW","WWW"]]);function ie(e){return o.createElement(l.a,{id:"gedcom.".concat(e),defaultMessage:re.get(e)||e})}function oe(e){return o.createElement(o.Fragment,null,e.map(function(e,t){return o.createElement("div",{key:t},o.createElement(A.a,{properties:{target:"_blank"}},e),o.createElement("br",null))}))}function se(e){var t=[e.data];return e.tree.forEach(function(e){if("CONC"===e.tag&&e.data){var n=t.length-1;t[n]+=e.data}else"CONT"===e.tag&&e.data&&t.push(e.data)}),t}function ce(e){return oe(se(e).map(function(e,t){return o.createElement("i",{key:t},e)}))}function le(e){return o.createElement("h2",{className:"ui header"},e.data.split("/").filter(function(e){return!!e}).map(function(e,t){return o.createElement("div",{key:t},e,o.createElement("br",null))}))}function ue(e,t,n){return W()(t,function(t){return e.filter(function(e){return e.tag===t}).map(function(e){return n(e)})}).filter(function(e){return null!==e}).map(function(e,t){return o.createElement("div",{className:"ui segment",key:t},e)})}function de(e){return e.tree.length>0||e.data&&!e.data.startsWith("@")}function fe(e){return e.filter(function(e){return!ae.includes(e.tag)&&!ne.includes(e.tag)}).filter(de).map(function(e){return function(e){var t=[];return e.data&&t.push.apply(t,Object(a.a)(se(e))),e.tree.filter(function(e){return"NOTE"===e.tag}).forEach(function(e){return se(e).forEach(function(e){return t.push(o.createElement("i",null,e))})}),t.length?o.createElement(o.Fragment,null,o.createElement("div",{className:"ui sub header"},ie(e.tag)),o.createElement("span",null,oe(t))):null}(e)}).filter(function(e){return null!==e}).map(function(e,t){return o.createElement("div",{className:"ui segment",key:t},e)})}var me=function(e){function t(){return Object(v.a)(this,t),Object(u.a)(this,Object(d.a)(t).apply(this,arguments))}return Object(f.a)(t,e),Object(w.a)(t,[{key:"render",value:function(){var e=this,t=this.props.gedcom.indis[this.props.indi].tree,n=t.map(function(t){return function(e,t){if(e.data){var n=t.other[G(e.data)];if(n)return n}return e}(t,e.props.gedcom)}).filter(de);return o.createElement("div",{className:"ui segments",id:"details"},ue(t,["NAME"],le),ue(t,ne,function(t){return function(e,t){var n=[];e.data&&e.data.length>1&&n.push(o.createElement("i",null,e.data));var r=e.tree.find(function(e){return"DATE"===e.tag});r&&r.data&&n.push(te(r.data,t));var i=e.tree.find(function(e){return"PLAC"===e.tag});return i&&i.data&&n.push.apply(n,Object(a.a)(se(i))),e.tree.filter(function(e){return"NOTE"===e.tag}).forEach(function(e){return se(e).forEach(function(e){return n.push(o.createElement("i",null,e))})}),n.length?o.createElement(o.Fragment,null,o.createElement("div",{className:"ui sub header"},ie(e.tag)),o.createElement("span",null,oe(n))):null}(t,e.context.intl)}),fe(n),ue(n,["NOTE"],ce))}}]),t}(o.Component);function he(e,t,n){return{id:t&&e.indis.some(function(e){return e.id===t})?t:e.indis[0].id,generation:n||0}}function pe(e,t,n){var a=function(e,t){var n=Object(F.parse)(e),a=Object(S.gedcomEntriesToJson)(n);if(!a||!a.indis||!a.indis.length||!a.fams||!a.fams.length)throw new Error("Failed to read GEDCOM file");return{chartData:X(J(a),t),gedcom:B(n)}}(e,n||new Map),r=JSON.stringify(a);try{sessionStorage.setItem(t,r)}catch(i){console.warn("Failed to store data in session storage: "+i)}return a}function ge(e,t){return ve.apply(this,arguments)}function ve(){return(ve=Object(g.a)(p.a.mark(function e(t,n){var a,r,i,o;return p.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,!(a=sessionStorage.getItem(t))){e.next=4;break}return e.abrupt("return",JSON.parse(a));case 4:e.next=9;break;case 6:e.prev=6,e.t0=e.catch(0),console.warn("Failed to load data from session storage: "+e.t0);case 9:return r=n?"https://cors-anywhere.herokuapp.com/"+t:t,e.next=12,window.fetch(r);case 12:if(200===(i=e.sent).status){e.next=15;break}throw new Error(i.statusText);case 15:return e.next=17,i.text();case 17:return o=e.sent,e.abrupt("return",pe(o,t));case 19:case"end":return e.stop()}},e,null,[[0,6]])}))).apply(this,arguments)}function we(e,t,n){return be.apply(this,arguments)}function be(){return(be=Object(g.a)(p.a.mark(function e(t,n,a){var r;return p.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,!(r=sessionStorage.getItem(t))){e.next=4;break}return e.abrupt("return",JSON.parse(r));case 4:e.next=9;break;case 6:e.prev=6,e.t0=e.catch(0),console.warn("Failed to load data from session storage: "+e.t0);case 9:if(n){e.next=11;break}throw new Error("Error loading data. Please upload your file again.");case 11:return e.abrupt("return",pe(n,t,a));case 12:case"end":return e.stop()}},e,null,[[0,6]])}))).apply(this,arguments)}me.contextTypes={intl:l.d};var ye=n(260),Ee=n.n(ye),ke=n(543),Oe=n(549),xe=n(286),De=n(536);function Se(e){return o.createElement(De.a,{to:{pathname:"/view",search:b.stringify({url:e.url})}},e.text)}function je(){return o.createElement("div",{id:"content"},o.createElement("div",{className:"backgroundImage"}),o.createElement(ke.a,{className:"intro"},o.createElement(ke.a.Content,null,o.createElement(ke.a.Header,null,o.createElement(l.a,{id:"intro.title",defaultMessage:"Topola Genealogy Viewer"}))),o.createElement(ke.a.Content,null,o.createElement(Oe.a,null,o.createElement(Oe.a.Row,null,o.createElement(Oe.a.Column,{width:5},o.createElement(xe.a,{src:Ee.a,alt:"Topola logo"})),o.createElement(Oe.a.Column,{width:11},o.createElement("p",null,o.createElement(l.a,{id:"intro.description",defaultMessage:"Topola Genealogy is a genealogy tree viewer that lets you browse the structure of the family."})),o.createElement("p",null,o.createElement(l.a,{id:"intro.instructions",defaultMessage:"Use the LOAD FROM URL or LOAD FROM FILE buttons above to load a GEDCOM file. You can export a GEDCOM file from most of the existing genealogy programs and web sites."})),o.createElement("p",null,o.createElement(l.a,{id:"intro.examples",defaultMessage:"Here are some examples from the web that you can view:"})),o.createElement("ul",null,o.createElement("li",null,o.createElement(Se,{url:"http://genpol.com/module-Downloads-prep_hand_out-lid-32.html",text:"Karol Wojty\u0142a"})," ","(",o.createElement(l.a,{id:"intro.from",defaultMessage:"from"})," ",o.createElement("a",{href:"http://genpol.com/module-Downloads-display-lid-32.html"},"GENPOL"),")"),o.createElement("li",null,o.createElement(Se,{url:"https://webtreeprint.com/tp_downloader.php?path=famous_gedcoms/shakespeare.ged",text:"Shakespeare"})," ","(",o.createElement(l.a,{id:"intro.from",defaultMessage:"from"})," ",o.createElement("a",{href:"https://webtreeprint.com/tp_famous_gedcoms.php"},"webtreeprint.com"),")"),o.createElement("li",null,o.createElement(Se,{url:"http://genealogyoflife.com/tng/gedcom/HarryPotter.ged",text:"Harry Potter"})," ","(",o.createElement(l.a,{id:"intro.from",defaultMessage:"from"})," ",o.createElement("a",{href:"http://famousfamilytrees.blogspot.com/"},"Famous Family Trees"),")")),o.createElement("p",null,o.createElement("b",null,o.createElement(l.a,{id:"intro.privacy",defaultMessage:"Privacy"})),": ",o.createElement(l.a,{id:"intro.privacy_note",defaultMessage:'When using the "load from file" option, this site does not send your data anywhere and files loaded from disk do not leave your computer. When using "load from URL", data is passed through the {link} service to deal with an issue with cross-site file loading in the browser (CORS).',values:{link:o.createElement("a",{href:"https://cors-anywhere.herokuapp.com/"},"cors-anywhere")}})),o.createElement("p",{className:"ui right aligned version"},"version: ","2020-03-20 18:53:56 +0100".slice(0,16)," (",o.createElement("a",{href:"https://github.com/PeWu/topola-viewer/commit/".concat("f8021c0")},"f8021c0"),")"))," ")," "))))}var Me=n(544),_e=n(554),Te=n(539),Re=n(87),Ne=n.n(Re);function Le(e){try{return sessionStorage.getItem(e)}catch(t){console.warn("Failed to load data from session storage: "+t)}return null}function Ce(e,t){try{sessionStorage.setItem(e,t)}catch(n){console.warn("Failed to store data in session storage: "+n)}}function ze(e,t){return Ie.apply(this,arguments)}function Ie(){return(Ie=Object(g.a)(p.a.mark(function e(t,n){var a,r,i,o,s;return p.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:for(r in(a=new FormData).append("format","json"),t)a.append(r,t[r]);return i=n?"https://cors-anywhere.herokuapp.com/https://apps.wikitree.com/api.php":"https://apps.wikitree.com/api.php",e.next=6,window.fetch(i,{method:"POST",body:a});case 6:return o=e.sent,e.next=9,o.text();case 9:return s=e.sent,e.abrupt("return",JSON.parse(s));case 11:case"end":return e.stop()}},e)}))).apply(this,arguments)}function Pe(e,t){return We.apply(this,arguments)}function We(){return(We=Object(g.a)(p.a.mark(function e(t,n){var a,r,i,o;return p.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(a="wikitree:ancestors:".concat(t),!(r=Le(a))){e.next=4;break}return e.abrupt("return",JSON.parse(r));case 4:return e.next=6,ze({action:"getAncestors",key:t,fields:"*"},n);case 6:return i=e.sent,o=i[0].ancestors,Ce(a,JSON.stringify(o)),e.abrupt("return",o);case 10:case"end":return e.stop()}},e)}))).apply(this,arguments)}function Ue(e,t){return Ae.apply(this,arguments)}function Ae(){return(Ae=Object(g.a)(p.a.mark(function e(t,n){var a,r,i,o;return p.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(a=[],r=[],t.forEach(function(e){var t=Le("wikitree:relatives:".concat(e));t?a.push(JSON.parse(t)):r.push(e)}),0!==r.length){e.next=5;break}return e.abrupt("return",a);case 5:return e.next=7,ze({action:"getRelatives",keys:r.join(","),getChildren:!0,getSpouses:!0},n);case 7:if(null!==(i=e.sent)[0].items){e.next=10;break}throw new Error("WikiTree profile ".concat(r[0]," not found."));case 10:return(o=i[0].items.map(function(e){return e.person})).forEach(function(e){Ce("wikitree:relatives:".concat(e.Name),JSON.stringify(e))}),e.abrupt("return",a.concat(o));case 13:case"end":return e.stop()}},e)}))).apply(this,arguments)}function Fe(e){return Ge.apply(this,arguments)}function Ge(){return(Ge=Object(g.a)(p.a.mark(function e(t){var n;return p.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,ze({action:"clientLogin",authcode:t},!1);case 2:return n=e.sent,e.abrupt("return",n.clientLogin);case 4:case"end":return e.stop()}},e)}))).apply(this,arguments)}function Be(e,t){return He.apply(this,arguments)}function He(){return(He=Object(g.a)(p.a.mark(function e(t,n){var r,i,o,s,c,l,u,d,f,h,g,v,w,b,y,E,k,O,x,D,S;return p.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if((r="apps.wikitree.com"!==window.location.hostname)||Ne.a.get("wikidb_wtb_UserID")||!n){e.next=6;break}return e.next=4,Fe(n);case 4:"Success"===e.sent.result&&sessionStorage.clear();case 6:return i=[],e.next=9,Ue([t],r);case 9:if((o=e.sent)[0].Name){e.next=12;break}throw new Error("WikiTree profile ".concat(t," is not accessible. Try logging in."));case 12:return s=Object.values(o[0].Spouses).map(function(e){return e.Name}),e.next=15,Promise.all([t].concat(s).map(function(e){return Pe(e,r)}));case 15:return c=e.sent,l=c.flat().map(function(e){return e.Name}).filter(function(e){return!!e}),e.next=19,Ue(l,r);case 19:u=e.sent,i.push.apply(i,Object(a.a)(u)),d=5,f=[t],h=0;case 24:if(!(f.length>0&&h<=d)){e.next=35;break}return e.next=27,Ue(f,r);case 27:g=e.sent,i.push.apply(i,Object(a.a)(g)),v=g.flatMap(function(e){return Object.values(e.Spouses)}),i.push.apply(i,Object(a.a)(v)),f=g.flatMap(function(e){return Object.values(e.Children).map(function(e){return e.Name})}),h++,e.next=24;break;case 35:return w=new Map,b=new Map,y=new Map,E=new Map,i.forEach(function(e){if(E.set(e.Id,e.Name),e.Mother||e.Father){var t=Ze(e.Mother,e.Father);qe(w,e.Mother).add(t),qe(w,e.Father).add(t),qe(b,t).add(e.Id),y.set(t,{wife:e.Mother||void 0,husband:e.Father||void 0})}}),k=[],O=new Set,i.forEach(function(e){if(!O.has(e.Id)){O.add(e.Id);var t=Ve(e);console.log(e,t),e.Spouses&&Object.values(e.Spouses).forEach(function(t){var n=Ze(e.Id,t.Id);qe(w,e.Id).add(n),qe(w,t.Id).add(n);var a="Male"===e.Gender?{wife:t.Id,husband:e.Id,spouse:t}:{wife:e.Id,husband:t.Id,spouse:t};y.set(n,a)}),t.fams=Array.from(qe(w,e.Id)),k.push(t)}}),x=Array.from(y.entries()).map(function(e){var t=Object(m.a)(e,2),n=t[0],a=t[1],r={id:n},i=a.wife&&E.get(a.wife);i&&(r.wife=i);var o=a.husband&&E.get(a.husband);if(o&&(r.husb=o),r.children=Array.from(qe(b,n)).map(function(e){return E.get(e)}),a.spouse&&(a.spouse.marriage_date&&"0000-00-00"!==a.spouse.marriage_date||a.spouse.marriage_location)){var s=Ke(a.spouse.marriage_date);r.marriage=Object.assign({},s,{place:a.spouse.marriage_location})}return r}),D=J({indis:k,fams:x}),S=Je(k),e.abrupt("return",{chartData:D,gedcom:S});case 47:case"end":return e.stop()}},e)}))).apply(this,arguments)}function Ze(e,t){return t>e?"".concat(e,"_").concat(t):"".concat(t,"_").concat(e)}function Ve(e){var t={id:e.Name};if("Unknown"!==e.FirstName&&(t.firstName=e.FirstName),"Unknown"!==e.LastNameAtBirth&&(t.lastName=e.LastNameAtBirth),(e.Mother||e.Father)&&(t.famc=Ze(e.Mother,e.Father)),"Male"===e.Gender?t.sex="M":"Female"===e.Gender&&(t.sex="F"),e.BirthDate&&"0000-00-00"!==e.BirthDate||e.BirthLocation){var n=Ke(e.BirthDate,e.DataStatus&&e.DataStatus.BirthDate);t.birth=Object.assign({},n,{place:e.BirthLocation})}if(e.DeathDate&&"0000-00-00"!==e.DeathDate||e.DeathLocation){var a=Ke(e.DeathDate,e.DataStatus&&e.DataStatus.DeathDate);t.death=Object.assign({},a,{place:e.DeathLocation})}return e.PhotoData&&(t.images=[{url:"https://wikitree.com".concat(e.PhotoData.path)}]),t}function Ke(e,t){if(e){var n=e.match(/(\d\d\d\d)-(\d\d)-(\d\d)/);if(!n)return{date:{text:e}};var a={};return"0000"!==n[1]&&(a.year=~~n[1]),"00"!==n[2]&&(a.month=~~n[2]),"00"!==n[3]&&(a.day=~~n[3]),"after"===t?{dateRange:{from:a}}:"before"===t?{dateRange:{to:a}}:("guess"===t&&(a.qualifier="abt"),{date:a})}}function Je(e){var t={};return e.forEach(function(e){var n=e.id.replace(/ /g,"_");t[e.id]={level:0,pointer:"@".concat(e.id,"@"),tag:"INDI",data:"",tree:[{level:1,pointer:"",tag:"NAME",data:"".concat(e.firstName||""," /").concat(e.lastName||"","/"),tree:[]},{level:1,pointer:"",tag:"WWW",data:"https://www.wikitree.com/wiki/".concat(n),tree:[]}]}}),{head:{level:0,pointer:"",tag:"HEAD",data:"",tree:[]},indis:t,fams:{},other:{}}}function qe(e,t){var n=e.get(t);if(n)return n;var a=new Set;return e.set(t,a),a}var Ye=n(551),Xe=n(552),$e=n(547),Qe=n(264),et=n.n(Qe),tt=n(169),nt=n.n(tt),at=n(265),rt=n.n(at),it=n(266),ot=n.n(it);function st(e){return e.toLocaleLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/\u0142/g,"l")}function ct(e,t){return e.score!==t.score?t.score-e.score:rt()(e.ref,t.ref)}function lt(e,t){return e.tree.filter(function(e){return"FAMS"===e.tag}).map(function(e){return t.fams[G(e.data)]}).filter(function(e){return!!e}).map(function(n){var a=n.tree.find(function(e){return"HUSB"===e.tag}),r=a&&G(a.data);return r&&r!==G(e.pointer)&&t.indis[r]}).filter(function(e){return!!e}).flatMap(function(e){return e.tree.filter(function(e){return"NAME"===e.tag}).map(function(e){var t=e.data.split("/");return t.length>=2?t[1]:""})}).join(" ")}var ut=function(){function e(t){Object(v.a)(this,e),this.gedcom=t,this.index=void 0}return Object(w.a)(e,[{key:"initialize",value:function(){var e=this;this.index=ot()(function(){for(var t in this.ref("id"),this.field("id"),this.field("name",{boost:10}),this.field("normalizedName",{boost:8}),this.field("spouseLastName",{boost:2}),this.field("normalizedSpouseLastName",{boost:2}),e.gedcom.indis){var n=e.gedcom.indis[t],a=n.tree.filter(function(e){return"NAME"===e.tag}).map(function(e){return e.data}).join(" "),r=lt(n,e.gedcom);this.add({id:t,name:a,normalizedName:st(a),spouseLastName:r,normalizedSpouseLastName:st(r)})}})}},{key:"search",value:function(e){var t=this,n=e.split(" ").filter(function(e){return!!e}).map(function(e){return"+".concat(e,"*")}).join(" ");return this.index.search(n).sort(ct).slice(0,8).map(function(e){return{id:e.ref,indi:t.gedcom.indis[e.ref]}})}}]),e}();function dt(e){var t=e.indi.tree.find(function(e){return"NAME"===e.tag}),n=t&&t.data.split("/").filter(function(e){return!!e}).join(" ");return e.id.length>8?n:o.createElement(o.Fragment,null,n," ",o.createElement("i",null,"(",e.id,")"))}function ft(e,t,n){var a=e.tree.find(function(e){return e.tag===t}),r=a&&a.tree.find(function(e){return"DATE"===e.tag});return r&&te(r.data,n)||""}function mt(e,t){var n=ft(e,"BIRT",t),a=ft(e,"DEAT",t);return a?"".concat(n," \u2013 ").concat(a):n}var ht,pt=n(541),gt=n(550),vt=n(66),wt=n(540),bt=n(538),yt=n(530),Et=n(545),kt=n(542),Ot=n(546);function xt(e){return new Promise(function(t,n){var a=new FileReader;a.onload=function(e){t(e.target.result)},a.readAsText(e)})}function Dt(e){var t=e.toLowerCase();return t.endsWith(".jpg")||t.endsWith(".png")}!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.NOT_LOGGED_IN=1]="NOT_LOGGED_IN",e[e.LOGGED_IN=2]="LOGGED_IN"}(ht||(ht={}));var St,jt=function(e){function t(){var e,n;Object(v.a)(this,t);for(var a=arguments.length,r=new Array(a),i=0;i {\n const reader = new FileReader();\n reader.readAsDataURL(blob);\n return new Promise((resolve, reject) => {\n reader.onload = (e) => resolve((e.target as FileReader).result as string);\n });\n}\n\nasync function inlineImage(image: SVGImageElement) {\n const href = image.href.baseVal;\n if (!href) {\n return;\n }\n try {\n const response = await fetch(href);\n const blob = await response.blob();\n const dataUrl = await loadAsDataUrl(blob);\n image.href.baseVal = dataUrl;\n } catch (e) {\n console.warn('Failed to load image:', e);\n }\n}\n\n/**\n * Fetches all images in the SVG and replaces them with inlined images as data\n * URLs. Images are replaced in place. The replacement is done, the returned\n * promise is resolved.\n */\nasync function inlineImages(svg: Element): Promise {\n const images = Array.from(svg.getElementsByTagName('image'));\n await Promise.all(images.map(inlineImage));\n}\n\n/** Loads a blob into an image object. */\nfunction loadImage(blob: Blob): Promise {\n const image = new Image();\n image.src = URL.createObjectURL(blob);\n return new Promise((resolve, reject) => {\n image.addEventListener('load', () => resolve(image));\n });\n}\n\n/** Draw image on a new canvas and return the canvas. */\nfunction drawOnCanvas(image: HTMLImageElement) {\n const canvas = document.createElement('canvas');\n // Scale image for better quality.\n canvas.width = image.width * 2;\n canvas.height = image.height * 2;\n\n const ctx = canvas.getContext('2d')!;\n const oldFill = ctx.fillStyle;\n ctx.fillStyle = 'white';\n ctx.fillRect(0, 0, canvas.width, canvas.height);\n ctx.fillStyle = oldFill;\n\n ctx.drawImage(image, 0, 0, canvas.width, canvas.height);\n return canvas;\n}\n\nfunction canvasToBlob(canvas: HTMLCanvasElement, type: string) {\n return new Promise((resolve, reject) => {\n canvas.toBlob((blob) => {\n if (blob) {\n resolve(blob);\n } else {\n reject();\n }\n }, type);\n });\n}\n\n/** Supported chart types. */\nexport enum ChartType {\n Hourglass,\n Relatives,\n Fancy,\n}\n\nexport interface ChartProps {\n data: JsonGedcomData;\n selection: IndiInfo;\n chartType: ChartType;\n onSelection: (indiInfo: IndiInfo) => void;\n enableZoom: boolean;\n}\n\n/** Component showing the genealogy chart and handling transition animations. */\nexport class Chart extends React.PureComponent {\n private chart?: ChartHandle;\n /** Animation is in progress. */\n private animating = false;\n /** Rendering is required after the current animation finishes. */\n private rerenderRequired = false;\n /** The d3 zoom behavior object. */\n private zoomBehavior?: d3.ZoomBehavior;\n\n private getChartType() {\n switch (this.props.chartType) {\n case ChartType.Hourglass:\n return HourglassChart;\n case ChartType.Relatives:\n return RelativesChart;\n case ChartType.Fancy:\n return FancyChart;\n default:\n // Fall back to hourglass chart.\n return HourglassChart;\n }\n }\n\n private getRendererType() {\n switch (this.props.chartType) {\n case ChartType.Fancy:\n return CircleRenderer;\n default:\n // Use DetailedRenderer by default.\n return DetailedRenderer;\n }\n }\n\n private zoom(factor: number) {\n const parent = d3.select('#svgContainer') as d3.Selection<\n Element,\n any,\n any,\n any\n >;\n this.zoomBehavior!.scaleBy(parent, factor);\n }\n\n /**\n * Renders the chart or performs a transition animation to a new state.\n * If indiInfo is not given, it means that it is the initial render and no\n * animation is performed.\n */\n private renderChart(args: {initialRender: boolean} = {initialRender: false}) {\n // Wait for animation to finish if animation is in progress.\n if (!args.initialRender && this.animating) {\n this.rerenderRequired = true;\n return;\n }\n\n if (args.initialRender) {\n (d3.select('#chart').node() as HTMLElement).innerHTML = '';\n this.chart = createChart({\n json: this.props.data,\n chartType: this.getChartType(),\n renderer: this.getRendererType(),\n svgSelector: '#chart',\n indiCallback: (info) => this.props.onSelection(info),\n animate: true,\n updateSvgSize: false,\n locale: this.context.intl.locale,\n });\n } else {\n this.chart!.setData(this.props.data);\n }\n const chartInfo = this.chart!.render({\n startIndi: this.props.selection.id,\n baseGeneration: this.props.selection.generation,\n });\n const svg = d3.select('#chartSvg');\n const parent = d3.select('#svgContainer').node() as Element;\n\n const scale = this.props.enableZoom ? d3.zoomTransform(parent).k : 1;\n const zoomOutFactor = d3.min([\n 1,\n scale,\n parent.clientWidth / chartInfo.size[0],\n parent.clientHeight / chartInfo.size[1],\n ])!;\n const extent: [number, number] = this.props.enableZoom\n ? [d3.max([0.1, zoomOutFactor])!, 2]\n : [1, 1];\n\n this.zoomBehavior = d3\n .zoom()\n .scaleExtent(extent)\n .translateExtent([[0, 0], chartInfo.size])\n .on('zoom', () => zoomed(chartInfo.size, this.props.enableZoom));\n d3.select(parent)\n .on('scroll', () => scrolled(this.props.enableZoom))\n .call(this.zoomBehavior);\n\n const scrollTopTween = (scrollTop: number) => {\n return () => {\n const i = d3.interpolateNumber(parent.scrollTop, scrollTop);\n return (t: number) => {\n parent.scrollTop = i(t);\n };\n };\n };\n const scrollLeftTween = (scrollLeft: number) => {\n return () => {\n const i = d3.interpolateNumber(parent.scrollLeft, scrollLeft);\n return (t: number) => {\n parent.scrollLeft = i(t);\n };\n };\n };\n\n const dx = parent.clientWidth / 2 - chartInfo.origin[0] * scale;\n const dy = parent.clientHeight / 2 - chartInfo.origin[1] * scale;\n const offsetX = d3.max([\n 0,\n (parent.clientWidth - chartInfo.size[0] * scale) / 2,\n ]);\n const offsetY = d3.max([\n 0,\n (parent.clientHeight - chartInfo.size[1] * scale) / 2,\n ]);\n const svgTransition = svg\n .transition()\n .delay(200)\n .duration(500);\n const transition = args.initialRender ? svg : svgTransition;\n transition\n .attr('transform', `translate(${offsetX}, ${offsetY})`)\n .attr('width', chartInfo.size[0] * scale)\n .attr('height', chartInfo.size[1] * scale);\n if (args.initialRender) {\n parent.scrollLeft = -dx;\n parent.scrollTop = -dy;\n } else {\n svgTransition\n .tween('scrollLeft', scrollLeftTween(-dx))\n .tween('scrollTop', scrollTopTween(-dy));\n }\n\n // After the animation is finished, rerender the chart if required.\n this.animating = true;\n chartInfo.animationPromise.then(() => {\n this.animating = false;\n if (this.rerenderRequired) {\n this.rerenderRequired = false;\n this.renderChart({initialRender: false});\n }\n });\n }\n\n componentDidMount() {\n this.renderChart({initialRender: true});\n }\n\n componentDidUpdate(prevProps: ChartProps) {\n const initialRender = this.props.chartType !== prevProps.chartType;\n this.renderChart({initialRender});\n }\n\n /** Make intl appear in this.context. */\n static contextTypes = {\n intl: intlShape,\n };\n\n render() {\n return (\n
\n {this.props.enableZoom ? (\n \n \n this.zoom(1 / ZOOM_FACTOR)}\n >\n −\n \n \n ) : null}\n \n \n \n
\n );\n }\n\n /** Return a copy of the SVG chart but without scaling and positioning. */\n private getStrippedSvg() {\n const svg = document.getElementById('chartSvg')!.cloneNode(true) as Element;\n\n svg.removeAttribute('transform');\n if (this.props.enableZoom) {\n const parent = d3.select('#svgContainer').node() as Element;\n const scale = d3.zoomTransform(parent).k;\n svg.setAttribute(\n 'width',\n String(Number(svg.getAttribute('width')) / scale),\n );\n svg.setAttribute(\n 'height',\n String(Number(svg.getAttribute('height')) / scale),\n );\n svg.querySelector('#chart')!.removeAttribute('transform');\n }\n return svg;\n }\n\n private getSvgContents() {\n return new XMLSerializer().serializeToString(this.getStrippedSvg());\n }\n\n private async getSvgContentsWithInlinedImages() {\n const svg = this.getStrippedSvg();\n await inlineImages(svg);\n return new XMLSerializer().serializeToString(svg);\n }\n\n /** Shows the print dialog to print the currently displayed chart. */\n print() {\n const printWindow = document.createElement('iframe');\n printWindow.style.position = 'absolute';\n printWindow.style.top = '-1000px';\n printWindow.style.left = '-1000px';\n printWindow.onload = () => {\n printWindow.contentDocument!.open();\n printWindow.contentDocument!.write(this.getSvgContents());\n printWindow.contentDocument!.close();\n // Doesn't work on Firefox without the setTimeout.\n setTimeout(() => {\n printWindow.contentWindow!.focus();\n printWindow.contentWindow!.print();\n printWindow.parentNode!.removeChild(printWindow);\n }, 500);\n };\n document.body.appendChild(printWindow);\n }\n\n async downloadSvg() {\n const contents = await this.getSvgContentsWithInlinedImages();\n const blob = new Blob([contents], {type: 'image/svg+xml'});\n saveAs(blob, 'topola.svg');\n }\n\n private async drawOnCanvas(): Promise {\n const contents = await this.getSvgContentsWithInlinedImages();\n const blob = new Blob([contents], {type: 'image/svg+xml'});\n return await drawOnCanvas(await loadImage(blob));\n }\n\n async downloadPng() {\n const canvas = await this.drawOnCanvas();\n const blob = await canvasToBlob(canvas, 'image/png');\n saveAs(blob, 'topola.png');\n }\n\n async downloadPdf() {\n const canvas = await this.drawOnCanvas();\n const doc = new jsPDF({\n orientation: canvas.width > canvas.height ? 'l' : 'p',\n unit: 'pt',\n format: [canvas.width, canvas.height],\n });\n doc.addImage(canvas, 'PNG', 0, 0, canvas.width, canvas.height, 'NONE');\n doc.save('topola.pdf');\n }\n}\n","import {\n JsonFam,\n JsonGedcomData,\n JsonIndi,\n gedcomEntriesToJson,\n JsonImage,\n JsonEvent,\n} from 'topola';\nimport {GedcomEntry, parse as parseGedcom} from 'parse-gedcom';\n\nexport interface GedcomData {\n /** The HEAD entry. */\n head: GedcomEntry;\n /** INDI entries mapped by id. */\n indis: {[key: string]: GedcomEntry};\n /** FAM entries mapped by id. */\n fams: {[key: string]: GedcomEntry};\n /** Other entries mapped by id, e.g. NOTE, SOUR. */\n other: {[key: string]: GedcomEntry};\n}\n\nexport interface TopolaData {\n chartData: JsonGedcomData;\n gedcom: GedcomData;\n}\n\n/**\n * Returns the identifier extracted from a pointer string.\n * E.g. '@I123@' -> 'I123'\n */\nexport function pointerToId(pointer: string): string {\n return pointer.substring(1, pointer.length - 1);\n}\n\nfunction prepareGedcom(entries: GedcomEntry[]): GedcomData {\n const head = entries.find((entry) => entry.tag === 'HEAD')!;\n const indis: {[key: string]: GedcomEntry} = {};\n const fams: {[key: string]: GedcomEntry} = {};\n const other: {[key: string]: GedcomEntry} = {};\n entries.forEach((entry) => {\n if (entry.tag === 'INDI') {\n indis[pointerToId(entry.pointer)] = entry;\n } else if (entry.tag === 'FAM') {\n fams[pointerToId(entry.pointer)] = entry;\n } else if (entry.pointer) {\n other[pointerToId(entry.pointer)] = entry;\n }\n });\n return {head, indis, fams, other};\n}\n\nfunction strcmp(a: string, b: string) {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n}\n\n/** Compares dates of the given events. */\nfunction compareDates(\n event1: JsonEvent | undefined,\n event2: JsonEvent | undefined,\n): number {\n const date1 =\n event1 && (event1.date || (event1.dateRange && event1.dateRange.from));\n const date2 =\n event2 && (event2.date || (event2.dateRange && event2.dateRange.from));\n if (!date1 || !date1.year || !date2 || !date2.year) {\n return 0;\n }\n if (date1.year !== date2.year) {\n return date1.year - date2.year;\n }\n if (!date1.month || !date2.month) {\n return 0;\n }\n if (date1.month !== date2.month) {\n return date1.month - date2.month;\n }\n if (date1.day && date2.day && date1.day !== date2.day) {\n return date1.month - date2.month;\n }\n return 0;\n}\n\n/** Birth date comparator for individuals. */\nfunction birthDatesComparator(gedcom: JsonGedcomData) {\n const idToIndiMap = new Map();\n gedcom.indis.forEach((indi) => {\n idToIndiMap[indi.id] = indi;\n });\n\n return (indiId1: string, indiId2: string) => {\n const indi1: JsonIndi = idToIndiMap[indiId1];\n const indi2: JsonIndi = idToIndiMap[indiId2];\n return (\n compareDates(indi1 && indi1.birth, indi2 && indi2.birth) ||\n strcmp(indiId1, indiId2)\n );\n };\n}\n\n/** Marriage date comparator for families. */\nfunction marriageDatesComparator(gedcom: JsonGedcomData) {\n const idToFamMap = new Map();\n gedcom.fams.forEach((fam) => {\n idToFamMap[fam.id] = fam;\n });\n\n return (famId1: string, famId2: string) => {\n const fam1: JsonFam = idToFamMap[famId1];\n const fam2: JsonFam = idToFamMap[famId2];\n return (\n compareDates(fam1 && fam1.marriage, fam2 && fam2.marriage) ||\n strcmp(famId1, famId2)\n );\n };\n}\n\n/**\n * Sorts children by birth date in the given family.\n * Does not modify the input objects.\n */\nfunction sortFamilyChildren(\n fam: JsonFam,\n comparator: (id1: string, id2: string) => number,\n): JsonFam {\n if (!fam.children) {\n return fam;\n }\n const newChildren = fam.children.sort(comparator);\n return Object.assign({}, fam, {children: newChildren});\n}\n\n/**\n * Sorts children by birth date.\n * Does not modify the input object.\n */\nfunction sortChildren(gedcom: JsonGedcomData): JsonGedcomData {\n const comparator = birthDatesComparator(gedcom);\n const newFams = gedcom.fams.map((fam) => sortFamilyChildren(fam, comparator));\n return Object.assign({}, gedcom, {fams: newFams});\n}\n\n/**\n * Sorts spouses by marriage date.\n * Does not modify the input objects.\n */\nfunction sortIndiSpouses(\n indi: JsonIndi,\n comparator: (id1: string, id2: string) => number,\n): JsonFam {\n if (!indi.fams) {\n return indi;\n }\n const newFams = indi.fams.sort(comparator);\n return Object.assign({}, indi, {fams: newFams});\n}\n\nfunction sortSpouses(gedcom: JsonGedcomData): JsonGedcomData {\n const comparator = marriageDatesComparator(gedcom);\n const newIndis = gedcom.indis.map((indi) =>\n sortIndiSpouses(indi, comparator),\n );\n return Object.assign({}, gedcom, {indis: newIndis});\n}\n\n/** Sorts children and spouses. */\nexport function normalizeGedcom(gedcom: JsonGedcomData): JsonGedcomData {\n return sortSpouses(sortChildren(gedcom));\n}\n\nconst IMAGE_EXTENSIONS = ['.jpg', '.png', '.gif'];\n\n/** Returns true if the given file name has a known image extension. */\nfunction isImageFile(fileName: string): boolean {\n const lowerName = fileName.toLowerCase();\n return IMAGE_EXTENSIONS.some((ext) => lowerName.endsWith(ext));\n}\n\n/**\n * Removes images that are not HTTP links or do not have known image extensions.\n * Does not modify the input object.\n */\nfunction filterImage(indi: JsonIndi, images: Map): JsonIndi {\n if (!indi.images || indi.images.length === 0) {\n return indi;\n }\n const newImages: JsonImage[] = [];\n indi.images.forEach((image) => {\n const fileName = image.url.match(/[^/\\\\]*$/)![0];\n // If the image file has been loaded into memory, use it.\n if (images.has(fileName)) {\n newImages.push({url: images.get(fileName)!, title: image.title});\n } else if (image.url.startsWith('http') && isImageFile(image.url)) {\n newImages.push(image);\n }\n });\n return Object.assign({}, indi, {images: newImages});\n}\n\n/**\n * Removes images that are not HTTP links.\n * Does not modify the input object.\n */\nfunction filterImages(\n gedcom: JsonGedcomData,\n images: Map,\n): JsonGedcomData {\n const newIndis = gedcom.indis.map((indi) => filterImage(indi, images));\n return Object.assign({}, gedcom, {indis: newIndis});\n}\n\n/**\n * Converts GEDCOM file into JSON data performing additional transformations:\n * - sort children by birth date\n * - remove images that are not HTTP links and aren't mapped in `images`.\n *\n * @param images Map from file name to image URL. This is used to pass in\n * uploaded images.\n */\nexport function convertGedcom(\n gedcom: string,\n images: Map,\n): TopolaData {\n const entries = parseGedcom(gedcom);\n const json = gedcomEntriesToJson(entries);\n if (\n !json ||\n !json.indis ||\n !json.indis.length ||\n !json.fams ||\n !json.fams.length\n ) {\n throw new Error('Failed to read GEDCOM file');\n }\n\n return {\n chartData: filterImages(normalizeGedcom(json), images),\n gedcom: prepareGedcom(entries),\n };\n}\n\nexport function getSoftware(head: GedcomEntry): string | null {\n const sour =\n head && head.tree && head.tree.find((entry) => entry.tag === 'SOUR');\n const name =\n sour && sour.tree && sour.tree.find((entry) => entry.tag === 'NAME');\n return (name && name.data) || null;\n}\n","import {Date as TopolaDate, DateRange, getDate} from 'topola';\nimport {InjectedIntl} from 'react-intl';\n\nconst DATE_QUALIFIERS = new Map([\n ['abt', 'about'],\n ['cal', 'calculated'],\n ['est', 'estimated'],\n]);\n\nfunction formatDate(date: TopolaDate, intl: InjectedIntl) {\n const hasDay = date.day !== undefined;\n const hasMonth = date.month !== undefined;\n const hasYear = date.year !== undefined;\n if (!hasDay && !hasMonth && !hasYear) {\n return date.text || '';\n }\n const dateObject = new Date(\n hasYear ? date.year! : 0,\n hasMonth ? date.month! - 1 : 0,\n hasDay ? date.day! : 1,\n );\n\n const qualifier = date.qualifier && date.qualifier.toLowerCase();\n const translatedQualifier =\n qualifier &&\n intl.formatMessage({\n id: `date.${qualifier}`,\n defaultMessage: DATE_QUALIFIERS.get(qualifier) || qualifier,\n });\n\n const formatOptions = {\n day: hasDay ? 'numeric' : undefined,\n month: hasMonth ? 'long' : undefined,\n year: hasYear ? 'numeric' : undefined,\n };\n const translatedDate = new Intl.DateTimeFormat(\n intl.locale,\n formatOptions,\n ).format(dateObject);\n\n return [translatedQualifier, translatedDate].join(' ');\n}\n\nfunction formatDateRage(dateRange: DateRange, intl: InjectedIntl) {\n const fromDate = dateRange.from;\n const toDate = dateRange.to;\n const translatedFromDate = fromDate && formatDate(fromDate, intl);\n const translatedToDate = toDate && formatDate(toDate, intl);\n if (translatedFromDate && translatedToDate) {\n return intl.formatMessage(\n {\n id: 'date.between',\n defaultMessage: 'between {from} and {to}',\n },\n {from: translatedFromDate, to: translatedToDate},\n );\n }\n if (translatedFromDate) {\n return intl.formatMessage(\n {\n id: 'date.after',\n defaultMessage: 'after {from}',\n },\n {from: translatedFromDate},\n );\n }\n if (translatedToDate) {\n return intl.formatMessage(\n {\n id: 'date.before',\n defaultMessage: 'before {to}',\n },\n {to: translatedToDate},\n );\n }\n return '';\n}\n\n/** Formats a date given in GEDCOM format. */\nexport function translateDate(gedcomDate: string, intl: InjectedIntl) {\n const dateOrRange = getDate(gedcomDate);\n if (!dateOrRange) {\n return '';\n }\n if (dateOrRange.date) {\n return formatDate(dateOrRange.date, intl);\n }\n if (dateOrRange.dateRange) {\n return formatDateRage(dateOrRange.dateRange, intl);\n }\n return '';\n}\n","import * as React from 'react';\nimport flatMap from 'array.prototype.flatmap';\nimport Linkify from 'react-linkify';\nimport {FormattedMessage, InjectedIntl} from 'react-intl';\nimport {GedcomData, pointerToId} from './gedcom_util';\nimport {GedcomEntry} from 'parse-gedcom';\nimport {intlShape} from 'react-intl';\nimport {translateDate} from './date_util';\n\ninterface Props {\n gedcom: GedcomData;\n indi: string;\n}\n\nconst EVENT_TAGS = ['BIRT', 'BAPM', 'CHR', 'DEAT', 'BURI', 'EVEN'];\nconst EXCLUDED_TAGS = ['NAME', 'SEX', 'FAMC', 'FAMS', 'NOTE', 'SOUR'];\nconst TAG_DESCRIPTIONS = new Map([\n ['BAPM', 'Baptism'],\n ['BIRT', 'Birth'],\n ['BURI', 'Burial'],\n ['CHR', 'Christening'],\n ['DEAT', 'Death'],\n ['EMAIL', 'E-mail'],\n ['EVEN', 'Event'],\n ['OCCU', 'Occupation'],\n ['TITL', 'Title'],\n ['WWW', 'WWW'],\n]);\n\nfunction translateTag(tag: string) {\n return (\n \n );\n}\n\nfunction joinLines(lines: (JSX.Element | string)[]) {\n return (\n <>\n {lines.map((line, index) => (\n
\n {line}\n
\n
\n ))}\n \n );\n}\n\n/**\n * Returns the data for the given GEDCOM entry as an array of lines. Supports\n * continuations with CONT and CONC.\n */\nfunction getData(entry: GedcomEntry) {\n const result = [entry.data];\n entry.tree.forEach((subentry) => {\n if (subentry.tag === 'CONC' && subentry.data) {\n const last = result.length - 1;\n result[last] += subentry.data;\n } else if (subentry.tag === 'CONT' && subentry.data) {\n result.push(subentry.data);\n }\n });\n return result;\n}\n\nfunction eventDetails(entry: GedcomEntry, intl: InjectedIntl) {\n const lines = [];\n if (entry.data && entry.data.length > 1) {\n lines.push({entry.data});\n }\n const date = entry.tree.find((subentry) => subentry.tag === 'DATE');\n if (date && date.data) {\n lines.push(translateDate(date.data, intl));\n }\n const place = entry.tree.find((subentry) => subentry.tag === 'PLAC');\n if (place && place.data) {\n lines.push(...getData(place));\n }\n entry.tree\n .filter((subentry) => subentry.tag === 'NOTE')\n .forEach((note) =>\n getData(note).forEach((line) => lines.push({line})),\n );\n if (!lines.length) {\n return null;\n }\n return (\n <>\n
{translateTag(entry.tag)}
\n {joinLines(lines)}\n \n );\n}\n\nfunction dataDetails(entry: GedcomEntry) {\n const lines = [];\n if (entry.data) {\n lines.push(...getData(entry));\n }\n entry.tree\n .filter((subentry) => subentry.tag === 'NOTE')\n .forEach((note) =>\n getData(note).forEach((line) => lines.push({line})),\n );\n if (!lines.length) {\n return null;\n }\n return (\n <>\n
{translateTag(entry.tag)}
\n {joinLines(lines)}\n \n );\n}\n\nfunction noteDetails(entry: GedcomEntry) {\n return joinLines(\n getData(entry).map((line, index) => {line}),\n );\n}\n\nfunction nameDetails(entry: GedcomEntry) {\n return (\n

\n {entry.data\n .split('/')\n .filter((name) => !!name)\n .map((name, index) => (\n
\n {name}\n
\n
\n ))}\n

\n );\n}\n\nfunction getDetails(\n entries: GedcomEntry[],\n tags: string[],\n detailsFunction: (entry: GedcomEntry) => JSX.Element | null,\n): JSX.Element[] {\n return flatMap(tags, (tag) =>\n entries\n .filter((entry) => entry.tag === tag)\n .map((entry) => detailsFunction(entry)),\n )\n .filter((element) => element !== null)\n .map((element, index) => (\n
\n {element}\n
\n ));\n}\n\n/**\n * Returns true if there is displayable information in this entry.\n * Returns false if there is no data in this entry or this is only a reference\n * to another entry.\n */\nfunction hasData(entry: GedcomEntry) {\n return entry.tree.length > 0 || (entry.data && !entry.data.startsWith('@'));\n}\n\nfunction getOtherDetails(entries: GedcomEntry[]) {\n return entries\n .filter(\n (entry) =>\n !EXCLUDED_TAGS.includes(entry.tag) && !EVENT_TAGS.includes(entry.tag),\n )\n .filter(hasData)\n .map((entry) => dataDetails(entry))\n .filter((element) => element !== null)\n .map((element, index) => (\n
\n {element}\n
\n ));\n}\n\n/**\n * If the entry is a reference to a top-level entry, the referenced entry is\n * returned. Otherwise, returns the given entry unmodified.\n */\nfunction dereference(entry: GedcomEntry, gedcom: GedcomData) {\n if (entry.data) {\n const dereferenced = gedcom.other[pointerToId(entry.data)];\n if (dereferenced) {\n return dereferenced;\n }\n }\n return entry;\n}\n\nexport class Details extends React.Component {\n /** Make intl appear in this.context. */\n static contextTypes = {\n intl: intlShape,\n };\n\n render() {\n const entries = this.props.gedcom.indis[this.props.indi].tree;\n const entriesWithData = entries\n .map((entry) => dereference(entry, this.props.gedcom))\n .filter(hasData);\n\n return (\n
\n {getDetails(entries, ['NAME'], nameDetails)}\n {getDetails(entries, EVENT_TAGS, (entry) =>\n eventDetails(entry, this.context.intl as InjectedIntl),\n )}\n {getOtherDetails(entriesWithData)}\n {getDetails(entriesWithData, ['NOTE'], noteDetails)}\n
\n );\n }\n}\n","import {convertGedcom, TopolaData} from './gedcom_util';\nimport {IndiInfo, JsonGedcomData} from 'topola';\n\n/**\n * Returns a valid IndiInfo object, either with the given indi and generation\n * or with an individual taken from the data and generation 0.\n */\nexport function getSelection(\n data: JsonGedcomData,\n indi?: string,\n generation?: number,\n): IndiInfo {\n // If ID is not given or it doesn't exist in the data, use the first ID in\n // the data.\n const id =\n indi && data.indis.some((i) => i.id === indi) ? indi : data.indis[0].id;\n return {id, generation: generation || 0};\n}\n\nfunction prepareData(\n gedcom: string,\n cacheId: string,\n images?: Map,\n): TopolaData {\n const data = convertGedcom(gedcom, images || new Map());\n const serializedData = JSON.stringify(data);\n try {\n sessionStorage.setItem(cacheId, serializedData);\n } catch (e) {\n console.warn('Failed to store data in session storage: ' + e);\n }\n return data;\n}\n\n/** Fetches data from the given URL. Uses cors-anywhere if handleCors is true. */\nexport async function loadFromUrl(\n url: string,\n handleCors: boolean,\n): Promise {\n try {\n const cachedData = sessionStorage.getItem(url);\n if (cachedData) {\n return JSON.parse(cachedData);\n }\n } catch (e) {\n console.warn('Failed to load data from session storage: ' + e);\n }\n const urlToFetch = handleCors\n ? 'https://cors-anywhere.herokuapp.com/' + url\n : url;\n\n const response = await window.fetch(urlToFetch);\n if (response.status !== 200) {\n throw new Error(response.statusText);\n }\n const gedcom = await response.text();\n return prepareData(gedcom, url);\n}\n\n/** Loads data from the given GEDCOM file contents. */\nexport async function loadGedcom(\n hash: string,\n gedcom?: string,\n images?: Map,\n): Promise {\n try {\n const cachedData = sessionStorage.getItem(hash);\n if (cachedData) {\n return JSON.parse(cachedData);\n }\n } catch (e) {\n console.warn('Failed to load data from session storage: ' + e);\n }\n if (!gedcom) {\n throw new Error('Error loading data. Please upload your file again.');\n }\n return prepareData(gedcom, hash, images);\n}\n","import * as queryString from 'query-string';\nimport * as React from 'react';\nimport logo from './topola.jpg';\nimport {Card, Grid, Image} from 'semantic-ui-react';\nimport {FormattedMessage} from 'react-intl';\nimport {Link} from 'react-router-dom';\n\n/** Link that loads a GEDCOM file from URL. */\nfunction GedcomLink(props: {url: string; text: string}) {\n return (\n \n {props.text}\n \n );\n}\n\nfunction formatBuildDate(dateString: string) {\n return dateString.slice(0, 16);\n}\n\n/** The intro page. */\nexport function Intro() {\n return (\n
\n
\n \n \n \n \n \n \n \n \n \n \n \"Topola\n \n \n

\n \n

\n

\n \n

\n

\n \n

\n \n

\n \n \n \n {': '}\n \n cors-anywhere\n \n ),\n }}\n />\n

\n

\n version: {formatBuildDate(process.env.REACT_APP_GIT_TIME!)} (\n \n {process.env.REACT_APP_GIT_SHA}\n \n )\n

\n
{' '}\n
{' '}\n
\n
\n
\n
\n );\n}\n","import Cookies from 'js-cookie';\nimport {Date, JsonFam, JsonIndi, DateOrRange} from 'topola';\nimport {GedcomData, TopolaData, normalizeGedcom} from './gedcom_util';\nimport {GedcomEntry} from 'parse-gedcom';\n\n/** WikiTree API getAncestors request. */\ninterface GetAncestorsRequest {\n action: 'getAncestors';\n key: string;\n fields: string;\n}\n\n/** WikiTree API getRelatives request. */\ninterface GetRelatives {\n action: 'getRelatives';\n keys: string;\n getChildren?: true;\n getSpouses?: true;\n}\n\ninterface ClientLogin {\n action: 'clientLogin';\n authcode: string;\n}\n\ntype WikiTreeRequest = GetAncestorsRequest | GetRelatives | ClientLogin;\n\n/** Person structure returned from WikiTree API. */\ninterface Person {\n Id: number;\n Name: string;\n FirstName: string;\n LastNameAtBirth: string;\n Spouses: {[key: number]: Person};\n Children: {[key: number]: Person};\n Mother: number;\n Father: number;\n Gender: string;\n BirthDate: string;\n DeathDate: string;\n BirthLocation: string;\n DeathLocation: string;\n marriage_location: string;\n marriage_date: string;\n DataStatus?: {\n BirthDate: string;\n DeathDate: string;\n };\n PhotoData?: {\n path: string;\n };\n}\n\n/** Gets item from session storage. Logs exception if one is thrown. */\nfunction getSessionStorageItem(key: string): string | null {\n try {\n return sessionStorage.getItem(key);\n } catch (e) {\n console.warn('Failed to load data from session storage: ' + e);\n }\n return null;\n}\n\n/** Sets item in session storage. Logs exception if one is thrown. */\nfunction setSessionStorageItem(key: string, value: string) {\n try {\n sessionStorage.setItem(key, value);\n } catch (e) {\n console.warn('Failed to store data in session storage: ' + e);\n }\n}\n\n/** Sends a request to the WikiTree API. Returns the parsed response JSON. */\nasync function wikiTreeGet(request: WikiTreeRequest, handleCors: boolean) {\n const requestData = new FormData();\n requestData.append('format', 'json');\n for (const key in request) {\n requestData.append(key, request[key]);\n }\n const apiUrl = handleCors\n ? 'https://cors-anywhere.herokuapp.com/https://apps.wikitree.com/api.php'\n : 'https://apps.wikitree.com/api.php';\n const response = await window.fetch(apiUrl, {\n method: 'POST',\n body: requestData,\n });\n const responseBody = await response.text();\n return JSON.parse(responseBody);\n}\n\n/**\n * Retrieves ancestors from WikiTree for the given person ID.\n * Uses sessionStorage for caching responses.\n */\nasync function getAncestors(key: string, handleCors: boolean) {\n const cacheKey = `wikitree:ancestors:${key}`;\n const cachedData = getSessionStorageItem(cacheKey);\n if (cachedData) {\n return JSON.parse(cachedData);\n }\n const response = await wikiTreeGet(\n {\n action: 'getAncestors',\n key: key,\n fields: '*',\n },\n handleCors,\n );\n const result = response[0].ancestors as Person[];\n setSessionStorageItem(cacheKey, JSON.stringify(result));\n return result;\n}\n\n/**\n * Retrieves relatives from WikiTree for the given array of person IDs.\n * Uses sessionStorage for caching responses.\n */\nasync function getRelatives(keys: string[], handleCors: boolean) {\n const result: Person[] = [];\n const keysToFetch: string[] = [];\n keys.forEach((key) => {\n const cachedData = getSessionStorageItem(`wikitree:relatives:${key}`);\n if (cachedData) {\n result.push(JSON.parse(cachedData));\n } else {\n keysToFetch.push(key);\n }\n });\n if (keysToFetch.length === 0) {\n return result;\n }\n const response = await wikiTreeGet(\n {\n action: 'getRelatives',\n keys: keysToFetch.join(','),\n getChildren: true,\n getSpouses: true,\n },\n handleCors,\n );\n if (response[0].items === null) {\n throw new Error(`WikiTree profile ${keysToFetch[0]} not found.`);\n }\n const fetchedResults = response[0].items.map(\n (x: {person: Person}) => x.person,\n ) as Person[];\n fetchedResults.forEach((person) => {\n setSessionStorageItem(\n `wikitree:relatives:${person.Name}`,\n JSON.stringify(person),\n );\n });\n return result.concat(fetchedResults);\n}\n\nexport async function clientLogin(authcode: string) {\n const response = await wikiTreeGet(\n {\n action: 'clientLogin',\n authcode,\n },\n false,\n );\n return response.clientLogin;\n}\n\n/**\n * Loads data from WikiTree to populate an hourglass chart starting from the\n * given person ID.\n */\nexport async function loadWikiTree(\n key: string,\n authcode?: string,\n): Promise {\n // Work around CORS if not in apps.wikitree.com domain.\n const handleCors = window.location.hostname !== 'apps.wikitree.com';\n\n if (!handleCors && !Cookies.get('wikidb_wtb_UserID') && authcode) {\n const loginResult = await clientLogin(authcode);\n if (loginResult.result === 'Success') {\n sessionStorage.clear();\n }\n }\n\n const everyone: Person[] = [];\n\n // Fetch the ancestors of the input person and ancestors of his/her spouses.\n const firstPerson = await getRelatives([key], handleCors);\n if (!firstPerson[0].Name) {\n throw new Error(\n `WikiTree profile ${key} is not accessible. Try logging in.`,\n );\n }\n\n const spouseKeys = Object.values(firstPerson[0].Spouses).map((s) => s.Name);\n const ancestors = await Promise.all(\n [key]\n .concat(spouseKeys)\n .map((personId) => getAncestors(personId, handleCors)),\n );\n const ancestorKeys = ancestors\n .flat()\n .map((person) => person.Name)\n .filter((key) => !!key);\n const ancestorDetails = await getRelatives(ancestorKeys, handleCors);\n everyone.push(...ancestorDetails);\n\n // Limit the number of generations of descendants because there may be tens of\n // generations for some profiles.\n const descendantGenerationLimit = 5;\n\n // Fetch descendants recursively.\n let toFetch = [key];\n let generation = 0;\n while (toFetch.length > 0 && generation <= descendantGenerationLimit) {\n const people = await getRelatives(toFetch, handleCors);\n everyone.push(...people);\n const allSpouses = people.flatMap((person) =>\n Object.values(person.Spouses),\n );\n everyone.push(...allSpouses);\n // Fetch all children.\n toFetch = people.flatMap((person) =>\n Object.values(person.Children).map((c) => c.Name),\n );\n generation++;\n }\n\n // Map from person id to the set of families where they are a spouse.\n const families = new Map>();\n // Map from family id to the set of children.\n const children = new Map>();\n // Map from famliy id to the spouses.\n const spouses = new Map<\n string,\n {wife?: number; husband?: number; spouse?: Person}\n >();\n // Map from numerical id to human-readable id.\n const idToName = new Map();\n\n everyone.forEach((person) => {\n idToName.set(person.Id, person.Name);\n if (person.Mother || person.Father) {\n const famId = getFamilyId(person.Mother, person.Father);\n getSet(families, person.Mother).add(famId);\n getSet(families, person.Father).add(famId);\n getSet(children, famId).add(person.Id);\n spouses.set(famId, {\n wife: person.Mother || undefined,\n husband: person.Father || undefined,\n });\n }\n });\n\n const indis: JsonIndi[] = [];\n const converted = new Set();\n everyone.forEach((person) => {\n if (converted.has(person.Id)) {\n return;\n }\n converted.add(person.Id);\n const indi = convertPerson(person);\n console.log(person, indi);\n if (person.Spouses) {\n Object.values(person.Spouses).forEach((spouse) => {\n const famId = getFamilyId(person.Id, spouse.Id);\n getSet(families, person.Id).add(famId);\n getSet(families, spouse.Id).add(famId);\n const familySpouses =\n person.Gender === 'Male'\n ? {wife: spouse.Id, husband: person.Id, spouse}\n : {wife: person.Id, husband: spouse.Id, spouse};\n spouses.set(famId, familySpouses);\n });\n }\n indi.fams = Array.from(getSet(families, person.Id));\n indis.push(indi);\n });\n\n const fams = Array.from(spouses.entries()).map(([key, value]) => {\n const fam: JsonFam = {\n id: key,\n };\n const wife = value.wife && idToName.get(value.wife);\n if (wife) {\n fam.wife = wife;\n }\n const husband = value.husband && idToName.get(value.husband);\n if (husband) {\n fam.husb = husband;\n }\n fam.children = Array.from(getSet(children, key)).map(\n (child) => idToName.get(child)!,\n );\n if (\n value.spouse &&\n ((value.spouse.marriage_date &&\n value.spouse.marriage_date !== '0000-00-00') ||\n value.spouse.marriage_location)\n ) {\n const parsedDate = parseDate(value.spouse.marriage_date);\n fam.marriage = Object.assign({}, parsedDate, {\n place: value.spouse.marriage_location,\n });\n }\n return fam;\n });\n\n const chartData = normalizeGedcom({indis, fams});\n const gedcom = buildGedcom(indis);\n return {chartData, gedcom};\n}\n\n/** Creates a family identifier given 2 spouse identifiers. */\nfunction getFamilyId(spouse1: number, spouse2: number) {\n if (spouse2 > spouse1) {\n return `${spouse1}_${spouse2}`;\n }\n return `${spouse2}_${spouse1}`;\n}\n\nfunction convertPerson(person: Person): JsonIndi {\n const indi: JsonIndi = {\n id: person.Name,\n };\n if (person.FirstName !== 'Unknown') {\n indi.firstName = person.FirstName;\n }\n if (person.LastNameAtBirth !== 'Unknown') {\n indi.lastName = person.LastNameAtBirth;\n }\n if (person.Mother || person.Father) {\n indi.famc = getFamilyId(person.Mother, person.Father);\n }\n if (person.Gender === 'Male') {\n indi.sex = 'M';\n } else if (person.Gender === 'Female') {\n indi.sex = 'F';\n }\n if (\n (person.BirthDate && person.BirthDate !== '0000-00-00') ||\n person.BirthLocation\n ) {\n const parsedDate = parseDate(\n person.BirthDate,\n person.DataStatus && person.DataStatus.BirthDate,\n );\n indi.birth = Object.assign({}, parsedDate, {place: person.BirthLocation});\n }\n if (\n (person.DeathDate && person.DeathDate !== '0000-00-00') ||\n person.DeathLocation\n ) {\n const parsedDate = parseDate(\n person.DeathDate,\n person.DataStatus && person.DataStatus.DeathDate,\n );\n indi.death = Object.assign({}, parsedDate, {place: person.DeathLocation});\n }\n if (person.PhotoData) {\n indi.images = [{url: `https://wikitree.com${person.PhotoData.path}`}];\n }\n return indi;\n}\n\n/**\n * Parses a date in the format returned by WikiTree and converts in to\n * the format defined by Topola.\n */\nfunction parseDate(date: string, dataStatus?: string): DateOrRange | undefined {\n if (!date) {\n return undefined;\n }\n const matchedDate = date.match(/(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)/);\n if (!matchedDate) {\n return {date: {text: date}};\n }\n const parsedDate: Date = {};\n if (matchedDate[1] !== '0000') {\n parsedDate.year = ~~matchedDate[1];\n }\n if (matchedDate[2] !== '00') {\n parsedDate.month = ~~matchedDate[2];\n }\n if (matchedDate[3] !== '00') {\n parsedDate.day = ~~matchedDate[3];\n }\n if (dataStatus === 'after') {\n return {dateRange: {from: parsedDate}};\n }\n if (dataStatus === 'before') {\n return {dateRange: {to: parsedDate}};\n }\n if (dataStatus === 'guess') {\n parsedDate.qualifier = 'abt';\n }\n return {date: parsedDate};\n}\n\n/**\n * Creates a GEDCOM structure for the purpose of displaying the details\n * panel.\n */\nfunction buildGedcom(indis: JsonIndi[]): GedcomData {\n const gedcomIndis: {[key: string]: GedcomEntry} = {};\n indis.forEach((indi) => {\n // WikiTree URLs replace spaces with underscores.\n const escapedId = indi.id.replace(/ /g, '_');\n gedcomIndis[indi.id] = {\n level: 0,\n pointer: `@${indi.id}@`,\n tag: 'INDI',\n data: '',\n tree: [\n {\n level: 1,\n pointer: '',\n tag: 'NAME',\n data: `${indi.firstName || ''} /${indi.lastName || ''}/`,\n tree: [],\n },\n {\n level: 1,\n pointer: '',\n tag: 'WWW',\n data: `https://www.wikitree.com/wiki/${escapedId}`,\n tree: [],\n },\n ],\n };\n });\n\n return {\n head: {level: 0, pointer: '', tag: 'HEAD', data: '', tree: []},\n indis: gedcomIndis,\n fams: {},\n other: {},\n };\n}\n\n/**\n * Returns a set which is a value from a SetMultimap. If the key doesn't exist,\n * an empty set is added to the map.\n */\nfunction getSet(map: Map>, key: K): Set {\n const set = map.get(key);\n if (set) {\n return set;\n }\n const newSet = new Set();\n map.set(key, newSet);\n return newSet;\n}\n","import naturalSort from 'javascript-natural-sort';\nimport lunr from 'lunr';\nimport {GedcomData, pointerToId} from './gedcom_util';\nimport {GedcomEntry} from 'parse-gedcom';\n\nconst MAX_RESULTS = 8;\n\nexport interface SearchResult {\n id: string;\n indi: GedcomEntry;\n}\n\nexport interface SearchIndex {\n search(input: string): SearchResult[];\n}\n\n/** Removes accents from letters, e.g. ó->o, ę->e. */\nfunction normalize(input: string) {\n return input\n .toLocaleLowerCase()\n .normalize('NFD')\n .replace(/[\\u0300-\\u036f]/g, '')\n .replace(/\\u0142/g, 'l'); // Special case: ł is not affected by NFD.\n}\n\n/** Comparator to sort by score first, then by id. */\nfunction compare(a: lunr.Index.Result, b: lunr.Index.Result) {\n if (a.score !== b.score) {\n return b.score - a.score;\n }\n return naturalSort(a.ref, b.ref);\n}\n\n/** Returns all last names of all husbands as a space-separated string. */\nfunction getHusbandLastName(indi: GedcomEntry, gedcom: GedcomData): string {\n return indi.tree\n .filter((entry) => entry.tag === 'FAMS')\n .map((entry) => gedcom.fams[pointerToId(entry.data)])\n .filter((entry) => !!entry)\n .map((entry) => {\n const husband = entry.tree.find((entry) => entry.tag === 'HUSB');\n const husbandId = husband && pointerToId(husband.data);\n return (\n husbandId &&\n husbandId !== pointerToId(indi.pointer) &&\n gedcom.indis[husbandId]\n );\n })\n .filter((entry) => !!entry)\n .flatMap((husband) =>\n (husband as GedcomEntry).tree\n .filter((entry) => entry.tag === 'NAME')\n .map((entry) => {\n const names = entry.data.split('/');\n return names.length >= 2 ? names[1] : '';\n }),\n )\n .join(' ');\n}\n\nclass LunrSearchIndex implements SearchIndex {\n private index: lunr.Index | undefined;\n\n constructor(private gedcom: GedcomData) {}\n\n initialize() {\n const self = this;\n this.index = lunr(function() {\n this.ref('id');\n this.field('id');\n this.field('name', {boost: 10});\n this.field('normalizedName', {boost: 8});\n this.field('spouseLastName', {boost: 2});\n this.field('normalizedSpouseLastName', {boost: 2});\n\n for (let id in self.gedcom.indis) {\n const indi = self.gedcom.indis[id];\n const name = indi.tree\n .filter((entry) => entry.tag === 'NAME')\n .map((entry) => entry.data)\n .join(' ');\n const spouseLastName = getHusbandLastName(indi, self.gedcom);\n this.add({\n id,\n name,\n normalizedName: normalize(name),\n spouseLastName,\n normalizedSpouseLastName: normalize(spouseLastName),\n });\n }\n });\n }\n\n public search(input: string) {\n const query = input\n .split(' ')\n .filter((s) => !!s)\n .map((s) => `+${s}*`)\n .join(' ');\n const results = this.index!.search(query);\n return results\n .sort(compare)\n .slice(0, MAX_RESULTS)\n .map((result) => ({id: result.ref, indi: this.gedcom.indis[result.ref]}));\n }\n}\n\n/** Builds a search index from data. */\nexport function buildSearchIndex(gedcom: GedcomData): SearchIndex {\n const index = new LunrSearchIndex(gedcom);\n index.initialize();\n return index;\n}\n","import * as React from 'react';\nimport {GedcomEntry} from 'parse-gedcom';\nimport {InjectedIntl} from 'react-intl';\nimport {SearchResult} from './search_index';\nimport {translateDate} from './date_util';\n\nfunction getNameLine(result: SearchResult) {\n const nameTag = result.indi.tree.find((entry) => entry.tag === 'NAME');\n const name =\n nameTag &&\n nameTag.data\n .split('/')\n .filter((s) => !!s)\n .join(' ');\n if (result.id.length > 8) {\n return name;\n }\n return (\n <>\n {name} ({result.id})\n \n );\n}\n\nfunction getDate(indi: GedcomEntry, tag: string, intl: InjectedIntl) {\n const eventEntry = indi.tree.find((entry) => entry.tag === tag);\n const dateEntry =\n eventEntry && eventEntry.tree.find((entry) => entry.tag === 'DATE');\n return (dateEntry && translateDate(dateEntry.data, intl)) || '';\n}\n\nfunction getDescriptionLine(indi: GedcomEntry, intl: InjectedIntl) {\n const birthDate = getDate(indi, 'BIRT', intl);\n const deathDate = getDate(indi, 'DEAT', intl);\n if (!deathDate) {\n return birthDate;\n }\n return `${birthDate} – ${deathDate}`;\n}\n\n/** Produces an object that is displayed in the Semantic UI Search results. */\nexport function displaySearchResult(result: SearchResult, intl: InjectedIntl) {\n return {\n id: result.id,\n key: result.id,\n title: getNameLine(result),\n description: getDescriptionLine(result.indi, intl),\n };\n}\n","import * as queryString from 'query-string';\nimport * as React from 'react';\nimport Cookies from 'js-cookie';\nimport debounce from 'debounce';\nimport md5 from 'md5';\nimport {analyticsEvent} from './analytics';\nimport {buildSearchIndex, SearchIndex} from './search_index';\nimport {displaySearchResult} from './search_util';\nimport {FormattedMessage, intlShape} from 'react-intl';\nimport {GedcomData} from './gedcom_util';\nimport {IndiInfo} from 'topola';\nimport {Link} from 'react-router-dom';\nimport {RouteComponentProps} from 'react-router-dom';\nimport {\n Header,\n Button,\n Icon,\n Menu,\n Modal,\n Input,\n Form,\n Dropdown,\n Search,\n SearchProps,\n SearchResultProps,\n} from 'semantic-ui-react';\n\nenum WikiTreeLoginState {\n UNKNOWN,\n NOT_LOGGED_IN,\n LOGGED_IN,\n}\n\n/** Menus and dialogs state. */\ninterface State {\n loadUrlDialogOpen: boolean;\n url?: string;\n wikiTreeLoginState: WikiTreeLoginState;\n wikiTreeLoginUsername?: string;\n searchResults: SearchResultProps[];\n}\n\ninterface EventHandlers {\n onSelection: (indiInfo: IndiInfo) => void;\n onPrint: () => void;\n onDownloadPdf: () => void;\n onDownloadPng: () => void;\n onDownloadSvg: () => void;\n}\n\ninterface Props {\n /** True if the application is currently showing a chart. */\n showingChart: boolean;\n /** Data used for the search index. */\n gedcom?: GedcomData;\n standalone: boolean;\n /** Whether to show the \"All relatives\" chart type in the menu. */\n allowAllRelativesChart: boolean;\n eventHandlers: EventHandlers;\n /** Whether to show the 'Log in to WikiTree' button. */\n showWikiTreeLogin: boolean;\n}\n\nfunction loadFileAsText(file: File): Promise {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = (evt: ProgressEvent) => {\n resolve((evt.target as FileReader).result as string);\n };\n reader.readAsText(file);\n });\n}\n\nfunction isImageFileName(fileName: string) {\n const lower = fileName.toLowerCase();\n return lower.endsWith('.jpg') || lower.endsWith('.png');\n}\n\nexport class TopBar extends React.Component<\n RouteComponentProps & Props,\n State\n> {\n state: State = {\n loadUrlDialogOpen: false,\n searchResults: [],\n wikiTreeLoginState: WikiTreeLoginState.UNKNOWN,\n };\n /** Make intl appear in this.context. */\n static contextTypes = {\n intl: intlShape,\n };\n\n urlInputRef: React.RefObject = React.createRef();\n wikiTreeLoginFormRef: React.RefObject = React.createRef();\n wikiTreeReturnUrlRef: React.RefObject = React.createRef();\n searchRef?: {setValue(value: string): void};\n searchIndex?: SearchIndex;\n\n /** Handles the \"Upload file\" button. */\n private async handleUpload(event: React.SyntheticEvent) {\n const files = (event.target as HTMLInputElement).files;\n if (!files || !files.length) {\n return;\n }\n const filesArray = Array.from(files);\n (event.target as HTMLInputElement).value = ''; // Reset the file input.\n analyticsEvent('upload_files_selected', {\n event_value: files.length,\n });\n\n const gedcomFile =\n filesArray.length === 1\n ? filesArray[0]\n : filesArray.find((file) => file.name.toLowerCase().endsWith('.ged')) ||\n filesArray[0];\n\n // Convert uploaded images to object URLs.\n const images = filesArray\n .filter(\n (file) => file.name !== gedcomFile.name && isImageFileName(file.name),\n )\n .map((file) => ({\n name: file.name,\n url: URL.createObjectURL(file),\n }));\n const imageMap = new Map(\n images.map((entry) => [entry.name, entry.url] as [string, string]),\n );\n\n const data = await loadFileAsText(gedcomFile);\n const imageFileNames = images\n .map((image) => image.name)\n .sort()\n .join('|');\n // Hash GEDCOM contents with uploaded image file names.\n const hash = md5(md5(data) + imageFileNames);\n\n // Use history.replace() when reuploading the same file and history.push() when loading\n // a new file.\n const search = queryString.parse(this.props.location.search);\n const historyPush =\n search.file === hash\n ? this.props.history.replace\n : this.props.history.push;\n\n historyPush({\n pathname: '/view',\n search: queryString.stringify({file: hash}),\n state: {data, images: imageMap},\n });\n }\n\n /** Opens the \"Load from URL\" dialog. */\n private openLoadUrlDialog() {\n this.setState(\n Object.assign({}, this.state, {loadUrlDialogOpen: true}),\n () => this.urlInputRef.current!.focus(),\n );\n }\n\n /** Cancels the \"Load from URL\" dialog. */\n private handleClose() {\n this.setState(Object.assign({}, this.state, {loadUrlDialogOpen: false}));\n }\n\n /** Upload button clicked in the \"Load from URL\" dialog. */\n private handleLoad() {\n this.setState(\n Object.assign({}, this.state, {\n loadUrlDialogOpen: false,\n }),\n );\n if (this.state.url) {\n analyticsEvent('url_selected');\n this.props.history.push({\n pathname: '/view',\n search: queryString.stringify({url: this.state.url}),\n });\n }\n }\n\n /** Called when the URL input is typed into. */\n private handleUrlChange(event: React.SyntheticEvent) {\n this.setState(\n Object.assign({}, this.state, {\n url: (event.target as HTMLInputElement).value,\n }),\n );\n }\n\n /** On search input change. */\n private handleSearch(input: string | undefined) {\n if (!input) {\n return;\n }\n const results = this.searchIndex!.search(input).map((result) =>\n displaySearchResult(result, this.context.intl),\n );\n this.setState(Object.assign({}, this.state, {searchResults: results}));\n }\n\n /** On search result selected. */\n private handleResultSelect(id: string) {\n analyticsEvent('search_result_selected');\n this.props.eventHandlers.onSelection({id, generation: 0});\n this.searchRef!.setValue('');\n }\n\n private initializeSearchIndex() {\n if (this.props.gedcom) {\n this.searchIndex = buildSearchIndex(this.props.gedcom);\n }\n }\n\n changeView(view: string) {\n const location = this.props.location;\n const search = queryString.parse(location.search);\n if (search.view !== view) {\n search.view = view;\n location.search = queryString.stringify(search);\n this.props.history.push(location);\n }\n }\n\n /**\n * Redirect to the WikiTree Apps login page with a return URL pointing to\n * Topola Viewer hosted on apps.wikitree.com.\n */\n private wikiTreeLogin() {\n const wikiTreeTopolaUrl =\n 'https://apps.wikitree.com/apps/wiech13/topola-viewer';\n // Append '&' because the login page appends '?authcode=...' to this URL.\n // TODO: remove ?authcode if it is in the current URL.\n const returnUrl = `${wikiTreeTopolaUrl}${window.location.hash}&`;\n this.wikiTreeReturnUrlRef.current!.value = returnUrl;\n this.wikiTreeLoginFormRef.current!.submit();\n }\n\n private checkWikiTreeLoginState() {\n const wikiTreeLoginState =\n Cookies.get('wikidb_wtb_UserID') !== undefined\n ? WikiTreeLoginState.LOGGED_IN\n : WikiTreeLoginState.NOT_LOGGED_IN;\n if (this.state.wikiTreeLoginState !== wikiTreeLoginState) {\n const wikiTreeLoginUsername = Cookies.get('wikidb_wtb_UserName');\n this.setState(\n Object.assign({}, this.state, {\n wikiTreeLoginState,\n wikiTreeLoginUsername,\n }),\n );\n }\n }\n\n async componentDidMount() {\n this.checkWikiTreeLoginState();\n this.initializeSearchIndex();\n }\n\n componentDidUpdate(prevProps: Props) {\n this.checkWikiTreeLoginState();\n if (prevProps.gedcom !== this.props.gedcom) {\n this.initializeSearchIndex();\n }\n }\n\n private loadFromUrlModal() {\n return (\n this.handleClose()}\n centered={false}\n >\n
\n \n txt}\n />\n
\n \n
this.handleLoad()}>\n this.handleUrlChange(e)}\n ref={this.urlInputRef}\n />\n

\n \n cors-anywhere.herokuapp.com\n \n ),\n }}\n />\n

\n \n
\n \n \n \n \n \n );\n }\n\n private chartMenus() {\n if (!this.props.showingChart) {\n return null;\n }\n return (\n <>\n this.props.eventHandlers.onPrint()}>\n \n \n \n\n \n \n \n
\n }\n className=\"item\"\n >\n \n this.props.eventHandlers.onDownloadPdf()}\n >\n \n \n this.props.eventHandlers.onDownloadPng()}\n >\n \n \n this.props.eventHandlers.onDownloadSvg()}\n >\n \n \n \n \n\n \n \n \n \n }\n className=\"item\"\n >\n \n this.changeView('hourglass')}>\n \n \n \n {this.props.allowAllRelativesChart ? (\n this.changeView('relatives')}>\n \n \n \n ) : null}\n this.changeView('fancy')}>\n \n \n \n \n \n\n , data: SearchProps) =>\n this.handleSearch(data.value),\n 200,\n )}\n onResultSelect={(_, data) => this.handleResultSelect(data.result.id)}\n results={this.state.searchResults}\n noResultsMessage={this.context.intl.formatMessage({\n id: 'menu.search.no_results',\n defaultMessage: 'No results found',\n })}\n placeholder={this.context.intl.formatMessage({\n id: 'menu.search.placeholder',\n defaultMessage: 'Search for people',\n })}\n selectFirstResult={true}\n ref={(ref) =>\n (this.searchRef = (ref as unknown) as {\n setValue(value: string): void;\n })\n }\n />\n \n );\n }\n\n private fileMenus() {\n if (!this.props.standalone) {\n return null;\n }\n return (\n <>\n \n \n Topola Genealogy\n \n \n this.openLoadUrlDialog()}>\n \n \n \n this.handleUpload(e)}\n />\n \n \n );\n }\n\n private wikiTreeLoginMenu() {\n if (!this.props.showWikiTreeLogin) {\n return null;\n }\n const wikiTreeLogoUrl =\n 'https://www.wikitree.com/photo.php/a/a5/WikiTree_Images.png';\n switch (this.state.wikiTreeLoginState) {\n case WikiTreeLoginState.NOT_LOGGED_IN:\n return (\n this.wikiTreeLogin()}>\n \n \n \n \n \n \n \n );\n case WikiTreeLoginState.LOGGED_IN:\n const tooltip = this.state.wikiTreeLoginUsername\n ? this.context.intl.formatMessage(\n {\n id: 'menu.wikitree_popup_username',\n defaultMessage: 'Logged in to WikiTree as {username}',\n },\n {username: this.state.wikiTreeLoginUsername},\n )\n : this.context.intl.formatMessage({\n id: 'menu.wikitree_popup',\n defaultMessage: 'Logged in to WikiTree',\n });\n return (\n \n \n \n \n );\n default:\n return null;\n }\n }\n\n private sourceLink() {\n return (\n \n \n \n );\n }\n\n private poweredByLink() {\n return (\n \n \n \n );\n }\n\n render() {\n return (\n \n {this.fileMenus()}\n {this.chartMenus()}\n \n {this.wikiTreeLoginMenu()}\n {this.props.standalone ? this.sourceLink() : this.poweredByLink()}\n \n {this.loadFromUrlModal()}\n \n );\n }\n}\n","import * as H from 'history';\nimport * as queryString from 'query-string';\nimport * as React from 'react';\nimport {analyticsEvent} from './analytics';\nimport {Chart, ChartType} from './chart';\nimport {Details} from './details';\nimport {FormattedMessage} from 'react-intl';\nimport {getSelection, loadFromUrl, loadGedcom} from './load_data';\nimport {getSoftware, TopolaData} from './gedcom_util';\nimport {IndiInfo} from 'topola';\nimport {intlShape} from 'react-intl';\nimport {Intro} from './intro';\nimport {Loader, Message, Portal, Responsive} from 'semantic-ui-react';\nimport {loadWikiTree} from './wikitree';\nimport {Redirect, Route, RouteComponentProps, Switch} from 'react-router-dom';\nimport {TopBar} from './top_bar';\n\n/** Shows an error message in the middle of the screen. */\nfunction ErrorMessage(props: {message?: string}) {\n return (\n \n \n \n \n

{props.message}

\n
\n );\n}\n\ninterface ErrorPopupProps {\n message?: string;\n open: boolean;\n onDismiss: () => void;\n}\n\n/**\n * Shows a dismissable error message in the bottom left corner of the screen.\n */\nfunction ErrorPopup(props: ErrorPopupProps) {\n return (\n \n \n \n \n \n

{props.message}

\n
\n
\n );\n}\n\n/**\n * Message types used in embedded mode.\n * When the parent is ready to receive messages, it sends PARENT_READY.\n * When the child (this app) is ready to receive messages, it sends READY.\n * When the child receives PARENT_READY, it sends READY.\n * When the parent receives READY, it sends data in a GEDCOM message.\n */\nenum EmbeddedMessageType {\n GEDCOM = 'gedcom',\n READY = 'ready',\n PARENT_READY = 'parent_ready',\n}\n\n/** Message sent to parent or received from parent in embedded mode. */\ninterface EmbeddedMessage {\n message: EmbeddedMessageType;\n}\n\ninterface GedcomMessage extends EmbeddedMessage {\n message: EmbeddedMessageType.GEDCOM;\n gedcom?: string;\n}\n\n/** Interface encapsulating functions specific for a data source. */\ninterface DataSource {\n /**\n * Returns true if the application is now loading a completely new data set\n * and the existing one should be wiped.\n */\n isNewData(args: Arguments, state: State): boolean;\n /** Loads data from the data source. */\n loadData(args: Arguments): Promise;\n}\n\n/** Files opened from the local computer. */\nclass UploadedDataSource implements DataSource {\n isNewData(args: Arguments, state: State): boolean {\n return (\n args.hash !== state.hash ||\n !!(args.gedcom && !state.loading && !state.data)\n );\n }\n\n async loadData(args: Arguments): Promise {\n try {\n const data = await loadGedcom(args.hash!, args.gedcom, args.images);\n const software = getSoftware(data.gedcom.head);\n analyticsEvent('upload_file_loaded', {\n event_label: software,\n event_value: (args.images && args.images.size) || 0,\n });\n return data;\n } catch (error) {\n analyticsEvent('upload_file_error');\n throw error;\n }\n }\n}\n\n/** GEDCOM file loaded by pointing to a URL. */\nclass GedcomUrlDataSource implements DataSource {\n isNewData(args: Arguments, state: State): boolean {\n return args.url !== state.url;\n }\n\n async loadData(args: Arguments): Promise {\n try {\n const data = await loadFromUrl(args.url!, args.handleCors);\n const software = getSoftware(data.gedcom.head);\n analyticsEvent('upload_file_loaded', {event_label: software});\n return data;\n } catch (error) {\n analyticsEvent('url_file_error');\n throw error;\n }\n }\n}\n\n/** Loading data from the WikiTree API. */\nclass WikiTreeDataSource implements DataSource {\n isNewData(args: Arguments, state: State): boolean {\n // WikiTree is always a single data source.\n return false;\n }\n\n async loadData(args: Arguments): Promise {\n try {\n const data = await loadWikiTree(args.indi!, args.authcode);\n analyticsEvent('wikitree_loaded');\n return data;\n } catch (error) {\n analyticsEvent('wikitree_error');\n throw error;\n }\n }\n}\n\n/** Supported data sources. */\nenum DataSourceEnum {\n UPLOADED,\n GEDCOM_URL,\n WIKITREE,\n}\n\n/** Mapping from data source identifier to data source handler functions. */\nconst DATA_SOURCES = new Map([\n [DataSourceEnum.UPLOADED, new UploadedDataSource()],\n [DataSourceEnum.GEDCOM_URL, new GedcomUrlDataSource()],\n [DataSourceEnum.WIKITREE, new WikiTreeDataSource()],\n]);\n\n/** Arguments passed to the application, primarily through URL parameters. */\ninterface Arguments {\n showSidePanel: boolean;\n embedded: boolean;\n url?: string;\n indi?: string;\n generation?: number;\n hash?: string;\n handleCors: boolean;\n standalone: boolean;\n source?: DataSourceEnum;\n authcode?: string;\n chartType: ChartType;\n gedcom?: string;\n images?: Map;\n enableZoom: boolean;\n}\n\n/**\n * Retrieve arguments passed into the application through the URL and uploaded\n * data.\n */\nfunction getArguments(location: H.Location): Arguments {\n const search = queryString.parse(location.search);\n const getParam = (name: string) => {\n const value = search[name];\n return typeof value === 'string' ? value : undefined;\n };\n\n const parsedGen = Number(getParam('gen'));\n const view = getParam('view');\n const chartTypes = new Map([\n ['relatives', ChartType.Relatives],\n ['fancy', ChartType.Fancy],\n ]);\n const hash = getParam('file');\n const url = getParam('url');\n const source =\n getParam('source') === 'wikitree'\n ? DataSourceEnum.WIKITREE\n : hash\n ? DataSourceEnum.UPLOADED\n : url\n ? DataSourceEnum.GEDCOM_URL\n : undefined;\n return {\n showSidePanel: getParam('sidePanel') !== 'false', // True by default.\n embedded: getParam('embedded') === 'true', // False by default.\n url,\n indi: getParam('indi'),\n generation: !isNaN(parsedGen) ? parsedGen : undefined,\n hash,\n handleCors: getParam('handleCors') !== 'false', // True by default.\n standalone: getParam('standalone') !== 'false', // True by default.\n source,\n authcode: getParam('?authcode'),\n\n // Hourglass is the default view.\n chartType: chartTypes.get(view) || ChartType.Hourglass,\n\n gedcom: location.state && location.state.data,\n images: location.state && location.state.images,\n enableZoom: getParam('enableZoom') !== 'false', // True by default.\n };\n}\n\n/** Returs true if the changes object has values that are different than those in state. */\nfunction hasUpdatedValues(state: T, changes: Partial | undefined) {\n if (!changes) {\n return false;\n }\n return Object.entries(changes).some(\n ([key, value]) => value !== undefined && state[key] !== value,\n );\n}\n\ninterface State {\n /** Loaded data. */\n data?: TopolaData;\n /** Selected individual. */\n selection?: IndiInfo;\n /** Hash of the GEDCOM contents. */\n hash?: string;\n /** Error to display. */\n error?: string;\n /** True if data is currently being loaded. */\n loading: boolean;\n /** URL of the data that is loaded or is being loaded. */\n url?: string;\n /** Whether the side panel is shown. */\n showSidePanel?: boolean;\n /** Whether the app is in embedded mode, i.e. embedded in an iframe. */\n embedded: boolean;\n /** Whether the app is in standalone mode, i.e. showing 'open file' menus. */\n standalone: boolean;\n /** Type of displayed chart. */\n chartType: ChartType;\n /** Whether to show the error popup. */\n showErrorPopup: boolean;\n /** Source of the data. */\n source?: DataSourceEnum;\n loadingMore?: boolean;\n /** Whether the zoom functionality is enabled. */\n enableZoom: boolean;\n}\n\nexport class App extends React.Component {\n state: State = {\n loading: false,\n embedded: false,\n standalone: true,\n chartType: ChartType.Hourglass,\n showErrorPopup: false,\n enableZoom: false,\n };\n chartRef: Chart | null = null;\n\n /** Make intl appear in this.context. */\n static contextTypes = {\n intl: intlShape,\n };\n\n /** Sets the state with a new individual selection and chart type. */\n private updateDisplay(\n selection: IndiInfo,\n otherStateChanges?: Partial,\n ) {\n if (\n !this.state.selection ||\n this.state.selection.id !== selection.id ||\n this.state.selection!.generation !== selection.generation ||\n hasUpdatedValues(this.state, otherStateChanges)\n ) {\n this.setState(\n Object.assign({}, this.state, {selection}, otherStateChanges),\n );\n }\n }\n\n /** Sets error message after data load failure. */\n private setError(error: string) {\n this.setState(\n Object.assign({}, this.state, {\n error: error,\n loading: false,\n }),\n );\n }\n\n private async onMessage(message: EmbeddedMessage) {\n if (message.message === EmbeddedMessageType.PARENT_READY) {\n // Parent didn't receive the first 'ready' message, so we need to send it again.\n window.parent.postMessage({message: EmbeddedMessageType.READY}, '*');\n } else if (message.message === EmbeddedMessageType.GEDCOM) {\n const gedcom = (message as GedcomMessage).gedcom;\n if (!gedcom) {\n return;\n }\n try {\n const data = await loadGedcom('', gedcom);\n const software = getSoftware(data.gedcom.head);\n analyticsEvent('embedded_file_loaded', {\n event_label: software,\n });\n // Set state with data.\n this.setState(\n Object.assign({}, this.state, {\n data,\n selection: getSelection(data.chartData),\n error: undefined,\n loading: false,\n }),\n );\n } catch (error) {\n analyticsEvent('embedded_file_error');\n this.setError(error.message);\n }\n }\n }\n\n componentDidMount() {\n this.componentDidUpdate();\n }\n\n async componentDidUpdate() {\n if (this.props.location.pathname !== '/view') {\n return;\n }\n\n const args = getArguments(this.props.location);\n\n if (args.embedded && !this.state.embedded) {\n this.setState(\n Object.assign({}, this.state, {\n embedded: true,\n standalone: false,\n showSidePanel: args.showSidePanel,\n }),\n );\n // Notify the parent window that we are ready.\n window.parent.postMessage('ready', '*');\n window.addEventListener('message', (data) => this.onMessage(data.data));\n }\n if (args.embedded) {\n // If the app is embedded, do not run the normal loading code.\n return;\n }\n\n const dataSource = DATA_SOURCES.get(args.source!);\n\n if (!dataSource) {\n this.props.history.replace({pathname: '/'});\n } else if (\n (!this.state.loading && !this.state.data && !this.state.error) ||\n args.source !== this.state.source ||\n dataSource.isNewData(args, this.state)\n ) {\n // Set loading state.\n this.setState(\n Object.assign({}, this.state, {\n data: undefined,\n selection: undefined,\n hash: args.hash,\n error: undefined,\n loading: true,\n url: args.url,\n standalone: args.standalone,\n chartType: args.chartType,\n source: args.source,\n enableZoom: args.enableZoom,\n }),\n );\n try {\n const data = await dataSource.loadData(args);\n\n // Set state with data.\n this.setState(\n Object.assign({}, this.state, {\n data,\n hash: args.hash,\n selection: getSelection(data.chartData, args.indi, args.generation),\n error: undefined,\n loading: false,\n url: args.url,\n showSidePanel: args.showSidePanel,\n standalone: args.standalone,\n chartType: args.chartType,\n source: args.source,\n enableZoom: args.enableZoom,\n }),\n );\n } catch (error) {\n this.setError(error.message);\n }\n } else if (this.state.data && this.state.selection) {\n // Update selection if it has changed in the URL.\n const selection = getSelection(\n this.state.data.chartData,\n args.indi,\n args.generation,\n );\n const loadMoreFromWikitree =\n args.source === DataSourceEnum.WIKITREE &&\n (!this.state.selection || this.state.selection.id !== selection.id);\n this.updateDisplay(selection, {\n chartType: args.chartType,\n loadingMore: loadMoreFromWikitree || undefined,\n });\n if (loadMoreFromWikitree) {\n const data = await loadWikiTree(args.indi!);\n this.setState(\n Object.assign({}, this.state, {\n data,\n hash: args.hash,\n selection: getSelection(data.chartData, args.indi, args.generation),\n error: undefined,\n loading: false,\n url: args.url,\n showSidePanel: args.showSidePanel,\n standalone: args.standalone,\n chartType: args.chartType,\n source: args.source,\n enableZoom: args.enableZoom,\n loadingMore: false,\n }),\n );\n }\n }\n }\n\n /**\n * Called when the user clicks an individual box in the chart.\n * Updates the browser URL.\n */\n private onSelection = (selection: IndiInfo) => {\n analyticsEvent('selection_changed');\n if (this.state.embedded) {\n // In embedded mode the URL doesn't change.\n this.updateDisplay(selection);\n return;\n }\n const location = this.props.location;\n const search = queryString.parse(location.search);\n search.indi = selection.id;\n search.gen = String(selection.generation);\n location.search = queryString.stringify(search);\n this.props.history.push(location);\n };\n\n private onPrint = () => {\n analyticsEvent('print');\n this.chartRef && this.chartRef.print();\n };\n\n private showErrorPopup(message: string) {\n this.setState(\n Object.assign({}, this.state, {\n showErrorPopup: true,\n error: message,\n }),\n );\n }\n\n private onDownloadPdf = async () => {\n analyticsEvent('download_pdf');\n try {\n this.chartRef && (await this.chartRef.downloadPdf());\n } catch (e) {\n this.showErrorPopup(\n this.context.intl.formatMessage({\n id: 'error.failed_pdf',\n defaultMessage:\n 'Failed to generate PDF file.' +\n ' Please try with a smaller diagram or download an SVG file.',\n }),\n );\n }\n };\n\n private onDownloadPng = async () => {\n analyticsEvent('download_png');\n try {\n this.chartRef && (await this.chartRef.downloadPng());\n } catch (e) {\n this.showErrorPopup(\n this.context.intl.formatMessage({\n id: 'error.failed_png',\n defaultMessage:\n 'Failed to generate PNG file.' +\n ' Please try with a smaller diagram or download an SVG file.',\n }),\n );\n }\n };\n\n private onDownloadSvg = () => {\n analyticsEvent('download_svg');\n this.chartRef && this.chartRef.downloadSvg();\n };\n\n onDismissErrorPopup = () => {\n this.setState(\n Object.assign({}, this.state, {\n showErrorPopup: false,\n }),\n );\n };\n\n private renderMainArea = () => {\n if (this.state.data && this.state.selection) {\n return (\n
\n \n {this.state.loadingMore ? (\n \n ) : null}\n (this.chartRef = ref)}\n enableZoom={this.state.enableZoom}\n />\n {this.state.showSidePanel ? (\n \n \n \n ) : null}\n
\n );\n }\n if (this.state.error) {\n return ;\n }\n return ;\n };\n\n render() {\n return (\n <>\n (\n \n )}\n />\n \n \n \n \n \n \n );\n }\n}\n","import * as locale_en from 'react-intl/locale-data/en';\nimport * as locale_pl from 'react-intl/locale-data/pl';\nimport * as React from 'react';\nimport * as ReactDOM from 'react-dom';\nimport messages_pl from './translations/pl.json';\nimport {addLocaleData} from 'react-intl';\nimport {App} from './app';\nimport {detect} from 'detect-browser';\nimport {HashRouter as Router, Route} from 'react-router-dom';\nimport {IntlProvider} from 'react-intl';\nimport './index.css';\nimport 'semantic-ui-css/semantic.min.css';\nimport 'canvas-toBlob';\n\naddLocaleData([...locale_en, ...locale_pl]);\n\nconst messages = {\n pl: messages_pl,\n};\nconst language = navigator.language && navigator.language.split(/[-_]/)[0];\n\nconst browser = detect();\n\nif (browser && browser.name === 'ie') {\n ReactDOM.render(\n

\n Topola Genealogy Viewer does not support Internet Explorer. Please try a\n different browser.\n

,\n document.querySelector('#root'),\n );\n} else {\n ReactDOM.render(\n \n \n \n \n ,\n document.querySelector('#root'),\n );\n}\n"],"sourceRoot":""} \ No newline at end of file