From 05f70d406b8ec9f6b8b4a76dd6268cb8584d7f3f Mon Sep 17 00:00:00 2001 From: Przemek Wiech Date: Sun, 3 May 2020 12:40:44 +0200 Subject: [PATCH] Updates --- asset-manifest.json | 8 ++++---- index.html | 2 +- ... precache-manifest.a7d25a8b479e4e8de8a626c344b67b98.js | 8 ++++---- service-worker.js | 2 +- static/js/main.0c73a86c.chunk.js | 2 -- static/js/main.0c73a86c.chunk.js.map | 1 - static/js/main.20beea3f.chunk.js | 2 ++ static/js/main.20beea3f.chunk.js.map | 1 + 8 files changed, 13 insertions(+), 13 deletions(-) rename precache-manifest.6ba9221b4f66212cd78be0b52426ce2c.js => precache-manifest.a7d25a8b479e4e8de8a626c344b67b98.js (93%) delete mode 100644 static/js/main.0c73a86c.chunk.js delete mode 100644 static/js/main.0c73a86c.chunk.js.map create mode 100644 static/js/main.20beea3f.chunk.js create mode 100644 static/js/main.20beea3f.chunk.js.map diff --git a/asset-manifest.json b/asset-manifest.json index ea40e36..1fb12e0 100644 --- a/asset-manifest.json +++ b/asset-manifest.json @@ -1,8 +1,8 @@ { "files": { "main.css": "./static/css/main.e470b262.chunk.css", - "main.js": "./static/js/main.0c73a86c.chunk.js", - "main.js.map": "./static/js/main.0c73a86c.chunk.js.map", + "main.js": "./static/js/main.20beea3f.chunk.js", + "main.js.map": "./static/js/main.20beea3f.chunk.js.map", "runtime-main.js": "./static/js/runtime-main.37653c46.js", "runtime-main.js.map": "./static/js/runtime-main.37653c46.js.map", "static/css/2.8e9053bd.chunk.css": "./static/css/2.8e9053bd.chunk.css", @@ -11,7 +11,7 @@ "static/js/3.45a083e8.chunk.js": "./static/js/3.45a083e8.chunk.js", "static/js/3.45a083e8.chunk.js.map": "./static/js/3.45a083e8.chunk.js.map", "index.html": "./index.html", - "precache-manifest.6ba9221b4f66212cd78be0b52426ce2c.js": "./precache-manifest.6ba9221b4f66212cd78be0b52426ce2c.js", + "precache-manifest.a7d25a8b479e4e8de8a626c344b67b98.js": "./precache-manifest.a7d25a8b479e4e8de8a626c344b67b98.js", "service-worker.js": "./service-worker.js", "static/css/2.8e9053bd.chunk.css.map": "./static/css/2.8e9053bd.chunk.css.map", "static/css/main.e470b262.chunk.css.map": "./static/css/main.e470b262.chunk.css.map", @@ -26,6 +26,6 @@ "static/css/2.8e9053bd.chunk.css", "static/js/2.1d88b484.chunk.js", "static/css/main.e470b262.chunk.css", - "static/js/main.0c73a86c.chunk.js" + "static/js/main.20beea3f.chunk.js" ] } \ No newline at end of file diff --git a/index.html b/index.html index e12086d..cb1e9db 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.6ba9221b4f66212cd78be0b52426ce2c.js b/precache-manifest.a7d25a8b479e4e8de8a626c344b67b98.js similarity index 93% rename from precache-manifest.6ba9221b4f66212cd78be0b52426ce2c.js rename to precache-manifest.a7d25a8b479e4e8de8a626c344b67b98.js index 0294925..7a250fe 100644 --- a/precache-manifest.6ba9221b4f66212cd78be0b52426ce2c.js +++ b/precache-manifest.a7d25a8b479e4e8de8a626c344b67b98.js @@ -1,6 +1,6 @@ self.__precacheManifest = (self.__precacheManifest || []).concat([ { - "revision": "fe1e072fba0d47037894e405cb55ad2f", + "revision": "25c33e1f85fa4fe229a11fa71a9e8c4a", "url": "./index.html" }, { @@ -8,7 +8,7 @@ self.__precacheManifest = (self.__precacheManifest || []).concat([ "url": "./static/css/2.8e9053bd.chunk.css" }, { - "revision": "f41eb66d680517d4bd34", + "revision": "b846261a2dbbdb9bdac1", "url": "./static/css/main.e470b262.chunk.css" }, { @@ -28,8 +28,8 @@ self.__precacheManifest = (self.__precacheManifest || []).concat([ "url": "./static/js/3.45a083e8.chunk.js.LICENSE.txt" }, { - "revision": "f41eb66d680517d4bd34", - "url": "./static/js/main.0c73a86c.chunk.js" + "revision": "b846261a2dbbdb9bdac1", + "url": "./static/js/main.20beea3f.chunk.js" }, { "revision": "60b8ba4879f051fe8653", diff --git a/service-worker.js b/service-worker.js index 0da83e2..34dee79 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.6ba9221b4f66212cd78be0b52426ce2c.js" + "./precache-manifest.a7d25a8b479e4e8de8a626c344b67b98.js" ); self.addEventListener('message', (event) => { diff --git a/static/js/main.0c73a86c.chunk.js b/static/js/main.0c73a86c.chunk.js deleted file mode 100644 index 29143a0..0000000 --- a/static/js/main.0c73a86c.chunk.js +++ /dev/null @@ -1,2 +0,0 @@ -(this["webpackJsonptopola-viewer"]=this["webpackJsonptopola-viewer"]||[]).push([[0],{196:function(e,t,n){e.exports=n.p+"static/media/topola.060eef13.jpg"},287:function(e){e.exports=JSON.parse('{"menu.open":"Otw\xf3rz","menu.open_file":"Otw\xf3rz plik","menu.load_from_url":"Otw\xf3rz URL","menu.select_wikitree_id":"Wybierz WikiTree ID","menu.print":"Drukuj","menu.download":"Pobierz","menu.pdf_file":"Plik PDF","menu.png_file":"Plik PNG","menu.svg_file":"Plik SVG","menu.download_pdf":"Pobierz PDF","menu.download_png":"Pobierz PNG","menu.download_svg":"Pobierz 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":"Projekt na stronie GitHub","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 PLIK lub OTW\xd3RZ URL, 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","select_wikitree_id.title":"Podaj WikiTree ID","select_wikitree_id.comment":"Wpisz identyfikator profilu {wikiTreeLink}. Przyk\u0142ady: {example1}, {example2}","select_wikitree_id.cancel":"Anuluj","select_wikitree_id.load":"Otw\xf3rz","gedcom.BAPM":"Chrzest","gedcom.BIRT":"Narodziny","gedcom.BURI":"Pogrzeb","gedcom.CENS":"Spis ludno\u015bci","gedcom.CHR":"Chrzest","gedcom.DEAT":"\u015amier\u0107","gedcom.DSCR":"Opis","gedcom.EMAIL":"E-mail","gedcom.EVEN":"Wydarzenie","gedcom.OCCU":"Zaw\xf3d","gedcom.RIN":"ID","gedcom.TITL":"Tytu\u0142","gedcom.WWW":"Strona WWW","gedcom._UPD":"Ostatnia aktualizacja","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","error.failed_wikitree_load_more":"B\u0142\u0105d podczas pobierania danych z WikiTree. {error}","wikitree.private":"Prywatne"}')},288:function(e,t){},331:function(e,t,n){e.exports=n(585)},343:function(e,t){},349:function(e,t){},410:function(e,t){},582:function(e,t,n){},585:function(e,t,n){"use strict";n.r(t);var a=n(34),r=n(285),i=n(286),o=n(0),s=n(76),c=n(287),l=n(8),u=n(41),d=n(40),m=n(48),f=n(10),h=n.n(f),p=n(18),g=n(28),v=n(29),w=n(33);function E(e,t){window.gtag("event",e,t)}var k,b=n(142),y=n(72),O=n(49),M=n(103),D=n(73),T=n(615),I=n(195),S=n(95),j=(n(74),n(35));function x(e){var t=Object(b.a)("#svgContainer").node(),n=y.c.transform.k,a=Object(M.a)([0,(t.clientWidth-e[0]*n)/2]),r=Object(M.a)([0,(t.clientHeight-e[1]*n)/2]);Object(b.a)("#chartSvg").attr("width",e[0]*n).attr("height",e[1]*n).attr("transform","translate(".concat(a,", ").concat(r,")")),Object(b.a)("#chart").attr("transform","scale(".concat(n,")")),t.scrollLeft=-y.c.transform.x,t.scrollTop=-y.c.transform.y}function _(){var e=Object(b.a)("#svgContainer").node(),t=e.scrollLeft+e.clientWidth/2,n=e.scrollTop+e.clientHeight/2,a=Object(S.b)(e).k;Object(b.a)(e).call(Object(S.a)().translateTo,t/a,n/a)}function R(e){var t=new FileReader;return t.readAsDataURL(e),new Promise((function(e,n){t.onload=function(t){return e(t.target.result)}}))}function L(e){return N.apply(this,arguments)}function N(){return(N=Object(p.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,R(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 C(e){return z.apply(this,arguments)}function z(){return(z=Object(p.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(L));case 3:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function W(e){var t=new Image;return t.src=URL.createObjectURL(e),new Promise((function(e,n){t.addEventListener("load",(function(){return e(t)}))}))}function P(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 A(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"}(k||(k={}));var F=function(e){Object(u.a)(a,e);var t=Object(d.a)(a);function a(){var e;Object(g.a)(this,a);for(var n=arguments.length,r=new Array(n),i=0;i0&&void 0!==arguments[0]?arguments[0]:{initialRender:!1};if(t.initialRender||!this.animating){if(t.initialRender||!this.props.freezeAnimation){t.initialRender?(Object(b.a)("#chart").node().innerHTML="",this.chart=Object(j.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=Object(b.a)("#chartSvg"),r=Object(b.a)("#svgContainer").node(),i=Object(S.b)(r).k,o=Object(D.a)([1,i,r.clientWidth/n.size[0],r.clientHeight/n.size[1]]),s=[Object(M.a)([.1,o]),2];this.zoomBehavior=Object(S.a)().scaleExtent(s).translateExtent([[0,0],n.size]).on("zoom",(function(){return x(n.size)})),Object(b.a)(r).on("scroll",_).call(this.zoomBehavior);var c=function(e){return function(){var t=Object(O.a)(r.scrollTop,e);return function(e){r.scrollTop=t(e)}}},l=function(e){return function(){var t=Object(O.a)(r.scrollLeft,e);return function(e){r.scrollLeft=t(e)}}},u=r.clientWidth/2-n.origin[0]*i,d=r.clientHeight/2-n.origin[1]*i,m=Object(M.a)([0,(r.clientWidth-n.size[0]*i)/2]),f=Object(M.a)([0,(r.clientHeight-n.size[1]*i)/2]),h=a.transition().delay(200).duration(500),p=t.initialRender?a:h;p.attr("transform","translate(".concat(m,", ").concat(f,")")).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)).tween("scrollTop",c(-d)),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"},o.createElement(T.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")),o.createElement("svg",{id:"chartSvg"},o.createElement("g",{id:"chart"})))}},{key:"getStrippedSvg",value:function(){var e=document.getElementById("chartSvg").cloneNode(!0);e.removeAttribute("transform");var t=Object(b.a)("#svgContainer").node(),n=Object(S.b)(t).k;return e.setAttribute("width",String(Number(e.getAttribute("width"))/n)),e.setAttribute("height",String(Number(e.getAttribute("height"))/n)),e.querySelector("#chart").removeAttribute("transform"),e}},{key:"getSvgContents",value:function(){return(new XMLSerializer).serializeToString(this.getStrippedSvg())}},{key:"getSvgContentsWithInlinedImages",value:function(){var e=Object(p.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,C(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(p.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(I.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(p.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=P,e.next=7,W(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(p.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,A(t,"image/png");case 5:n=e.sent,Object(I.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(p.a)(h.a.mark((function e(){var t,a,r,i;return h.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,n.e(3).then(n.t.bind(null,617,7));case 2:return t=e.sent,a=t.default,e.next=6,this.drawOnCanvas();case 6:r=e.sent,(i=new a({orientation:r.width>r.height?"l":"p",unit:"pt",format:[r.width,r.height]})).addImage(r,"PNG",0,0,r.width,r.height,"NONE"),i.save("topola.pdf");case 10:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()}]),a}(o.PureComponent);F.contextTypes={intl:l.d};var U=n(292),G=n.n(U),H=n(293),B=n.n(H),V=n(191);function K(e){return e.substring(1,e.length-1)}function J(e){var t=new Map;return e.indis.forEach((function(e){t.set(e.id,e)})),t}function q(e){var t=new Map;return e.fams.forEach((function(e){t.set(e.id,e)})),t}function Z(e){var t=e.find((function(e){return"HEAD"===e.tag})),n={},a={},r={};return e.forEach((function(e){"INDI"===e.tag?n[K(e.pointer)]=e:"FAM"===e.tag?a[K(e.pointer)]=e:e.pointer&&(r[K(e.pointer)]=e)})),{head:t,indis:n,fams:a,other:r}}function Y(e,t){return et?1:0}function X(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.day&&a.day&&n.day!==a.day)?n.month-a.month:0:0}function $(e){var t=function(e){var t=J(e);return function(e,n){var a=t.get(e),r=t.get(n);return X(a&&a.birth,r&&r.birth)||Y(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 Q(e){var t=function(e){var t=q(e);return function(e,n){var a=t.get(e),r=t.get(n);return X(a&&a.marriage,r&&r.marriage)||Y(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 ee(e){return Q($(e))}var te=[".jpg",".png",".gif"];function ne(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 te.some((function(e){return t.endsWith(e)}))}(e.url)&&n.push(e)})),Object.assign({},e,{images:n})}function ae(e,t){var n=e.indis.map((function(e){return ne(e,t)}));return Object.assign({},e,{indis:n})}function re(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 ie=new Map([["abt","about"],["cal","calculated"],["est","estimated"]]);function oe(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:ie.get(o)||o}),new Intl.DateTimeFormat(t.locale,s).format(i)].join(" ")}function se(e,t){return e?e.date?oe(e.date,t):e.dateRange?function(e,t){var n=e.from,a=e.to,r=n&&oe(n,t),i=a&&oe(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}):""}(e.dateRange,t):"":""}var ce=["BIRT","BAPM","CHR","DEAT","BURI","EVEN","CENS"],le=["NAME","SEX","FAMC","FAMS","NOTE","SOUR"],ue=new Map([["BAPM","Baptism"],["BIRT","Birth"],["BURI","Burial"],["CENS","Census"],["CHR","Christening"],["DEAT","Death"],["EMAIL","E-mail"],["EVEN","Event"],["OCCU","Occupation"],["TITL","Title"],["WWW","WWW"]]);function de(e){return o.createElement(l.a,{id:"gedcom.".concat(e),defaultMessage:ue.get(e)||e})}function me(e){return o.createElement(o.Fragment,null,e.map((function(e,t){return o.createElement("div",{key:t},o.createElement(B.a,{properties:{target:"_blank"}},e),o.createElement("br",null))})))}function fe(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 he(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(function(e,t){return se(Object(j.getDate)(e),t)}(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)(fe(i))),e.tree.filter((function(e){return"NOTE"===e.tag})).forEach((function(e){return fe(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"},de(e.tag)),o.createElement("span",null,me(n))):null}function pe(e){return me(fe(e).map((function(e,t){return o.createElement("i",{key:t},e)})))}function ge(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 ve(e,t,n){return G()(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 we(e){return e.tree.length>0||e.data&&!e.data.startsWith("@")}function Ee(e){return e.filter((function(e){return!le.includes(e.tag)&&!ce.includes(e.tag)})).filter(we).map((function(e){return function(e){var t=[];return e.data&&t.push.apply(t,Object(a.a)(fe(e))),e.tree.filter((function(e){return"NOTE"===e.tag})).forEach((function(e){return fe(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"},de(e.tag)),o.createElement("span",null,me(t))):null}(e)})).filter((function(e){return null!==e})).map((function(e,t){return o.createElement("div",{className:"ui segment",key:t},e)}))}var ke=function(e){Object(u.a)(n,e);var t=Object(d.a)(n);function n(){return Object(g.a)(this,n),t.apply(this,arguments)}return Object(v.a)(n,[{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[K(e.data)];if(n)return n}return e}(t,e.props.gedcom)})).filter(we);return o.createElement("div",{className:"ui segments",id:"details"},ve(t,["NAME"],ge),ve(t,ce,(function(t){return he(t,e.context.intl)})),Ee(n),ve(n,["NOTE"],pe))}}]),n}(o.Component);function be(e,t,n){return{id:t&&e.indis.some((function(e){return e.id===t}))?t:e.indis[0].id,generation:n||0}}function ye(e,t,n){var a=function(e,t){var n=Object(V.parse)(e),a=Object(j.gedcomEntriesToJson)(n);if(!a||!a.indis||!a.indis.length||!a.fams||!a.fams.length)throw new Error("Failed to read GEDCOM file");return{chartData:ae(ee(a),t),gedcom:Z(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 Oe(e,t){return Me.apply(this,arguments)}function Me(){return(Me=Object(p.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",ye(o,t));case 19:case"end":return e.stop()}}),e,null,[[0,6]])})))).apply(this,arguments)}function De(e,t,n){return Te.apply(this,arguments)}function Te(){return(Te=Object(p.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",ye(n,t,a));case 12:case"end":return e.stop()}}),e,null,[[0,6]])})))).apply(this,arguments)}ke.contextTypes={intl:l.d};var Ie=n(196),Se=n.n(Ie),je=n(605),xe=n(611),_e=n(318),Re=n(598);function Le(e){return o.createElement(Re.a,{to:{pathname:"/view",search:w.stringify({url:e.url})}},e.text)}function Ne(){var e=o.createElement(o.Fragment,null,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 OPEN FILE or LOAD FROM URL 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(Le,{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(Le,{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(Le,{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-04-29 23:35:43 +0200".slice(0,16)," (",o.createElement("a",{href:"https://github.com/PeWu/topola-viewer/commit/".concat("506d6bf")},"506d6bf"),")"));return o.createElement("div",{id:"content"},o.createElement("div",{className:"backgroundImage"}),o.createElement(je.a,{className:"intro"},o.createElement(T.a,{as:je.a.Content,minWidth:768},o.createElement(je.a.Header,null,o.createElement(l.a,{id:"intro.title",defaultMessage:"Topola Genealogy Viewer"}))),o.createElement(je.a.Content,null,o.createElement(T.a,{as:xe.a,minWidth:768},o.createElement(xe.a.Row,null,o.createElement(xe.a.Column,{width:5},o.createElement(_e.a,{src:Se.a,alt:"Topola logo"})),o.createElement(xe.a.Column,{width:11},e))),o.createElement(T.a,{maxWidth:767},o.createElement(_e.a,{src:Se.a,alt:"Topola logo",centered:!0,size:"tiny",className:"blockImage"}),e))))}var Ce=n(606),ze=n(616),We=n(601),Pe=n(197),Ae=n.n(Pe);function Fe(e){try{return sessionStorage.getItem(e)}catch(t){console.warn("Failed to load data from session storage: "+t)}return null}function Ue(e,t){try{sessionStorage.setItem(e,t)}catch(n){console.warn("Failed to store data in session storage: "+n)}}function Ge(e,t){return He.apply(this,arguments)}function He(){return(He=Object(p.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://api.wikitree.com/api.php":"https://api.wikitree.com/api.php",e.next=6,window.fetch(i,{method:"POST",body:a,credentials:n?void 0:"include"});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 Be(e,t){return Ve.apply(this,arguments)}function Ve(){return(Ve=Object(p.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=Fe(a))){e.next=4;break}return e.abrupt("return",JSON.parse(r));case 4:return e.next=6,Ge({action:"getAncestors",key:t,fields:"*"},n);case 6:return i=e.sent,o=i[0].ancestors,Ue(a,JSON.stringify(o)),e.abrupt("return",o);case 10:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function Ke(e,t){return Je.apply(this,arguments)}function Je(){return(Je=Object(p.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=Fe("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,Ge({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){Ue("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 qe(e){return Ze.apply(this,arguments)}function Ze(){return(Ze=Object(p.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,Ge({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 Ye(){return Ae.a.get("wikidb_wtb_UserName")}function Xe(e,t,n){return $e.apply(this,arguments)}function $e(){return($e=Object(p.a)(h.a.mark((function e(t,n,r){var i,o,s,c,l,u,d,f,p,g,v,w,E,k,b,y,O,M,D,T,I,S,j,x,_;return h.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if((i="apps.wikitree.com"!==window.location.hostname)||Ye()||!r){e.next=6;break}return e.next=4,qe(r);case 4:"Success"===(o=e.sent).result&&(sessionStorage.clear(),Ae.a.set("wikidb_wtb_UserName",o.username));case 6:return s=[],e.next=9,Ke([t],i);case 9:if((c=e.sent)[0].Name){e.next=12;break}throw new Error("WikiTree profile ".concat(t," is not accessible. Try logging in."));case 12:return l=Object.values(c[0].Spouses).map((function(e){return e.Name})),e.next=15,Promise.all([t].concat(l).map((function(e){return Be(e,i)})));case 15:return u=e.sent,d=u.flat().map((function(e){return e.Name})).filter((function(e){return!!e})),e.next=19,Ke(d,i);case 19:f=e.sent,p=new Map,g=new Map,u.forEach((function(e,t){var n=1e3*t;e.forEach((function(e){e.Id<0&&(e.Id-=n,e.Name="".concat("~Private").concat(e.Id)),e.Father<0&&(e.Father-=n,p.set(e.Id,e.Father)),e.Mother<0&&(e.Mother-=n,g.set(e.Id,e.Mother))}))})),f.forEach((function(e){var t=p.get(e.Id);t&&(e.Father=t);var n=g.get(e.Id);n&&(e.Mother=n)})),s.push.apply(s,Object(a.a)(f)),v=u.flat().filter((function(e){return e.Id<0})),s.push.apply(s,Object(a.a)(v)),w=5,E=[t],k=0;case 30:if(!(E.length>0&&k<=w)){e.next=41;break}return e.next=33,Ke(E,i);case 33:b=e.sent,s.push.apply(s,Object(a.a)(b)),y=b.flatMap((function(e){return Object.values(e.Spouses)})),s.push.apply(s,Object(a.a)(y)),E=b.flatMap((function(e){return Object.values(e.Children).map((function(e){return e.Name}))})),k++,e.next=30;break;case 41:return O=new Map,M=new Map,D=new Map,T=new Map,s.forEach((function(e){if(T.set(e.Id,e.Name),e.Mother||e.Father){var t=Qe(e.Mother,e.Father);rt(O,e.Mother).add(t),rt(O,e.Father).add(t),rt(M,t).add(e.Id),D.set(t,{wife:e.Mother||void 0,husband:e.Father||void 0})}})),I=[],S=new Set,s.forEach((function(e){if(!S.has(e.Id)){S.add(e.Id);var t=et(e,n);e.Spouses&&Object.values(e.Spouses).forEach((function(t){var n=Qe(e.Id,t.Id);rt(O,e.Id).add(n),rt(O,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};D.set(n,a)})),t.fams=Array.from(rt(O,e.Id)),I.push(t)}})),j=Array.from(D.entries()).map((function(e){var t=Object(m.a)(e,2),n=t[0],a=t[1],r={id:n},i=a.wife&&T.get(a.wife);i&&(r.wife=i);var o=a.husband&&T.get(a.husband);if(o&&(r.husb=o),r.children=Array.from(rt(M,n)).map((function(e){return T.get(e)})),a.spouse&&(a.spouse.marriage_date&&"0000-00-00"!==a.spouse.marriage_date||a.spouse.marriage_location)){var s=tt(a.spouse.marriage_date);r.marriage=Object.assign({},s,{place:a.spouse.marriage_location})}return r})),x=ee({indis:I,fams:j}),_=at(I),e.abrupt("return",{chartData:x,gedcom:_});case 53:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function Qe(e,t){return t>e?"".concat(e,"_").concat(t):"".concat(t,"_").concat(e)}function et(e,t){var n={id:e.Name};if(e.Name.startsWith("~Private")&&(n.hideId=!0,n.firstName=t.formatMessage({id:"wikitree.private",defaultMessage:"Private"})),e.FirstName&&"Unknown"!==e.FirstName&&(n.firstName=e.FirstName),"Unknown"!==e.LastNameAtBirth&&(n.lastName=e.LastNameAtBirth),(e.Mother||e.Father)&&(n.famc=Qe(e.Mother,e.Father)),"Male"===e.Gender?n.sex="M":"Female"===e.Gender&&(n.sex="F"),e.BirthDate&&"0000-00-00"!==e.BirthDate||e.BirthLocation||"unknown"!==e.BirthDateDecade){var a=tt(e.BirthDate,e.DataStatus&&e.DataStatus.BirthDate)||nt(e.BirthDateDecade);n.birth=Object.assign({},a,{place:e.BirthLocation})}if(e.DeathDate&&"0000-00-00"!==e.DeathDate||e.DeathLocation||"unknown"!==e.DeathDateDecade){var r=tt(e.DeathDate,e.DataStatus&&e.DataStatus.DeathDate)||nt(e.DeathDateDecade);n.death=Object.assign({},r,{place:e.DeathLocation})}return e.PhotoData&&(n.images=[{url:"https://www.wikitree.com".concat(e.PhotoData.url)}]),n}function tt(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 nt(e){return"unknown"!==e?{date:{text:e}}:void 0}function at(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:[]}]},e.id.startsWith("~")||t[e.id].tree.push({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 rt(e,t){var n=e.get(t);if(n)return n;var a=new Set;return e.set(t,a),a}var it=n(613),ot=n(614),st=n(609),ct=n(297),lt=n.n(ct),ut=n(198),dt=n.n(ut),mt=n(298),ft=n.n(mt),ht=n(299),pt=n.n(ht);function gt(e){return e.toLocaleLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/\u0142/g,"l")}function vt(e,t){return e.score!==t.score?t.score-e.score:ft()(e.ref,t.ref)}var wt=function(){function e(t){Object(g.a)(this,e),this.index=void 0,this.indiMap=void 0,this.famMap=void 0,this.indiMap=J(t),this.famMap=q(t)}return Object(v.a)(e,[{key:"initialize",value:function(){var e=this;this.index=pt()((function(){var t=this;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.indiMap.forEach((function(n){var a=[n.firstName,n.lastName].join(" "),r=function(e,t,n){return(e.fams||[]).map((function(e){return n.get(e)})).map((function(e){return e&&e.husb})).map((function(e){return e&&t.get(e)})).map((function(e){return e&&e.lastName})).join(" ")}(n,e.indiMap,e.famMap);t.add({id:n.id,name:a,normalizedName:gt(a),spouseLastName:r,normalizedSpouseLastName:gt(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(vt).slice(0,8).map((function(e){return{id:e.ref,indi:t.indiMap.get(e.ref)}}))}}]),e}();function Et(e){var t=[e.indi.firstName,e.indi.lastName].join(" ").trim();return e.id.length>8?t:o.createElement(o.Fragment,null,t," ",o.createElement("i",null,"(",e.id,")"))}function kt(e,t){var n=se(e.birth,t),a=se(e.death,t);return a?"".concat(n," \u2013 ").concat(a):n}var bt,yt,Ot=n(603),Mt=n(612),Dt=n(77),Tt=n(602),It=n(600),St=n(587),jt=n(607),xt=n(604),_t=n(608),Rt=n(78),Lt=n.n(Rt);function Nt(e){return new Promise((function(t,n){var a=new FileReader;a.onload=function(e){t(e.target.result)},a.readAsText(e)}))}function Ct(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"}(bt||(bt={})),function(e){e[e.LARGE=0]="LARGE",e[e.SMALL=1]="SMALL"}(yt||(yt={}));var zt,Wt=function(e){Object(u.a)(n,e);var t=Object(d.a)(n);function n(){var e;Object(g.a)(this,n);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 freezeAnimation?: 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?: 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 = select('#svgContainer') as Selection;\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 // Freeze changing selection after initial rendering.\n if (!args.initialRender && this.props.freezeAnimation) {\n return;\n }\n\n if (args.initialRender) {\n (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 = select('#chartSvg');\n const parent = select('#svgContainer').node() as Element;\n\n const scale = zoomTransform(parent).k;\n const zoomOutFactor = min([\n 1,\n scale,\n parent.clientWidth / chartInfo.size[0],\n parent.clientHeight / chartInfo.size[1],\n ])!;\n const extent: [number, number] = [max([0.1, zoomOutFactor])!, 2];\n\n this.zoomBehavior = zoom()\n .scaleExtent(extent)\n .translateExtent([[0, 0], chartInfo.size])\n .on('zoom', () => zoomed(chartInfo.size));\n select(parent)\n .on('scroll', scrolled)\n .call(this.zoomBehavior);\n\n const scrollTopTween = (scrollTop: number) => {\n return () => {\n const i = 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 = 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 = max([\n 0,\n (parent.clientWidth - chartInfo.size[0] * scale) / 2,\n ]);\n const offsetY = 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 \n \n this.zoom(1 / ZOOM_FACTOR)}\n >\n −\n \n \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 const parent = select('#svgContainer').node() as Element;\n const scale = 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 // Lazy load jspdf.\n const {default: jspdf} = await import('jspdf');\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\nexport function idToIndiMap(data: JsonGedcomData): Map {\n const map = new Map();\n data.indis.forEach((indi) => {\n map.set(indi.id, indi);\n });\n return map;\n}\n\nexport function idToFamMap(data: JsonGedcomData): Map {\n const map = new Map();\n data.fams.forEach((fam) => {\n map.set(fam.id, fam);\n });\n return map;\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 indiMap = idToIndiMap(gedcom);\n\n return (indiId1: string, indiId2: string) => {\n const indi1: JsonIndi | undefined = indiMap.get(indiId1);\n const indi2: JsonIndi | undefined = indiMap.get(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 famMap = idToFamMap(gedcom);\n\n return (famId1: string, famId2: string) => {\n const fam1: JsonFam | undefined = famMap.get(famId1);\n const fam2: JsonFam | undefined = famMap.get(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, DateOrRange} 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 DateOrRange object. */\nexport function formatDateOrRange(\n dateOrRange: DateOrRange | undefined,\n intl: InjectedIntl,\n): string {\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\n/** Formats a date given in GEDCOM format. */\nexport function translateDate(gedcomDate: string, intl: InjectedIntl): string {\n return formatDateOrRange(getDate(gedcomDate), intl);\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', 'CENS'];\nconst EXCLUDED_TAGS = ['NAME', 'SEX', 'FAMC', 'FAMS', 'NOTE', 'SOUR'];\nconst TAG_DESCRIPTIONS = new Map([\n ['BAPM', 'Baptism'],\n ['BIRT', 'Birth'],\n ['BURI', 'Burial'],\n ['CENS', 'Census'],\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, Responsive} 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 const contents = (\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 version: {formatBuildDate(process.env.REACT_APP_GIT_TIME!)} (\n \n {process.env.REACT_APP_GIT_SHA}\n \n )\n

\n \n );\n\n return (\n
\n
\n \n \n \n \n \n \n \n \n \n \n \"Topola\n \n {contents}\n \n \n \n \n {contents}\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';\nimport {InjectedIntl} from 'react-intl';\n\n/** Prefix for IDs of private individuals. */\nexport const PRIVATE_ID_PREFIX = '~Private';\n\n/**\n * Cookie where the logged in user name is stored. This cookie is shared\n * between apps hosted on apps.wikitree.com.\n */\nconst USER_NAME_COOKIE = 'wikidb_wtb_UserName';\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 GetRelativesRequest {\n action: 'getRelatives';\n keys: string;\n getChildren?: true;\n getSpouses?: true;\n}\n\n/** WikiTree API clientLogin request. */\ninterface ClientLoginRequest {\n action: 'clientLogin';\n authcode: string;\n}\n\n/** WikiTree API clientLogin response. */\ninterface ClientLoginResponse {\n result: string;\n username: string;\n}\n\ntype WikiTreeRequest =\n | GetAncestorsRequest\n | GetRelativesRequest\n | ClientLoginRequest;\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 BirthDateDecade: string;\n DeathDateDecade: string;\n marriage_location: string;\n marriage_date: string;\n DataStatus?: {\n BirthDate: string;\n DeathDate: string;\n };\n PhotoData?: {\n path: string;\n url: 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://api.wikitree.com/api.php'\n : 'https://api.wikitree.com/api.php';\n const response = await window.fetch(apiUrl, {\n method: 'POST',\n body: requestData,\n credentials: handleCors ? undefined : 'include',\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(\n key: string,\n handleCors: boolean,\n): Promise {\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(\n keys: string[],\n handleCors: boolean,\n): Promise {\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(\n authcode: string,\n): Promise {\n const response = await wikiTreeGet(\n {\n action: 'clientLogin',\n authcode,\n },\n false,\n );\n return response.clientLogin;\n}\n\n/**\n * Returnes the logged in user name or undefined if not logged in.\n *\n * This is not an authoritative answer. The result of this function relies on\n * the cookies set on the apps.wikitree.com domain under which this application\n * is hosted. The authoritative source of login information is in cookies set on\n * the api.wikitree.com domain.\n */\nexport function getLoggedInUserName(): string | undefined {\n return Cookies.get(USER_NAME_COOKIE);\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 intl: InjectedIntl,\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 && !getLoggedInUserName() && authcode) {\n const loginResult = await clientLogin(authcode);\n if (loginResult.result === 'Success') {\n sessionStorage.clear();\n Cookies.set(USER_NAME_COOKIE, loginResult.username);\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\n // Map from person id to father id if the father profile is private.\n const privateFathers: Map = new Map();\n // Map from person id to mother id if the mother profile is private.\n const privateMothers: Map = new Map();\n\n // Andujst private individual ids so that there are no collisions in the case\n // that ancestors were collected for more than one person.\n ancestors.forEach((ancestorList, index) => {\n const offset = 1000 * index;\n // Adjust ids by offset.\n ancestorList.forEach((person) => {\n if (person.Id < 0) {\n person.Id -= offset;\n person.Name = `${PRIVATE_ID_PREFIX}${person.Id}`;\n }\n if (person.Father < 0) {\n person.Father -= offset;\n privateFathers.set(person.Id, person.Father);\n }\n if (person.Mother < 0) {\n person.Mother -= offset;\n privateMothers.set(person.Id, person.Mother);\n }\n });\n });\n\n // Set the Father and Mother fields again because getRelatives doesn't return\n // private parents.\n ancestorDetails.forEach((person) => {\n const privateFather = privateFathers.get(person.Id);\n if (privateFather) {\n person.Father = privateFather;\n }\n const privateMother = privateMothers.get(person.Id);\n if (privateMother) {\n person.Mother = privateMother;\n }\n });\n everyone.push(...ancestorDetails);\n\n // Collect private individuals.\n const privateAncestors = ancestors.flat().filter((person) => person.Id < 0);\n everyone.push(...privateAncestors);\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, intl);\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, intl: InjectedIntl): JsonIndi {\n const indi: JsonIndi = {\n id: person.Name,\n };\n if (person.Name.startsWith(PRIVATE_ID_PREFIX)) {\n indi.hideId = true;\n indi.firstName = intl.formatMessage({\n id: 'wikitree.private',\n defaultMessage: 'Private',\n });\n }\n if (person.FirstName && 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 person.BirthDateDecade !== 'unknown'\n ) {\n const parsedDate = parseDate(\n person.BirthDate,\n person.DataStatus && person.DataStatus.BirthDate,\n );\n const date = parsedDate || parseDecade(person.BirthDateDecade);\n indi.birth = Object.assign({}, date, {place: person.BirthLocation});\n }\n if (\n (person.DeathDate && person.DeathDate !== '0000-00-00') ||\n person.DeathLocation ||\n person.DeathDateDecade !== 'unknown'\n ) {\n const parsedDate = parseDate(\n person.DeathDate,\n person.DataStatus && person.DataStatus.DeathDate,\n );\n const date = parsedDate || parseDecade(person.DeathDateDecade);\n indi.death = Object.assign({}, date, {place: person.DeathLocation});\n }\n if (person.PhotoData) {\n indi.images = [{url: `https://www.wikitree.com${person.PhotoData.url}`}];\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\nfunction parseDecade(decade: string): DateOrRange | undefined {\n return decade !== 'unknown' ? {date: {text: decade}} : undefined;\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 };\n if (!indi.id.startsWith('~')) {\n gedcomIndis[indi.id].tree.push({\n level: 1,\n pointer: '',\n tag: 'WWW',\n data: `https://www.wikitree.com/wiki/${escapedId}`,\n tree: [],\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 {idToIndiMap, idToFamMap} from './gedcom_util';\nimport {JsonIndi, JsonFam, JsonGedcomData} from 'topola';\n\nconst MAX_RESULTS = 8;\n\nexport interface SearchResult {\n id: string;\n indi: JsonIndi;\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(\n indi: JsonIndi,\n indiMap: Map,\n famMap: Map,\n): string {\n return (indi.fams || [])\n .map((famId) => famMap.get(famId))\n .map((fam) => fam && fam.husb)\n .map((husbId) => husbId && indiMap.get(husbId))\n .map((husband) => husband && husband.lastName)\n .join(' ');\n}\n\nclass LunrSearchIndex implements SearchIndex {\n private index: lunr.Index | undefined;\n private indiMap: Map;\n private famMap: Map;\n\n constructor(data: JsonGedcomData) {\n this.indiMap = idToIndiMap(data);\n this.famMap = idToFamMap(data);\n }\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 self.indiMap.forEach((indi) => {\n const name = [indi.firstName, indi.lastName].join(' ');\n const spouseLastName = getHusbandLastName(\n indi,\n self.indiMap,\n self.famMap,\n );\n this.add({\n id: indi.id,\n name,\n normalizedName: normalize(name),\n spouseLastName,\n normalizedSpouseLastName: normalize(spouseLastName),\n });\n });\n });\n }\n\n public search(input: string): SearchResult[] {\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.indiMap.get(result.ref)!}));\n }\n}\n\n/** Builds a search index from data. */\nexport function buildSearchIndex(data: JsonGedcomData): SearchIndex {\n const index = new LunrSearchIndex(data);\n index.initialize();\n return index;\n}\n","import * as React from 'react';\nimport {InjectedIntl} from 'react-intl';\nimport {SearchResult} from './search_index';\nimport {formatDateOrRange} from './date_util';\nimport {JsonIndi} from 'topola';\n\nfunction getNameLine(result: SearchResult) {\n const name = [result.indi.firstName, result.indi.lastName].join(' ').trim();\n if (result.id.length > 8) {\n return name;\n }\n return (\n <>\n {name} ({result.id})\n \n );\n}\n\nfunction getDescriptionLine(indi: JsonIndi, intl: InjectedIntl) {\n const birthDate = formatDateOrRange(indi.birth, intl);\n const deathDate = formatDateOrRange(indi.death, 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 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 {getLoggedInUserName} from './wikitree';\nimport {IndiInfo, JsonGedcomData} 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 Responsive,\n} from 'semantic-ui-react';\nimport wikitreeLogo from './wikitree.png';\n\nenum WikiTreeLoginState {\n UNKNOWN,\n NOT_LOGGED_IN,\n LOGGED_IN,\n}\n\nenum ScreenSize {\n LARGE,\n SMALL,\n}\n\n/** Menus and dialogs state. */\ninterface State {\n loadUrlDialogOpen: boolean;\n wikiTreeIdDialogOpen: boolean;\n url?: string;\n wikiTreeId?: 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 data?: JsonGedcomData;\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 additional WikiTree menus. */\n showWikiTreeMenus: 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 wikiTreeIdDialogOpen: 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 wikiTreeIdInputRef: 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 private openWikiTreeIdDialog() {\n this.setState(\n Object.assign({}, this.state, {wikiTreeIdDialogOpen: true}),\n () => this.wikiTreeIdInputRef.current!.focus(),\n );\n }\n\n /** Cancels any of the open dialogs. */\n private handleClose() {\n this.setState(\n Object.assign({}, this.state, {\n loadUrlDialogOpen: false,\n wikiTreeIdDialogOpen: false,\n }),\n );\n }\n\n /** Load 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 /** Select button clicked in the \"Select WikiTree ID\" dialog. */\n private handleSelectWikiTreeId() {\n this.setState(\n Object.assign({}, this.state, {\n wikiTreeIdDialogOpen: false,\n }),\n );\n if (this.state.wikiTreeId) {\n analyticsEvent('wikitree_id_selected');\n const search = queryString.parse(this.props.location.search);\n const standalone =\n search.standalone !== undefined ? search.standalone : true;\n this.props.history.push({\n pathname: '/view',\n search: queryString.stringify({\n indi: this.state.wikiTreeId,\n source: 'wikitree',\n standalone,\n }),\n });\n }\n }\n\n /** Called when the URL input is typed into. */\n private handleUrlChange(value: string) {\n this.setState(\n Object.assign({}, this.state, {\n url: value,\n }),\n );\n }\n\n /** Called when the URL input is typed into. */\n private handleWikiTreeIdChange(value: string) {\n this.setState(\n Object.assign({}, this.state, {\n wikiTreeId: 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.data) {\n this.searchIndex = buildSearchIndex(this.props.data);\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 wikiTreeLoginUsername = getLoggedInUserName();\n const wikiTreeLoginState = wikiTreeLoginUsername\n ? WikiTreeLoginState.LOGGED_IN\n : WikiTreeLoginState.NOT_LOGGED_IN;\n if (this.state.wikiTreeLoginState !== wikiTreeLoginState) {\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.data !== this.props.data) {\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(data.value)}\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 enterWikiTreeId(event: React.MouseEvent, id: string) {\n event.preventDefault(); // Do not follow link in href.\n ((this.wikiTreeIdInputRef.current as unknown) as {\n inputRef: HTMLInputElement;\n }).inputRef.value = id;\n this.handleWikiTreeIdChange(id);\n this.wikiTreeIdInputRef.current!.focus();\n }\n\n private wikiTreeIdModal() {\n return (\n this.handleClose()}\n centered={false}\n >\n
\n \n txt}\n />\n
\n \n
this.handleSelectWikiTreeId()}>\n

\n \n WikiTree\n \n ),\n example1: (\n this.enterWikiTreeId(e, 'Wojtyla-13')}\n className=\"link-span\"\n >\n Wojtyla-13\n \n ),\n example2: (\n this.enterWikiTreeId(e, 'Skłodowska-2')}\n className=\"link-span\"\n >\n Skłodowska-2\n \n ),\n }}\n />\n

\n this.handleWikiTreeIdChange(data.value)}\n ref={this.wikiTreeIdInputRef}\n />\n \n
\n \n \n \n \n \n );\n }\n\n private search() {\n return (\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 id=\"search\"\n />\n );\n }\n\n private chartMenus(screenSize: ScreenSize) {\n if (!this.props.showingChart) {\n return null;\n }\n const chartTypeItems = (\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 switch (screenSize) {\n case ScreenSize.LARGE:\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 {chartTypeItems}\n \n {this.search()}\n \n );\n\n case ScreenSize.SMALL:\n return (\n <>\n this.props.eventHandlers.onPrint()}>\n \n \n \n\n \n\n this.props.eventHandlers.onDownloadPdf()}\n >\n \n \n \n this.props.eventHandlers.onDownloadPng()}\n >\n \n \n \n this.props.eventHandlers.onDownloadSvg()}\n >\n \n \n \n\n \n {chartTypeItems}\n \n \n );\n }\n }\n\n private title() {\n return (\n \n Topola Genealogy\n \n );\n }\n\n private fileMenus(screenSize: ScreenSize) {\n const loadWikiTreeItem = (\n <>\n \"WikiTree\n \n \n );\n\n // In standalone WikiTree mode, show only the \"Select WikiTree ID\" menu.\n if (!this.props.standalone && this.props.showWikiTreeMenus) {\n switch (screenSize) {\n case ScreenSize.LARGE:\n return (\n <>\n this.openWikiTreeIdDialog()}>\n {loadWikiTreeItem}\n \n {this.wikiTreeIdModal()}\n \n );\n case ScreenSize.SMALL:\n return (\n <>\n this.openWikiTreeIdDialog()}>\n {loadWikiTreeItem}\n \n \n {this.wikiTreeIdModal()}\n \n );\n }\n }\n\n // Don't show \"open\" menus in non-standalone mode.\n if (!this.props.standalone) {\n return null;\n }\n\n const openFileItem = (\n <>\n \n \n \n );\n const loadUrlItem = (\n <>\n \n \n \n );\n const commonElements = (\n <>\n {this.loadFromUrlModal()}\n {this.wikiTreeIdModal()}\n this.handleUpload(e)}\n />\n \n );\n switch (screenSize) {\n case ScreenSize.LARGE:\n // Show dropdown if chart is shown, otherwise show individual menu\n // items.\n const menus = this.props.showingChart ? (\n \n \n \n \n }\n className=\"item\"\n >\n \n \n {openFileItem}\n \n this.openLoadUrlDialog()}>\n {loadUrlItem}\n \n this.openWikiTreeIdDialog()}>\n {loadWikiTreeItem}\n \n \n \n ) : (\n <>\n \n this.openLoadUrlDialog()}>\n {loadUrlItem}\n \n this.openWikiTreeIdDialog()}>\n {loadWikiTreeItem}\n \n \n );\n return (\n <>\n {menus}\n {commonElements}\n \n );\n\n case ScreenSize.SMALL:\n return (\n <>\n \n {openFileItem}\n \n this.openLoadUrlDialog()}>\n {loadUrlItem}\n \n this.openWikiTreeIdDialog()}>\n {loadWikiTreeItem}\n \n \n {commonElements}\n \n );\n }\n }\n\n private wikiTreeLoginMenu(screenSize: ScreenSize) {\n if (!this.props.showWikiTreeMenus) {\n return null;\n }\n switch (this.state.wikiTreeLoginState) {\n case WikiTreeLoginState.NOT_LOGGED_IN:\n const loginForm = (\n \n \n \n \n );\n switch (screenSize) {\n case ScreenSize.LARGE:\n return (\n this.wikiTreeLogin()}>\n \n \n {loginForm}\n \n );\n\n case ScreenSize.SMALL:\n return (\n <>\n this.wikiTreeLogin()}>\n \n \n {loginForm}\n \n \n \n );\n }\n break;\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 switch (screenSize) {\n case ScreenSize.LARGE:\n return (\n \n \n \n \n );\n\n case ScreenSize.SMALL:\n return (\n <>\n \n \n \n \n \n \n );\n\n default:\n return null;\n }\n }\n }\n\n private mobileMenus() {\n return (\n <>\n \n \n \n }\n className=\"item\"\n icon={null}\n >\n \n {this.fileMenus(ScreenSize.SMALL)}\n {this.chartMenus(ScreenSize.SMALL)}\n {this.wikiTreeLoginMenu(ScreenSize.SMALL)}\n\n \n \n \n \n \n {this.props.standalone ? (\n {this.title()}\n ) : (\n this.title()\n )}\n \n );\n }\n\n private desktopMenus() {\n return (\n <>\n {this.props.standalone ? {this.title()} : null}\n {this.fileMenus(ScreenSize.LARGE)}\n {this.chartMenus(ScreenSize.LARGE)}\n \n {this.wikiTreeLoginMenu(ScreenSize.LARGE)}\n \n \n \n \n \n );\n }\n\n render() {\n return (\n <>\n \n {this.desktopMenus()}\n \n \n {this.mobileMenus()}\n \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, InjectedIntl} 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, PRIVATE_ID_PREFIX} 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 constructor(private intl: InjectedIntl) {}\n\n isNewData(args: Arguments, state: State): boolean {\n if (state.selection && state.selection.id === args.indi) {\n // Selection unchanged -> don't reload.\n return false;\n }\n if (\n state.data &&\n state.data.chartData.indis.some((indi) => indi.id === args.indi)\n ) {\n // New selection exists in current view -> animate instead of reloading.\n return false;\n }\n return true;\n }\n\n async loadData(args: Arguments): Promise {\n try {\n const data = await loadWikiTree(args.indi!, this.intl, 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/** 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 freezeAnimation?: 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 freezeAnimation: getParam('freeze') === 'true', // False by default\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 };\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 /** Freeze animations after initial chart render. */\n freezeAnimation?: 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 };\n chartRef: Chart | null = null;\n\n /** Make intl appear in this.context. */\n static contextTypes = {\n intl: intlShape,\n };\n\n /** Mapping from data source identifier to data source handler functions. */\n private readonly dataSources = new Map([\n [DataSourceEnum.UPLOADED, new UploadedDataSource()],\n [DataSourceEnum.GEDCOM_URL, new GedcomUrlDataSource()],\n [DataSourceEnum.WIKITREE, new WikiTreeDataSource(this.context.intl)],\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 = this.dataSources.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: {id: args.indi},\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 }),\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 freezeAnimation: args.freezeAnimation,\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 try {\n const data = await loadWikiTree(args.indi!, this.context.intl);\n const selection = getSelection(\n data.chartData,\n args.indi,\n args.generation,\n );\n this.setState(\n Object.assign({}, this.state, {\n data,\n hash: args.hash,\n selection,\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 loadingMore: false,\n }),\n );\n } catch (error) {\n this.showErrorPopup(\n this.context.intl.formatMessage(\n {\n id: 'error.failed_wikitree_load_more',\n defaultMessage: 'Failed to load data from WikiTree. {error}',\n },\n {error},\n ),\n {\n loadingMore: false,\n },\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 // Don't allow selecting WikiTree private profiles.\n if (selection.id.startsWith(PRIVATE_ID_PREFIX)) {\n return;\n }\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, otherStateChanges?: Partial) {\n this.setState(\n Object.assign(\n {},\n this.state,\n {\n showErrorPopup: true,\n error: message,\n },\n otherStateChanges,\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 />\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","module.exports = __webpack_public_path__ + \"static/media/wikitree.1dee3d66.png\";"],"sourceRoot":""} \ No newline at end of file diff --git a/static/js/main.20beea3f.chunk.js b/static/js/main.20beea3f.chunk.js new file mode 100644 index 0000000..bd93932 --- /dev/null +++ b/static/js/main.20beea3f.chunk.js @@ -0,0 +1,2 @@ +(this["webpackJsonptopola-viewer"]=this["webpackJsonptopola-viewer"]||[]).push([[0],{196:function(e,t,n){e.exports=n.p+"static/media/topola.060eef13.jpg"},287:function(e){e.exports=JSON.parse('{"menu.open":"Otw\xf3rz","menu.open_file":"Otw\xf3rz plik","menu.load_from_url":"Otw\xf3rz URL","menu.select_wikitree_id":"Wybierz WikiTree ID","menu.print":"Drukuj","menu.download":"Pobierz","menu.pdf_file":"Plik PDF","menu.png_file":"Plik PNG","menu.svg_file":"Plik SVG","menu.download_pdf":"Pobierz PDF","menu.download_png":"Pobierz PNG","menu.download_svg":"Pobierz 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":"Projekt na stronie GitHub","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 PLIK lub OTW\xd3RZ URL, 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","select_wikitree_id.title":"Podaj WikiTree ID","select_wikitree_id.comment":"Wpisz identyfikator profilu {wikiTreeLink}. Przyk\u0142ady: {example1}, {example2}","select_wikitree_id.cancel":"Anuluj","select_wikitree_id.load":"Otw\xf3rz","gedcom.BAPM":"Chrzest","gedcom.BIRT":"Narodziny","gedcom.BURI":"Pogrzeb","gedcom.CENS":"Spis ludno\u015bci","gedcom.CHR":"Chrzest","gedcom.DEAT":"\u015amier\u0107","gedcom.DSCR":"Opis","gedcom.EMAIL":"E-mail","gedcom.EVEN":"Wydarzenie","gedcom.OCCU":"Zaw\xf3d","gedcom.RIN":"ID","gedcom.TITL":"Tytu\u0142","gedcom.WWW":"Strona WWW","gedcom._UPD":"Ostatnia aktualizacja","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","error.failed_wikitree_load_more":"B\u0142\u0105d podczas pobierania danych z WikiTree. {error}","wikitree.private":"Prywatne"}')},288:function(e,t){},331:function(e,t,n){e.exports=n(585)},343:function(e,t){},349:function(e,t){},410:function(e,t){},582:function(e,t,n){},585:function(e,t,n){"use strict";n.r(t);var a=n(34),r=n(285),i=n(286),o=n(0),s=n(76),c=n(287),l=n(8),u=n(41),d=n(40),m=n(48),f=n(10),h=n.n(f),p=n(18),g=n(28),v=n(29),w=n(33);function E(e,t){window.gtag("event",e,t)}var k,b=n(142),y=n(72),O=n(49),M=n(103),D=n(73),T=n(615),I=n(195),S=n(95),j=(n(74),n(35));function x(e){var t=Object(b.a)("#svgContainer").node(),n=y.c.transform.k,a=Object(M.a)([0,(t.clientWidth-e[0]*n)/2]),r=Object(M.a)([0,(t.clientHeight-e[1]*n)/2]);Object(b.a)("#chartSvg").attr("width",e[0]*n).attr("height",e[1]*n).attr("transform","translate(".concat(a,", ").concat(r,")")),Object(b.a)("#chart").attr("transform","scale(".concat(n,")")),t.scrollLeft=-y.c.transform.x,t.scrollTop=-y.c.transform.y}function _(){var e=Object(b.a)("#svgContainer").node(),t=e.scrollLeft+e.clientWidth/2,n=e.scrollTop+e.clientHeight/2,a=Object(S.b)(e).k;Object(b.a)(e).call(Object(S.a)().translateTo,t/a,n/a)}function R(e){var t=new FileReader;return t.readAsDataURL(e),new Promise((function(e,n){t.onload=function(t){return e(t.target.result)}}))}function N(e){return L.apply(this,arguments)}function L(){return(L=Object(p.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,R(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 C(e){return z.apply(this,arguments)}function z(){return(z=Object(p.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(N));case 3:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function W(e){var t=new Image;return t.src=URL.createObjectURL(e),new Promise((function(e,n){t.addEventListener("load",(function(){return e(t)}))}))}function P(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 A(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"}(k||(k={}));var F=function(e){Object(u.a)(a,e);var t=Object(d.a)(a);function a(){var e;Object(g.a)(this,a);for(var n=arguments.length,r=new Array(n),i=0;i0&&void 0!==arguments[0]?arguments[0]:{initialRender:!1};if(t.initialRender||!this.animating){if(t.initialRender||!this.props.freezeAnimation){t.initialRender?(Object(b.a)("#chart").node().innerHTML="",this.chart=Object(j.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=Object(b.a)("#chartSvg"),r=Object(b.a)("#svgContainer").node(),i=Object(S.b)(r).k,o=Object(D.a)([1,i,r.clientWidth/n.size[0],r.clientHeight/n.size[1]]),s=[Object(M.a)([.1,o]),2];this.zoomBehavior=Object(S.a)().scaleExtent(s).translateExtent([[0,0],n.size]).on("zoom",(function(){return x(n.size)})),Object(b.a)(r).on("scroll",_).call(this.zoomBehavior);var c=function(e){return function(){var t=Object(O.a)(r.scrollTop,e);return function(e){r.scrollTop=t(e)}}},l=function(e){return function(){var t=Object(O.a)(r.scrollLeft,e);return function(e){r.scrollLeft=t(e)}}},u=r.clientWidth/2-n.origin[0]*i,d=r.clientHeight/2-n.origin[1]*i,m=Object(M.a)([0,(r.clientWidth-n.size[0]*i)/2]),f=Object(M.a)([0,(r.clientHeight-n.size[1]*i)/2]),h=a.transition().delay(200).duration(500),p=t.initialRender?a:h;p.attr("transform","translate(".concat(m,", ").concat(f,")")).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)).tween("scrollTop",c(-d)),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"},o.createElement(T.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")),o.createElement("svg",{id:"chartSvg"},o.createElement("g",{id:"chart"})))}},{key:"getStrippedSvg",value:function(){var e=document.getElementById("chartSvg").cloneNode(!0);e.removeAttribute("transform");var t=Object(b.a)("#svgContainer").node(),n=Object(S.b)(t).k;return e.setAttribute("width",String(Number(e.getAttribute("width"))/n)),e.setAttribute("height",String(Number(e.getAttribute("height"))/n)),e.querySelector("#chart").removeAttribute("transform"),e}},{key:"getSvgContents",value:function(){return(new XMLSerializer).serializeToString(this.getStrippedSvg())}},{key:"getSvgContentsWithInlinedImages",value:function(){var e=Object(p.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,C(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(p.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(I.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(p.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=P,e.next=7,W(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(p.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,A(t,"image/png");case 5:n=e.sent,Object(I.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(p.a)(h.a.mark((function e(){var t,a,r,i;return h.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,n.e(3).then(n.t.bind(null,617,7));case 2:return t=e.sent,a=t.default,e.next=6,this.drawOnCanvas();case 6:r=e.sent,(i=new a({orientation:r.width>r.height?"l":"p",unit:"pt",format:[r.width,r.height]})).addImage(r,"PNG",0,0,r.width,r.height,"NONE"),i.save("topola.pdf");case 10:case"end":return e.stop()}}),e,this)})));return function(){return e.apply(this,arguments)}}()}]),a}(o.PureComponent);F.contextTypes={intl:l.d};var U=n(292),G=n.n(U),H=n(293),B=n.n(H),V=n(191);function K(e){return e.substring(1,e.length-1)}function J(e){var t=new Map;return e.indis.forEach((function(e){t.set(e.id,e)})),t}function q(e){var t=new Map;return e.fams.forEach((function(e){t.set(e.id,e)})),t}function Z(e){var t=e.find((function(e){return"HEAD"===e.tag})),n={},a={},r={};return e.forEach((function(e){"INDI"===e.tag?n[K(e.pointer)]=e:"FAM"===e.tag?a[K(e.pointer)]=e:e.pointer&&(r[K(e.pointer)]=e)})),{head:t,indis:n,fams:a,other:r}}function Y(e,t){return et?1:0}function X(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.day&&a.day&&n.day!==a.day)?n.month-a.month:0:0}function $(e){var t=function(e){var t=J(e);return function(e,n){var a=t.get(e),r=t.get(n);return X(a&&a.birth,r&&r.birth)||Y(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 Q(e){var t=function(e){var t=q(e);return function(e,n){var a=t.get(e),r=t.get(n);return X(a&&a.marriage,r&&r.marriage)||Y(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 ee(e){return Q($(e))}var te=[".jpg",".png",".gif"];function ne(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 te.some((function(e){return t.endsWith(e)}))}(e.url)&&n.push(e)})),Object.assign({},e,{images:n})}function ae(e,t){var n=e.indis.map((function(e){return ne(e,t)}));return Object.assign({},e,{indis:n})}function re(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 ie=new Map([["abt","about"],["cal","calculated"],["est","estimated"]]);function oe(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:ie.get(o)||o}),new Intl.DateTimeFormat(t.locale,s).format(i)].join(" ")}function se(e,t){return e?e.date?oe(e.date,t):e.dateRange?function(e,t){var n=e.from,a=e.to,r=n&&oe(n,t),i=a&&oe(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}):""}(e.dateRange,t):"":""}var ce=["BIRT","BAPM","CHR","DEAT","BURI","EVEN","CENS"],le=["NAME","SEX","FAMC","FAMS","NOTE","SOUR"],ue=new Map([["BAPM","Baptism"],["BIRT","Birth"],["BURI","Burial"],["CENS","Census"],["CHR","Christening"],["DEAT","Death"],["EMAIL","E-mail"],["EVEN","Event"],["OCCU","Occupation"],["TITL","Title"],["WWW","WWW"]]);function de(e){return o.createElement(l.a,{id:"gedcom.".concat(e),defaultMessage:ue.get(e)||e})}function me(e){return o.createElement(o.Fragment,null,e.map((function(e,t){return o.createElement("div",{key:t},o.createElement(B.a,{properties:{target:"_blank"}},e),o.createElement("br",null))})))}function fe(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 he(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(function(e,t){return se(Object(j.getDate)(e),t)}(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)(fe(i))),e.tree.filter((function(e){return"NOTE"===e.tag})).forEach((function(e){return fe(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"},de(e.tag)),o.createElement("span",null,me(n))):null}function pe(e){return me(fe(e).map((function(e,t){return o.createElement("i",{key:t},e)})))}function ge(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 ve(e,t,n){return G()(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 we(e){return e.tree.length>0||e.data&&!e.data.startsWith("@")}function Ee(e){return e.filter((function(e){return!le.includes(e.tag)&&!ce.includes(e.tag)})).filter(we).map((function(e){return function(e){var t=[];return e.data&&t.push.apply(t,Object(a.a)(fe(e))),e.tree.filter((function(e){return"NOTE"===e.tag})).forEach((function(e){return fe(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"},de(e.tag)),o.createElement("span",null,me(t))):null}(e)})).filter((function(e){return null!==e})).map((function(e,t){return o.createElement("div",{className:"ui segment",key:t},e)}))}var ke=function(e){Object(u.a)(n,e);var t=Object(d.a)(n);function n(){return Object(g.a)(this,n),t.apply(this,arguments)}return Object(v.a)(n,[{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[K(e.data)];if(n)return n}return e}(t,e.props.gedcom)})).filter(we);return o.createElement("div",{className:"ui segments",id:"details"},ve(t,["NAME"],ge),ve(t,ce,(function(t){return he(t,e.context.intl)})),Ee(n),ve(n,["NOTE"],pe))}}]),n}(o.Component);function be(e,t,n){return{id:t&&e.indis.some((function(e){return e.id===t}))?t:e.indis[0].id,generation:n||0}}function ye(e,t,n){var a=function(e,t){var n=Object(V.parse)(e),a=Object(j.gedcomEntriesToJson)(n);if(!a||!a.indis||!a.indis.length||!a.fams||!a.fams.length)throw new Error("Failed to read GEDCOM file");return{chartData:ae(ee(a),t),gedcom:Z(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 Oe(e,t){return Me.apply(this,arguments)}function Me(){return(Me=Object(p.a)(h.a.mark((function e(t,n){var a,r,i,o,s,c;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=t.match(/https:\/\/drive\.google\.com\/file\/d\/(.*)\/.*/))&&(t="https://drive.google.com/uc?id=".concat(r[1],"&export=download")),(i=t.match(/https:\/\/drive\.google\.com\/open\?id=([^&]*)&?.*/))&&(t="https://drive.google.com/uc?id=".concat(i[1],"&export=download")),o=n?"https://cors-anywhere.herokuapp.com/"+t:t,e.next=16,window.fetch(o);case 16:if(200===(s=e.sent).status){e.next=19;break}throw new Error(s.statusText);case 19:return e.next=21,s.text();case 21:return c=e.sent,e.abrupt("return",ye(c,t));case 23:case"end":return e.stop()}}),e,null,[[0,6]])})))).apply(this,arguments)}function De(e,t,n){return Te.apply(this,arguments)}function Te(){return(Te=Object(p.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",ye(n,t,a));case 12:case"end":return e.stop()}}),e,null,[[0,6]])})))).apply(this,arguments)}ke.contextTypes={intl:l.d};var Ie=n(196),Se=n.n(Ie),je=n(605),xe=n(611),_e=n(318),Re=n(598);function Ne(e){return o.createElement(Re.a,{to:{pathname:"/view",search:w.stringify({url:e.url})}},e.text)}function Le(){var e=o.createElement(o.Fragment,null,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 OPEN FILE or LOAD FROM URL 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(Ne,{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(Ne,{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(Ne,{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-05-01 16:57:41 +0200".slice(0,16)," (",o.createElement("a",{href:"https://github.com/PeWu/topola-viewer/commit/".concat("f588c62")},"f588c62"),")"));return o.createElement("div",{id:"content"},o.createElement("div",{className:"backgroundImage"}),o.createElement(je.a,{className:"intro"},o.createElement(T.a,{as:je.a.Content,minWidth:768},o.createElement(je.a.Header,null,o.createElement(l.a,{id:"intro.title",defaultMessage:"Topola Genealogy Viewer"}))),o.createElement(je.a.Content,null,o.createElement(T.a,{as:xe.a,minWidth:768},o.createElement(xe.a.Row,null,o.createElement(xe.a.Column,{width:5},o.createElement(_e.a,{src:Se.a,alt:"Topola logo"})),o.createElement(xe.a.Column,{width:11},e))),o.createElement(T.a,{maxWidth:767},o.createElement(_e.a,{src:Se.a,alt:"Topola logo",centered:!0,size:"tiny",className:"blockImage"}),e))))}var Ce=n(606),ze=n(616),We=n(601),Pe=n(197),Ae=n.n(Pe);function Fe(e){try{return sessionStorage.getItem(e)}catch(t){console.warn("Failed to load data from session storage: "+t)}return null}function Ue(e,t){try{sessionStorage.setItem(e,t)}catch(n){console.warn("Failed to store data in session storage: "+n)}}function Ge(e,t){return He.apply(this,arguments)}function He(){return(He=Object(p.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://api.wikitree.com/api.php":"https://api.wikitree.com/api.php",e.next=6,window.fetch(i,{method:"POST",body:a,credentials:n?void 0:"include"});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 Be(e,t){return Ve.apply(this,arguments)}function Ve(){return(Ve=Object(p.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=Fe(a))){e.next=4;break}return e.abrupt("return",JSON.parse(r));case 4:return e.next=6,Ge({action:"getAncestors",key:t,fields:"*"},n);case 6:return i=e.sent,o=i[0].ancestors,Ue(a,JSON.stringify(o)),e.abrupt("return",o);case 10:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function Ke(e,t){return Je.apply(this,arguments)}function Je(){return(Je=Object(p.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=Fe("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,Ge({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){Ue("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 qe(e){return Ze.apply(this,arguments)}function Ze(){return(Ze=Object(p.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,Ge({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 Ye(){return Ae.a.get("wikidb_wtb_UserName")}function Xe(e,t,n){return $e.apply(this,arguments)}function $e(){return($e=Object(p.a)(h.a.mark((function e(t,n,r){var i,o,s,c,l,u,d,f,p,g,v,w,E,k,b,y,O,M,D,T,I,S,j,x,_;return h.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if((i="apps.wikitree.com"!==window.location.hostname)||Ye()||!r){e.next=6;break}return e.next=4,qe(r);case 4:"Success"===(o=e.sent).result&&(sessionStorage.clear(),Ae.a.set("wikidb_wtb_UserName",o.username));case 6:return s=[],e.next=9,Ke([t],i);case 9:if((c=e.sent)[0].Name){e.next=12;break}throw new Error("WikiTree profile ".concat(t," is not accessible. Try logging in."));case 12:return l=Object.values(c[0].Spouses).map((function(e){return e.Name})),e.next=15,Promise.all([t].concat(l).map((function(e){return Be(e,i)})));case 15:return u=e.sent,d=u.flat().map((function(e){return e.Name})).filter((function(e){return!!e})),e.next=19,Ke(d,i);case 19:f=e.sent,p=new Map,g=new Map,u.forEach((function(e,t){var n=1e3*t;e.forEach((function(e){e.Id<0&&(e.Id-=n,e.Name="".concat("~Private").concat(e.Id)),e.Father<0&&(e.Father-=n,p.set(e.Id,e.Father)),e.Mother<0&&(e.Mother-=n,g.set(e.Id,e.Mother))}))})),f.forEach((function(e){var t=p.get(e.Id);t&&(e.Father=t);var n=g.get(e.Id);n&&(e.Mother=n)})),s.push.apply(s,Object(a.a)(f)),v=u.flat().filter((function(e){return e.Id<0})),s.push.apply(s,Object(a.a)(v)),w=5,E=[t],k=0;case 30:if(!(E.length>0&&k<=w)){e.next=41;break}return e.next=33,Ke(E,i);case 33:b=e.sent,s.push.apply(s,Object(a.a)(b)),y=b.flatMap((function(e){return Object.values(e.Spouses)})),s.push.apply(s,Object(a.a)(y)),E=b.flatMap((function(e){return Object.values(e.Children).map((function(e){return e.Name}))})),k++,e.next=30;break;case 41:return O=new Map,M=new Map,D=new Map,T=new Map,s.forEach((function(e){if(T.set(e.Id,e.Name),e.Mother||e.Father){var t=Qe(e.Mother,e.Father);rt(O,e.Mother).add(t),rt(O,e.Father).add(t),rt(M,t).add(e.Id),D.set(t,{wife:e.Mother||void 0,husband:e.Father||void 0})}})),I=[],S=new Set,s.forEach((function(e){if(!S.has(e.Id)){S.add(e.Id);var t=et(e,n);e.Spouses&&Object.values(e.Spouses).forEach((function(t){var n=Qe(e.Id,t.Id);rt(O,e.Id).add(n),rt(O,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};D.set(n,a)})),t.fams=Array.from(rt(O,e.Id)),I.push(t)}})),j=Array.from(D.entries()).map((function(e){var t=Object(m.a)(e,2),n=t[0],a=t[1],r={id:n},i=a.wife&&T.get(a.wife);i&&(r.wife=i);var o=a.husband&&T.get(a.husband);if(o&&(r.husb=o),r.children=Array.from(rt(M,n)).map((function(e){return T.get(e)})),a.spouse&&(a.spouse.marriage_date&&"0000-00-00"!==a.spouse.marriage_date||a.spouse.marriage_location)){var s=tt(a.spouse.marriage_date);r.marriage=Object.assign({},s,{place:a.spouse.marriage_location})}return r})),x=ee({indis:I,fams:j}),_=at(I),e.abrupt("return",{chartData:x,gedcom:_});case 53:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function Qe(e,t){return t>e?"".concat(e,"_").concat(t):"".concat(t,"_").concat(e)}function et(e,t){var n={id:e.Name};if(e.Name.startsWith("~Private")&&(n.hideId=!0,n.firstName=t.formatMessage({id:"wikitree.private",defaultMessage:"Private"})),e.FirstName&&"Unknown"!==e.FirstName?n.firstName=e.FirstName:e.RealName&&"Unknown"!==e.RealName&&(n.firstName=e.RealName),"Unknown"!==e.LastNameAtBirth&&(n.lastName=e.LastNameAtBirth),(e.Mother||e.Father)&&(n.famc=Qe(e.Mother,e.Father)),"Male"===e.Gender?n.sex="M":"Female"===e.Gender&&(n.sex="F"),e.BirthDate&&"0000-00-00"!==e.BirthDate||e.BirthLocation||"unknown"!==e.BirthDateDecade){var a=tt(e.BirthDate,e.DataStatus&&e.DataStatus.BirthDate)||nt(e.BirthDateDecade);n.birth=Object.assign({},a,{place:e.BirthLocation})}if(e.DeathDate&&"0000-00-00"!==e.DeathDate||e.DeathLocation||"unknown"!==e.DeathDateDecade){var r=tt(e.DeathDate,e.DataStatus&&e.DataStatus.DeathDate)||nt(e.DeathDateDecade);n.death=Object.assign({},r,{place:e.DeathLocation})}return e.PhotoData&&(n.images=[{url:"https://www.wikitree.com".concat(e.PhotoData.url)}]),n}function tt(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 nt(e){return"unknown"!==e?{date:{text:e}}:void 0}function at(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:[]}]},e.id.startsWith("~")||t[e.id].tree.push({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 rt(e,t){var n=e.get(t);if(n)return n;var a=new Set;return e.set(t,a),a}var it=n(613),ot=n(614),st=n(609),ct=n(297),lt=n.n(ct),ut=n(198),dt=n.n(ut),mt=n(298),ft=n.n(mt),ht=n(299),pt=n.n(ht);function gt(e){return e.toLocaleLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/\u0142/g,"l")}function vt(e,t){return e.score!==t.score?t.score-e.score:ft()(e.ref,t.ref)}var wt=function(){function e(t){Object(g.a)(this,e),this.index=void 0,this.indiMap=void 0,this.famMap=void 0,this.indiMap=J(t),this.famMap=q(t)}return Object(v.a)(e,[{key:"initialize",value:function(){var e=this;this.index=pt()((function(){var t=this;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.indiMap.forEach((function(n){var a=[n.firstName,n.lastName].join(" "),r=function(e,t,n){return(e.fams||[]).map((function(e){return n.get(e)})).map((function(e){return e&&e.husb})).map((function(e){return e&&t.get(e)})).map((function(e){return e&&e.lastName})).join(" ")}(n,e.indiMap,e.famMap);t.add({id:n.id,name:a,normalizedName:gt(a),spouseLastName:r,normalizedSpouseLastName:gt(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(vt).slice(0,8).map((function(e){return{id:e.ref,indi:t.indiMap.get(e.ref)}}))}}]),e}();function Et(e){var t=[e.indi.firstName,e.indi.lastName].join(" ").trim();return e.id.length>8?t:o.createElement(o.Fragment,null,t," ",o.createElement("i",null,"(",e.id,")"))}function kt(e,t){var n=se(e.birth,t),a=se(e.death,t);return a?"".concat(n," \u2013 ").concat(a):n}var bt,yt,Ot=n(603),Mt=n(612),Dt=n(77),Tt=n(602),It=n(600),St=n(587),jt=n(607),xt=n(604),_t=n(608),Rt=n(78),Nt=n.n(Rt);function Lt(e){return new Promise((function(t,n){var a=new FileReader;a.onload=function(e){t(e.target.result)},a.readAsText(e)}))}function Ct(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"}(bt||(bt={})),function(e){e[e.LARGE=0]="LARGE",e[e.SMALL=1]="SMALL"}(yt||(yt={}));var zt,Wt=function(e){Object(u.a)(n,e);var t=Object(d.a)(n);function n(){var e;Object(g.a)(this,n);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 freezeAnimation?: 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?: 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 = select('#svgContainer') as Selection;\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 // Freeze changing selection after initial rendering.\n if (!args.initialRender && this.props.freezeAnimation) {\n return;\n }\n\n if (args.initialRender) {\n (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 = select('#chartSvg');\n const parent = select('#svgContainer').node() as Element;\n\n const scale = zoomTransform(parent).k;\n const zoomOutFactor = min([\n 1,\n scale,\n parent.clientWidth / chartInfo.size[0],\n parent.clientHeight / chartInfo.size[1],\n ])!;\n const extent: [number, number] = [max([0.1, zoomOutFactor])!, 2];\n\n this.zoomBehavior = zoom()\n .scaleExtent(extent)\n .translateExtent([[0, 0], chartInfo.size])\n .on('zoom', () => zoomed(chartInfo.size));\n select(parent)\n .on('scroll', scrolled)\n .call(this.zoomBehavior);\n\n const scrollTopTween = (scrollTop: number) => {\n return () => {\n const i = 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 = 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 = max([\n 0,\n (parent.clientWidth - chartInfo.size[0] * scale) / 2,\n ]);\n const offsetY = 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 \n \n this.zoom(1 / ZOOM_FACTOR)}\n >\n −\n \n \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 const parent = select('#svgContainer').node() as Element;\n const scale = 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 // Lazy load jspdf.\n const {default: jspdf} = await import('jspdf');\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\nexport function idToIndiMap(data: JsonGedcomData): Map {\n const map = new Map();\n data.indis.forEach((indi) => {\n map.set(indi.id, indi);\n });\n return map;\n}\n\nexport function idToFamMap(data: JsonGedcomData): Map {\n const map = new Map();\n data.fams.forEach((fam) => {\n map.set(fam.id, fam);\n });\n return map;\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 indiMap = idToIndiMap(gedcom);\n\n return (indiId1: string, indiId2: string) => {\n const indi1: JsonIndi | undefined = indiMap.get(indiId1);\n const indi2: JsonIndi | undefined = indiMap.get(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 famMap = idToFamMap(gedcom);\n\n return (famId1: string, famId2: string) => {\n const fam1: JsonFam | undefined = famMap.get(famId1);\n const fam2: JsonFam | undefined = famMap.get(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, DateOrRange} 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 DateOrRange object. */\nexport function formatDateOrRange(\n dateOrRange: DateOrRange | undefined,\n intl: InjectedIntl,\n): string {\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\n/** Formats a date given in GEDCOM format. */\nexport function translateDate(gedcomDate: string, intl: InjectedIntl): string {\n return formatDateOrRange(getDate(gedcomDate), intl);\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', 'CENS'];\nconst EXCLUDED_TAGS = ['NAME', 'SEX', 'FAMC', 'FAMS', 'NOTE', 'SOUR'];\nconst TAG_DESCRIPTIONS = new Map([\n ['BAPM', 'Baptism'],\n ['BIRT', 'Birth'],\n ['BURI', 'Burial'],\n ['CENS', 'Census'],\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\n const driveUrlMatch1 = url.match(/https:\\/\\/drive\\.google\\.com\\/file\\/d\\/(.*)\\/.*/);\n if (driveUrlMatch1) {\n url = `https://drive.google.com/uc?id=${driveUrlMatch1[1]}&export=download`;\n }\n const driveUrlMatch2 = url.match(/https:\\/\\/drive\\.google\\.com\\/open\\?id=([^&]*)&?.*/);\n if (driveUrlMatch2) {\n url = `https://drive.google.com/uc?id=${driveUrlMatch2[1]}&export=download`;\n }\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, Responsive} 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 const contents = (\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 version: {formatBuildDate(process.env.REACT_APP_GIT_TIME!)} (\n \n {process.env.REACT_APP_GIT_SHA}\n \n )\n

\n \n );\n\n return (\n
\n
\n \n \n \n \n \n \n \n \n \n \n \"Topola\n \n {contents}\n \n \n \n \n {contents}\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';\nimport {InjectedIntl} from 'react-intl';\n\n/** Prefix for IDs of private individuals. */\nexport const PRIVATE_ID_PREFIX = '~Private';\n\n/**\n * Cookie where the logged in user name is stored. This cookie is shared\n * between apps hosted on apps.wikitree.com.\n */\nconst USER_NAME_COOKIE = 'wikidb_wtb_UserName';\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 GetRelativesRequest {\n action: 'getRelatives';\n keys: string;\n getChildren?: true;\n getSpouses?: true;\n}\n\n/** WikiTree API clientLogin request. */\ninterface ClientLoginRequest {\n action: 'clientLogin';\n authcode: string;\n}\n\n/** WikiTree API clientLogin response. */\ninterface ClientLoginResponse {\n result: string;\n username: string;\n}\n\ntype WikiTreeRequest =\n | GetAncestorsRequest\n | GetRelativesRequest\n | ClientLoginRequest;\n\n/** Person structure returned from WikiTree API. */\ninterface Person {\n Id: number;\n Name: string;\n FirstName: string;\n LastNameAtBirth: string;\n RealName: 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 BirthDateDecade: string;\n DeathDateDecade: string;\n marriage_location: string;\n marriage_date: string;\n DataStatus?: {\n BirthDate: string;\n DeathDate: string;\n };\n PhotoData?: {\n path: string;\n url: 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://api.wikitree.com/api.php'\n : 'https://api.wikitree.com/api.php';\n const response = await window.fetch(apiUrl, {\n method: 'POST',\n body: requestData,\n credentials: handleCors ? undefined : 'include',\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(\n key: string,\n handleCors: boolean,\n): Promise {\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(\n keys: string[],\n handleCors: boolean,\n): Promise {\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(\n authcode: string,\n): Promise {\n const response = await wikiTreeGet(\n {\n action: 'clientLogin',\n authcode,\n },\n false,\n );\n return response.clientLogin;\n}\n\n/**\n * Returnes the logged in user name or undefined if not logged in.\n *\n * This is not an authoritative answer. The result of this function relies on\n * the cookies set on the apps.wikitree.com domain under which this application\n * is hosted. The authoritative source of login information is in cookies set on\n * the api.wikitree.com domain.\n */\nexport function getLoggedInUserName(): string | undefined {\n return Cookies.get(USER_NAME_COOKIE);\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 intl: InjectedIntl,\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 && !getLoggedInUserName() && authcode) {\n const loginResult = await clientLogin(authcode);\n if (loginResult.result === 'Success') {\n sessionStorage.clear();\n Cookies.set(USER_NAME_COOKIE, loginResult.username);\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\n // Map from person id to father id if the father profile is private.\n const privateFathers: Map = new Map();\n // Map from person id to mother id if the mother profile is private.\n const privateMothers: Map = new Map();\n\n // Andujst private individual ids so that there are no collisions in the case\n // that ancestors were collected for more than one person.\n ancestors.forEach((ancestorList, index) => {\n const offset = 1000 * index;\n // Adjust ids by offset.\n ancestorList.forEach((person) => {\n if (person.Id < 0) {\n person.Id -= offset;\n person.Name = `${PRIVATE_ID_PREFIX}${person.Id}`;\n }\n if (person.Father < 0) {\n person.Father -= offset;\n privateFathers.set(person.Id, person.Father);\n }\n if (person.Mother < 0) {\n person.Mother -= offset;\n privateMothers.set(person.Id, person.Mother);\n }\n });\n });\n\n // Set the Father and Mother fields again because getRelatives doesn't return\n // private parents.\n ancestorDetails.forEach((person) => {\n const privateFather = privateFathers.get(person.Id);\n if (privateFather) {\n person.Father = privateFather;\n }\n const privateMother = privateMothers.get(person.Id);\n if (privateMother) {\n person.Mother = privateMother;\n }\n });\n everyone.push(...ancestorDetails);\n\n // Collect private individuals.\n const privateAncestors = ancestors.flat().filter((person) => person.Id < 0);\n everyone.push(...privateAncestors);\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, intl);\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, intl: InjectedIntl): JsonIndi {\n const indi: JsonIndi = {\n id: person.Name,\n };\n if (person.Name.startsWith(PRIVATE_ID_PREFIX)) {\n indi.hideId = true;\n indi.firstName = intl.formatMessage({\n id: 'wikitree.private',\n defaultMessage: 'Private',\n });\n }\n if (person.FirstName && person.FirstName !== 'Unknown') {\n indi.firstName = person.FirstName;\n } else if (person.RealName && person.RealName !== 'Unknown') {\n indi.firstName = person.RealName;\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 person.BirthDateDecade !== 'unknown'\n ) {\n const parsedDate = parseDate(\n person.BirthDate,\n person.DataStatus && person.DataStatus.BirthDate,\n );\n const date = parsedDate || parseDecade(person.BirthDateDecade);\n indi.birth = Object.assign({}, date, {place: person.BirthLocation});\n }\n if (\n (person.DeathDate && person.DeathDate !== '0000-00-00') ||\n person.DeathLocation ||\n person.DeathDateDecade !== 'unknown'\n ) {\n const parsedDate = parseDate(\n person.DeathDate,\n person.DataStatus && person.DataStatus.DeathDate,\n );\n const date = parsedDate || parseDecade(person.DeathDateDecade);\n indi.death = Object.assign({}, date, {place: person.DeathLocation});\n }\n if (person.PhotoData) {\n indi.images = [{url: `https://www.wikitree.com${person.PhotoData.url}`}];\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\nfunction parseDecade(decade: string): DateOrRange | undefined {\n return decade !== 'unknown' ? {date: {text: decade}} : undefined;\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 };\n if (!indi.id.startsWith('~')) {\n gedcomIndis[indi.id].tree.push({\n level: 1,\n pointer: '',\n tag: 'WWW',\n data: `https://www.wikitree.com/wiki/${escapedId}`,\n tree: [],\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 {idToIndiMap, idToFamMap} from './gedcom_util';\nimport {JsonIndi, JsonFam, JsonGedcomData} from 'topola';\n\nconst MAX_RESULTS = 8;\n\nexport interface SearchResult {\n id: string;\n indi: JsonIndi;\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(\n indi: JsonIndi,\n indiMap: Map,\n famMap: Map,\n): string {\n return (indi.fams || [])\n .map((famId) => famMap.get(famId))\n .map((fam) => fam && fam.husb)\n .map((husbId) => husbId && indiMap.get(husbId))\n .map((husband) => husband && husband.lastName)\n .join(' ');\n}\n\nclass LunrSearchIndex implements SearchIndex {\n private index: lunr.Index | undefined;\n private indiMap: Map;\n private famMap: Map;\n\n constructor(data: JsonGedcomData) {\n this.indiMap = idToIndiMap(data);\n this.famMap = idToFamMap(data);\n }\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 self.indiMap.forEach((indi) => {\n const name = [indi.firstName, indi.lastName].join(' ');\n const spouseLastName = getHusbandLastName(\n indi,\n self.indiMap,\n self.famMap,\n );\n this.add({\n id: indi.id,\n name,\n normalizedName: normalize(name),\n spouseLastName,\n normalizedSpouseLastName: normalize(spouseLastName),\n });\n });\n });\n }\n\n public search(input: string): SearchResult[] {\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.indiMap.get(result.ref)!}));\n }\n}\n\n/** Builds a search index from data. */\nexport function buildSearchIndex(data: JsonGedcomData): SearchIndex {\n const index = new LunrSearchIndex(data);\n index.initialize();\n return index;\n}\n","import * as React from 'react';\nimport {InjectedIntl} from 'react-intl';\nimport {SearchResult} from './search_index';\nimport {formatDateOrRange} from './date_util';\nimport {JsonIndi} from 'topola';\n\nfunction getNameLine(result: SearchResult) {\n const name = [result.indi.firstName, result.indi.lastName].join(' ').trim();\n if (result.id.length > 8) {\n return name;\n }\n return (\n <>\n {name} ({result.id})\n \n );\n}\n\nfunction getDescriptionLine(indi: JsonIndi, intl: InjectedIntl) {\n const birthDate = formatDateOrRange(indi.birth, intl);\n const deathDate = formatDateOrRange(indi.death, 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 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 {getLoggedInUserName} from './wikitree';\nimport {IndiInfo, JsonGedcomData} 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 Responsive,\n} from 'semantic-ui-react';\nimport wikitreeLogo from './wikitree.png';\n\nenum WikiTreeLoginState {\n UNKNOWN,\n NOT_LOGGED_IN,\n LOGGED_IN,\n}\n\nenum ScreenSize {\n LARGE,\n SMALL,\n}\n\n/** Menus and dialogs state. */\ninterface State {\n loadUrlDialogOpen: boolean;\n wikiTreeIdDialogOpen: boolean;\n url?: string;\n wikiTreeId?: 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 data?: JsonGedcomData;\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 additional WikiTree menus. */\n showWikiTreeMenus: 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 wikiTreeIdDialogOpen: 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 wikiTreeIdInputRef: 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 private openWikiTreeIdDialog() {\n this.setState(\n Object.assign({}, this.state, {wikiTreeIdDialogOpen: true}),\n () => this.wikiTreeIdInputRef.current!.focus(),\n );\n }\n\n /** Cancels any of the open dialogs. */\n private handleClose() {\n this.setState(\n Object.assign({}, this.state, {\n loadUrlDialogOpen: false,\n wikiTreeIdDialogOpen: false,\n }),\n );\n }\n\n /** Load 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 /** Select button clicked in the \"Select WikiTree ID\" dialog. */\n private handleSelectWikiTreeId() {\n this.setState(\n Object.assign({}, this.state, {\n wikiTreeIdDialogOpen: false,\n }),\n );\n if (this.state.wikiTreeId) {\n analyticsEvent('wikitree_id_selected');\n const search = queryString.parse(this.props.location.search);\n const standalone =\n search.standalone !== undefined ? search.standalone : true;\n this.props.history.push({\n pathname: '/view',\n search: queryString.stringify({\n indi: this.state.wikiTreeId,\n source: 'wikitree',\n standalone,\n }),\n });\n }\n }\n\n /** Called when the URL input is typed into. */\n private handleUrlChange(value: string) {\n this.setState(\n Object.assign({}, this.state, {\n url: value,\n }),\n );\n }\n\n /** Called when the URL input is typed into. */\n private handleWikiTreeIdChange(value: string) {\n this.setState(\n Object.assign({}, this.state, {\n wikiTreeId: 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.data) {\n this.searchIndex = buildSearchIndex(this.props.data);\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 wikiTreeLoginUsername = getLoggedInUserName();\n const wikiTreeLoginState = wikiTreeLoginUsername\n ? WikiTreeLoginState.LOGGED_IN\n : WikiTreeLoginState.NOT_LOGGED_IN;\n if (this.state.wikiTreeLoginState !== wikiTreeLoginState) {\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.data !== this.props.data) {\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(data.value)}\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 enterWikiTreeId(event: React.MouseEvent, id: string) {\n event.preventDefault(); // Do not follow link in href.\n ((this.wikiTreeIdInputRef.current as unknown) as {\n inputRef: HTMLInputElement;\n }).inputRef.value = id;\n this.handleWikiTreeIdChange(id);\n this.wikiTreeIdInputRef.current!.focus();\n }\n\n private wikiTreeIdModal() {\n return (\n this.handleClose()}\n centered={false}\n >\n
\n \n txt}\n />\n
\n \n
this.handleSelectWikiTreeId()}>\n

\n \n WikiTree\n \n ),\n example1: (\n this.enterWikiTreeId(e, 'Wojtyla-13')}\n className=\"link-span\"\n >\n Wojtyla-13\n \n ),\n example2: (\n this.enterWikiTreeId(e, 'Skłodowska-2')}\n className=\"link-span\"\n >\n Skłodowska-2\n \n ),\n }}\n />\n

\n this.handleWikiTreeIdChange(data.value)}\n ref={this.wikiTreeIdInputRef}\n />\n \n
\n \n \n \n \n \n );\n }\n\n private search() {\n return (\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 id=\"search\"\n />\n );\n }\n\n private chartMenus(screenSize: ScreenSize) {\n if (!this.props.showingChart) {\n return null;\n }\n const chartTypeItems = (\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 switch (screenSize) {\n case ScreenSize.LARGE:\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 {chartTypeItems}\n \n {this.search()}\n \n );\n\n case ScreenSize.SMALL:\n return (\n <>\n this.props.eventHandlers.onPrint()}>\n \n \n \n\n \n\n this.props.eventHandlers.onDownloadPdf()}\n >\n \n \n \n this.props.eventHandlers.onDownloadPng()}\n >\n \n \n \n this.props.eventHandlers.onDownloadSvg()}\n >\n \n \n \n\n \n {chartTypeItems}\n \n \n );\n }\n }\n\n private title() {\n return (\n \n Topola Genealogy\n \n );\n }\n\n private fileMenus(screenSize: ScreenSize) {\n const loadWikiTreeItem = (\n <>\n \n \n \n );\n\n // In standalone WikiTree mode, show only the \"Select WikiTree ID\" menu.\n if (!this.props.standalone && this.props.showWikiTreeMenus) {\n switch (screenSize) {\n case ScreenSize.LARGE:\n return (\n <>\n this.openWikiTreeIdDialog()}>\n {loadWikiTreeItem}\n \n {this.wikiTreeIdModal()}\n \n );\n case ScreenSize.SMALL:\n return (\n <>\n this.openWikiTreeIdDialog()}>\n {loadWikiTreeItem}\n \n \n {this.wikiTreeIdModal()}\n \n );\n }\n }\n\n // Don't show \"open\" menus in non-standalone mode.\n if (!this.props.standalone) {\n return null;\n }\n\n const openFileItem = (\n <>\n \n \n \n );\n const loadUrlItem = (\n <>\n \n \n \n );\n const commonElements = (\n <>\n {this.loadFromUrlModal()}\n {this.wikiTreeIdModal()}\n this.handleUpload(e)}\n />\n \n );\n switch (screenSize) {\n case ScreenSize.LARGE:\n // Show dropdown if chart is shown, otherwise show individual menu\n // items.\n const menus = this.props.showingChart ? (\n \n \n \n \n }\n className=\"item\"\n >\n \n \n {openFileItem}\n \n this.openLoadUrlDialog()}>\n {loadUrlItem}\n \n this.openWikiTreeIdDialog()}>\n {loadWikiTreeItem}\n \n \n \n ) : (\n <>\n \n this.openLoadUrlDialog()}>\n {loadUrlItem}\n \n this.openWikiTreeIdDialog()}>\n {loadWikiTreeItem}\n \n \n );\n return (\n <>\n {menus}\n {commonElements}\n \n );\n\n case ScreenSize.SMALL:\n return (\n <>\n \n {openFileItem}\n \n this.openLoadUrlDialog()}>\n {loadUrlItem}\n \n this.openWikiTreeIdDialog()}>\n {loadWikiTreeItem}\n \n \n {commonElements}\n \n );\n }\n }\n\n private wikiTreeLoginMenu(screenSize: ScreenSize) {\n if (!this.props.showWikiTreeMenus) {\n return null;\n }\n switch (this.state.wikiTreeLoginState) {\n case WikiTreeLoginState.NOT_LOGGED_IN:\n const loginForm = (\n \n \n \n \n );\n switch (screenSize) {\n case ScreenSize.LARGE:\n return (\n this.wikiTreeLogin()}>\n \n \n {loginForm}\n \n );\n\n case ScreenSize.SMALL:\n return (\n <>\n this.wikiTreeLogin()}>\n \n \n {loginForm}\n \n \n \n );\n }\n break;\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 switch (screenSize) {\n case ScreenSize.LARGE:\n return (\n \n \n \n \n );\n\n case ScreenSize.SMALL:\n return (\n <>\n \n \n \n \n \n \n );\n\n default:\n return null;\n }\n }\n }\n\n private mobileMenus() {\n return (\n <>\n \n \n \n }\n className=\"item\"\n icon={null}\n >\n \n {this.fileMenus(ScreenSize.SMALL)}\n {this.chartMenus(ScreenSize.SMALL)}\n {this.wikiTreeLoginMenu(ScreenSize.SMALL)}\n\n \n \n \n \n \n {this.props.standalone ? (\n {this.title()}\n ) : (\n this.title()\n )}\n \n );\n }\n\n private desktopMenus() {\n return (\n <>\n {this.props.standalone ? {this.title()} : null}\n {this.fileMenus(ScreenSize.LARGE)}\n {this.chartMenus(ScreenSize.LARGE)}\n \n {this.wikiTreeLoginMenu(ScreenSize.LARGE)}\n \n \n \n \n \n );\n }\n\n render() {\n return (\n <>\n \n {this.desktopMenus()}\n \n \n {this.mobileMenus()}\n \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, InjectedIntl} 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, PRIVATE_ID_PREFIX} 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 constructor(private intl: InjectedIntl) {}\n\n isNewData(args: Arguments, state: State): boolean {\n if (state.selection && state.selection.id === args.indi) {\n // Selection unchanged -> don't reload.\n return false;\n }\n if (\n state.data &&\n state.data.chartData.indis.some((indi) => indi.id === args.indi)\n ) {\n // New selection exists in current view -> animate instead of reloading.\n return false;\n }\n return true;\n }\n\n async loadData(args: Arguments): Promise {\n try {\n const data = await loadWikiTree(args.indi!, this.intl, 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/** 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 freezeAnimation?: 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 freezeAnimation: getParam('freeze') === 'true', // False by default\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 };\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 /** Freeze animations after initial chart render. */\n freezeAnimation?: 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 };\n chartRef: Chart | null = null;\n\n /** Make intl appear in this.context. */\n static contextTypes = {\n intl: intlShape,\n };\n\n /** Mapping from data source identifier to data source handler functions. */\n private readonly dataSources = new Map([\n [DataSourceEnum.UPLOADED, new UploadedDataSource()],\n [DataSourceEnum.GEDCOM_URL, new GedcomUrlDataSource()],\n [DataSourceEnum.WIKITREE, new WikiTreeDataSource(this.context.intl)],\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 = this.dataSources.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: {id: args.indi},\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 }),\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 freezeAnimation: args.freezeAnimation,\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 try {\n const data = await loadWikiTree(args.indi!, this.context.intl);\n const selection = getSelection(\n data.chartData,\n args.indi,\n args.generation,\n );\n this.setState(\n Object.assign({}, this.state, {\n data,\n hash: args.hash,\n selection,\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 loadingMore: false,\n }),\n );\n } catch (error) {\n this.showErrorPopup(\n this.context.intl.formatMessage(\n {\n id: 'error.failed_wikitree_load_more',\n defaultMessage: 'Failed to load data from WikiTree. {error}',\n },\n {error},\n ),\n {\n loadingMore: false,\n },\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 // Don't allow selecting WikiTree private profiles.\n if (selection.id.startsWith(PRIVATE_ID_PREFIX)) {\n return;\n }\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, otherStateChanges?: Partial) {\n this.setState(\n Object.assign(\n {},\n this.state,\n {\n showErrorPopup: true,\n error: message,\n },\n otherStateChanges,\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 />\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","module.exports = __webpack_public_path__ + \"static/media/wikitree.1dee3d66.png\";"],"sourceRoot":""} \ No newline at end of file