OSDN Git Service

[feature]人気のある種族・職業・性格・魔法領域のページを再実装
authorHabu <habu@users.sourceforge.jp>
Wed, 18 Apr 2018 10:59:52 +0000 (19:59 +0900)
committerHabu <habu@users.sourceforge.jp>
Fri, 20 Apr 2018 13:09:16 +0000 (22:09 +0900)
TypeScript + React による再実装
ソート機能も自前で実装した

18 files changed:
.eslintrc.json [new file with mode: 0644]
.gitignore
package.json [new file with mode: 0644]
score/.htaccess
score/css/score-table.css
score/get_popularity_ranking.php [new file with mode: 0644]
score/jquery.tablesorter.min.js [deleted file]
score/js/.htaccess [moved from score/tablesorter-theme/.htaccess with 59% similarity]
score/popularity_ranking.js [deleted file]
score/popularity_ranking.php
score/src/popurality_ranking.tsx [new file with mode: 0644]
score/tablesorter-theme/asc.gif [deleted file]
score/tablesorter-theme/bg.gif [deleted file]
score/tablesorter-theme/desc.gif [deleted file]
score/tablesorter-theme/style.css [deleted file]
tsconfig.json [new file with mode: 0644]
tslint.json [new file with mode: 0644]
webpack.config.js [new file with mode: 0644]

diff --git a/.eslintrc.json b/.eslintrc.json
new file mode 100644 (file)
index 0000000..160ebb0
--- /dev/null
@@ -0,0 +1,37 @@
+{
+    "env": {
+        "commonjs": true,
+        "browser": true,
+        "es6": true,
+        "jquery": true
+    },
+    "extends": ["eslint:recommended", "plugin:react/recommended"],
+    "parserOptions": {
+        "ecmaFeatures": {
+            "experimentalObjectRestSpread": true,
+            "jsx": true
+        },
+        "sourceType": "module"
+    },
+    "plugins": [
+        "react"
+    ],
+    "rules": {
+        "indent": [
+            "error",
+            4
+        ],
+        "linebreak-style": [
+            "error",
+            "unix"
+        ],
+        "quotes": [
+            "error",
+            "double"
+        ],
+        "semi": [
+            "error",
+            "always"
+        ]
+    }
+}
index f9ea237..ae26cc2 100644 (file)
@@ -1,3 +1,6 @@
 web
 node_modules
 .vscode
 web
 node_modules
 .vscode
+bundle.js
+*.bundle.js
+*.map
diff --git a/package.json b/package.json
new file mode 100644 (file)
index 0000000..0939220
--- /dev/null
@@ -0,0 +1,38 @@
+{
+  "name": "hengband-web",
+  "version": "1.0.0",
+  "description": "",
+  "main": "webpack.config.js",
+  "scripts": {
+    "build": "webpack --mode production",
+    "dev": "webpack --mode development",
+    "watch": "webpack --watch --mode development",
+    "test": "echo \"Error: no test specified\" && exit 1"
+  },
+  "repository": {
+    "type": "git",
+    "url": "habu@git.osdn.net:/gitroot/hengband/web.git"
+  },
+  "keywords": [],
+  "author": "",
+  "license": "ISC",
+  "devDependencies": {
+    "awesome-typescript-loader": "^5.0.0",
+    "eslint": "^4.19.1",
+    "eslint-plugin-react": "^7.7.0",
+    "prop-types": "^15.6.1",
+    "source-map-loader": "^0.2.3",
+    "tslint": "^5.9.1",
+    "typescript": "^2.8.1",
+    "webpack": "^4.6.0",
+    "webpack-cli": "^2.0.14"
+  },
+  "dependencies": {
+    "@types/jquery": "^3.3.1",
+    "@types/react": "^16.3.11",
+    "@types/react-dom": "^16.0.5",
+    "jquery": "^3.3.1",
+    "react": "^16.3.2",
+    "react-dom": "^16.3.2"
+  }
+}
index 6f72228..c13a458 100644 (file)
@@ -1,5 +1,5 @@
 deny from all
 
 deny from all
 
-<Files ~ "(\.php|\.js)$">
+<Files ~ "\.php$">
 allow from all
 </Files>
 allow from all
 </Files>
index cc50954..749a851 100644 (file)
-table.score
-{
-    width: 100%;
+table.score {
+       width: 100%;
 }
 
 table.score thead tr th,
 }
 
 table.score thead tr th,
-table.score tfoot tr th
-{
-         background-color: #302010;
-         border: 1px solid #d27d00;
-         padding: 4px;
+table.score tfoot tr th {
+       background-color: #302010;
+       border: 1px solid #d27d00;
+       padding: 4px;
 }
 
 }
 
-table.score tbody td
-{
-         color: black;
-         padding: 4px;
-         background-color: #e9967a;
-         vertical-align: top;
+table.score tbody td {
+       color: black;
+       padding: 4px;
+       background-color: #e9967a;
+       vertical-align: top;
 }
 
 }
 
-table.score tbody td.rank
-{
+table.score tbody td.rank {
        text-align: center;
        vertical-align: middle;
 }
 
        text-align: center;
        vertical-align: middle;
 }
 
-table.score tbody td.player_name a span
-{
+table.score tbody td.player_name a span {
        text-decoration: underline;
 }
 
 table.score tbody td.player_name span,
        text-decoration: underline;
 }
 
 table.score tbody td.player_name span,
-table.score tbody td.class_name span
-{
+table.score tbody td.class_name span {
        white-space: nowrap;
        display: inline-block;
 }
 
        white-space: nowrap;
        display: inline-block;
 }
 
-table.score tbody td.race_name
-{
+table.score tbody td.race_name {
        white-space: nowrap;
 }
 
        white-space: nowrap;
 }
 
-table.score tbody td.sex
-{
+table.score tbody td.sex {
        text-align: center;
 }
 
 table.two_rows tbody tr:nth-child(4n+1) td,
        text-align: center;
 }
 
 table.two_rows tbody tr:nth-child(4n+1) td,
-table.two_rows tbody tr:nth-child(4n+2) td
-{
-         background-color: #f9b69a;
+table.two_rows tbody tr:nth-child(4n+2) td {
+       background-color: #f9b69a;
 }
 
 }
 
-table.one_row tbody tr:nth-child(odd) td
-{
-         background-color: #f9b69a;
+table.one_row tbody tr:nth-child(odd) td {
+       background-color: #f9b69a;
 }
 
 }
 
-table.score tbody td.number
-{
-         text-align: right;
+table.score tbody td.number {
+       text-align: right;
 }
 
 }
 
-table.score tbody td a:link
-{
-    color: black;
+table.score tbody td a:link {
+       color: black;
 }
 }
+
 table.score tbody td a:visited {
 table.score tbody td a:visited {
-    color: gray;
+       color: gray;
 }
 }
+
 table.score tbody td a:hover {
 table.score tbody td a:hover {
-    color: red;
+       color: red;
+}
+
+table.statistics_table th.sort {
+       cursor: pointer;
+}
+
+table.statistics_table th.sort:after {
+       content: '';
+       float: right;
+       margin-top: 7px;
+       border-width: 4px 4px 0;
+       border-style: solid;
+       border-color: #f9b69a transparent;
+       visibility: hidden;
+       opacity: 0;
+       -ms-user-select: none;
+       -webkit-user-select: none;
+       -moz-user-select: none;
+       user-select: none;
+}
+
+table.statistics_table th.sort.ascend:after {
+
+       border-width: 0 4px 4px;
+}
+
+table.statistics_table th.sort.ascend:after,
+table.statistics_table th.sort.descend:after {
+       visibility: visible;
+       opacity: 0.6;
 }
 
 }
 
-table.statistics_table
-{
-    display: none;
+table.statistics_table th.sort:hover:after {
+       visibility: visible;
+       opacity: 1;
 }
 }
diff --git a/score/get_popularity_ranking.php b/score/get_popularity_ranking.php
new file mode 100644 (file)
index 0000000..27e42b6
--- /dev/null
@@ -0,0 +1,20 @@
+<?php
+//ini_set('display_errors', 'On');
+
+ini_set('log_errors', 'On');
+ini_set('error_log', 'errors/'.pathinfo(__FILE__, PATHINFO_FILENAME).'.log');
+
+ini_set('zlib.output_compression', 'On');
+
+require_once "db_common.inc";
+require_once "web_template.inc";
+
+$db = new ScoreDB();
+
+$time_start = microtime(true);
+
+$statistics = $db->get_statistics_tables('total_count');
+
+$query_time = microtime(true) - $time_start;
+
+echo json_encode($statistics);
diff --git a/score/jquery.tablesorter.min.js b/score/jquery.tablesorter.min.js
deleted file mode 100644 (file)
index b8605df..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-
-(function($){$.extend({tablesorter:new
-function(){var parsers=[],widgets=[];this.defaults={cssHeader:"header",cssAsc:"headerSortUp",cssDesc:"headerSortDown",cssChildRow:"expand-child",sortInitialOrder:"asc",sortMultiSortKey:"shiftKey",sortForce:null,sortAppend:null,sortLocaleCompare:true,textExtraction:"simple",parsers:{},widgets:[],widgetZebra:{css:["even","odd"]},headers:{},widthFixed:false,cancelSelection:true,sortList:[],headerList:[],dateFormat:"us",decimal:'/\.|\,/g',onRenderHeader:null,selectorHeaders:'thead th',debug:false};function benchmark(s,d){log(s+","+(new Date().getTime()-d.getTime())+"ms");}this.benchmark=benchmark;function log(s){if(typeof console!="undefined"&&typeof console.debug!="undefined"){console.log(s);}else{alert(s);}}function buildParserCache(table,$headers){if(table.config.debug){var parsersDebug="";}if(table.tBodies.length==0)return;var rows=table.tBodies[0].rows;if(rows[0]){var list=[],cells=rows[0].cells,l=cells.length;for(var i=0;i<l;i++){var p=false;if($.metadata&&($($headers[i]).metadata()&&$($headers[i]).metadata().sorter)){p=getParserById($($headers[i]).metadata().sorter);}else if((table.config.headers[i]&&table.config.headers[i].sorter)){p=getParserById(table.config.headers[i].sorter);}if(!p){p=detectParserForColumn(table,rows,-1,i);}if(table.config.debug){parsersDebug+="column:"+i+" parser:"+p.id+"\n";}list.push(p);}}if(table.config.debug){log(parsersDebug);}return list;};function detectParserForColumn(table,rows,rowIndex,cellIndex){var l=parsers.length,node=false,nodeValue=false,keepLooking=true;while(nodeValue==''&&keepLooking){rowIndex++;if(rows[rowIndex]){node=getNodeFromRowAndCellIndex(rows,rowIndex,cellIndex);nodeValue=trimAndGetNodeText(table.config,node);if(table.config.debug){log('Checking if value was empty on row:'+rowIndex);}}else{keepLooking=false;}}for(var i=1;i<l;i++){if(parsers[i].is(nodeValue,table,node)){return parsers[i];}}return parsers[0];}function getNodeFromRowAndCellIndex(rows,rowIndex,cellIndex){return rows[rowIndex].cells[cellIndex];}function trimAndGetNodeText(config,node){return $.trim(getElementText(config,node));}function getParserById(name){var l=parsers.length;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==name.toLowerCase()){return parsers[i];}}return false;}function buildCache(table){if(table.config.debug){var cacheTime=new Date();}var totalRows=(table.tBodies[0]&&table.tBodies[0].rows.length)||0,totalCells=(table.tBodies[0].rows[0]&&table.tBodies[0].rows[0].cells.length)||0,parsers=table.config.parsers,cache={row:[],normalized:[]};for(var i=0;i<totalRows;++i){var c=$(table.tBodies[0].rows[i]),cols=[];if(c.hasClass(table.config.cssChildRow)){cache.row[cache.row.length-1]=cache.row[cache.row.length-1].add(c);continue;}cache.row.push(c);for(var j=0;j<totalCells;++j){cols.push(parsers[j].format(getElementText(table.config,c[0].cells[j]),table,c[0].cells[j]));}cols.push(cache.normalized.length);cache.normalized.push(cols);cols=null;};if(table.config.debug){benchmark("Building cache for "+totalRows+" rows:",cacheTime);}return cache;};function getElementText(config,node){var text="";if(!node)return"";if(!config.supportsTextContent)config.supportsTextContent=node.textContent||false;if(config.textExtraction=="simple"){if(config.supportsTextContent){text=node.textContent;}else{if(node.childNodes[0]&&node.childNodes[0].hasChildNodes()){text=node.childNodes[0].innerHTML;}else{text=node.innerHTML;}}}else{if(typeof(config.textExtraction)=="function"){text=config.textExtraction(node);}else{text=$(node).text();}}return text;}function appendToTable(table,cache){if(table.config.debug){var appendTime=new Date()}var c=cache,r=c.row,n=c.normalized,totalRows=n.length,checkCell=(n[0].length-1),tableBody=$(table.tBodies[0]),rows=[];for(var i=0;i<totalRows;i++){var pos=n[i][checkCell];rows.push(r[pos]);if(!table.config.appender){var l=r[pos].length;for(var j=0;j<l;j++){tableBody[0].appendChild(r[pos][j]);}}}if(table.config.appender){table.config.appender(table,rows);}rows=null;if(table.config.debug){benchmark("Rebuilt table:",appendTime);}applyWidget(table);setTimeout(function(){$(table).trigger("sortEnd");},0);};function buildHeaders(table){if(table.config.debug){var time=new Date();}var meta=($.metadata)?true:false;var header_index=computeTableHeaderCellIndexes(table);$tableHeaders=$(table.config.selectorHeaders,table).each(function(index){this.column=header_index[this.parentNode.rowIndex+"-"+this.cellIndex];this.order=formatSortingOrder(table.config.sortInitialOrder);this.count=this.order;if(checkHeaderMetadata(this)||checkHeaderOptions(table,index))this.sortDisabled=true;if(checkHeaderOptionsSortingLocked(table,index))this.order=this.lockedOrder=checkHeaderOptionsSortingLocked(table,index);if(!this.sortDisabled){var $th=$(this).addClass(table.config.cssHeader);if(table.config.onRenderHeader)table.config.onRenderHeader.apply($th);}table.config.headerList[index]=this;});if(table.config.debug){benchmark("Built headers:",time);log($tableHeaders);}return $tableHeaders;};function computeTableHeaderCellIndexes(t){var matrix=[];var lookup={};var thead=t.getElementsByTagName('THEAD')[0];var trs=thead.getElementsByTagName('TR');for(var i=0;i<trs.length;i++){var cells=trs[i].cells;for(var j=0;j<cells.length;j++){var c=cells[j];var rowIndex=c.parentNode.rowIndex;var cellId=rowIndex+"-"+c.cellIndex;var rowSpan=c.rowSpan||1;var colSpan=c.colSpan||1
-var firstAvailCol;if(typeof(matrix[rowIndex])=="undefined"){matrix[rowIndex]=[];}for(var k=0;k<matrix[rowIndex].length+1;k++){if(typeof(matrix[rowIndex][k])=="undefined"){firstAvailCol=k;break;}}lookup[cellId]=firstAvailCol;for(var k=rowIndex;k<rowIndex+rowSpan;k++){if(typeof(matrix[k])=="undefined"){matrix[k]=[];}var matrixrow=matrix[k];for(var l=firstAvailCol;l<firstAvailCol+colSpan;l++){matrixrow[l]="x";}}}}return lookup;}function checkCellColSpan(table,rows,row){var arr=[],r=table.tHead.rows,c=r[row].cells;for(var i=0;i<c.length;i++){var cell=c[i];if(cell.colSpan>1){arr=arr.concat(checkCellColSpan(table,headerArr,row++));}else{if(table.tHead.length==1||(cell.rowSpan>1||!r[row+1])){arr.push(cell);}}}return arr;};function checkHeaderMetadata(cell){if(($.metadata)&&($(cell).metadata().sorter===false)){return true;};return false;}function checkHeaderOptions(table,i){if((table.config.headers[i])&&(table.config.headers[i].sorter===false)){return true;};return false;}function checkHeaderOptionsSortingLocked(table,i){if((table.config.headers[i])&&(table.config.headers[i].lockedOrder))return table.config.headers[i].lockedOrder;return false;}function applyWidget(table){var c=table.config.widgets;var l=c.length;for(var i=0;i<l;i++){getWidgetById(c[i]).format(table);}}function getWidgetById(name){var l=widgets.length;for(var i=0;i<l;i++){if(widgets[i].id.toLowerCase()==name.toLowerCase()){return widgets[i];}}};function formatSortingOrder(v){if(typeof(v)!="Number"){return(v.toLowerCase()=="desc")?1:0;}else{return(v==1)?1:0;}}function isValueInArray(v,a){var l=a.length;for(var i=0;i<l;i++){if(a[i][0]==v){return true;}}return false;}function setHeadersCss(table,$headers,list,css){$headers.removeClass(css[0]).removeClass(css[1]);var h=[];$headers.each(function(offset){if(!this.sortDisabled){h[this.column]=$(this);}});var l=list.length;for(var i=0;i<l;i++){h[list[i][0]].addClass(css[list[i][1]]);}}function fixColumnWidth(table,$headers){var c=table.config;if(c.widthFixed){var colgroup=$('<colgroup>');$("tr:first td",table.tBodies[0]).each(function(){colgroup.append($('<col>').css('width',$(this).width()));});$(table).prepend(colgroup);};}function updateHeaderSortCount(table,sortList){var c=table.config,l=sortList.length;for(var i=0;i<l;i++){var s=sortList[i],o=c.headerList[s[0]];o.count=s[1];o.count++;}}function multisort(table,sortList,cache){if(table.config.debug){var sortTime=new Date();}var dynamicExp="var sortWrapper = function(a,b) {",l=sortList.length;for(var i=0;i<l;i++){var c=sortList[i][0];var order=sortList[i][1];var s=(table.config.parsers[c].type=="text")?((order==0)?makeSortFunction("text","asc",c):makeSortFunction("text","desc",c)):((order==0)?makeSortFunction("numeric","asc",c):makeSortFunction("numeric","desc",c));var e="e"+i;dynamicExp+="var "+e+" = "+s;dynamicExp+="if("+e+") { return "+e+"; } ";dynamicExp+="else { ";}var orgOrderCol=cache.normalized[0].length-1;dynamicExp+="return a["+orgOrderCol+"]-b["+orgOrderCol+"];";for(var i=0;i<l;i++){dynamicExp+="}; ";}dynamicExp+="return 0; ";dynamicExp+="}; ";if(table.config.debug){benchmark("Evaling expression:"+dynamicExp,new Date());}eval(dynamicExp);cache.normalized.sort(sortWrapper);if(table.config.debug){benchmark("Sorting on "+sortList.toString()+" and dir "+order+" time:",sortTime);}return cache;};function makeSortFunction(type,direction,index){var a="a["+index+"]",b="b["+index+"]";if(type=='text'&&direction=='asc'){return"("+a+" == "+b+" ? 0 : ("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : ("+a+" < "+b+") ? -1 : 1 )));";}else if(type=='text'&&direction=='desc'){return"("+a+" == "+b+" ? 0 : ("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : ("+b+" < "+a+") ? -1 : 1 )));";}else if(type=='numeric'&&direction=='asc'){return"("+a+" === null && "+b+" === null) ? 0 :("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : "+a+" - "+b+"));";}else if(type=='numeric'&&direction=='desc'){return"("+a+" === null && "+b+" === null) ? 0 :("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : "+b+" - "+a+"));";}};function makeSortText(i){return"((a["+i+"] < b["+i+"]) ? -1 : ((a["+i+"] > b["+i+"]) ? 1 : 0));";};function makeSortTextDesc(i){return"((b["+i+"] < a["+i+"]) ? -1 : ((b["+i+"] > a["+i+"]) ? 1 : 0));";};function makeSortNumeric(i){return"a["+i+"]-b["+i+"];";};function makeSortNumericDesc(i){return"b["+i+"]-a["+i+"];";};function sortText(a,b){if(table.config.sortLocaleCompare)return a.localeCompare(b);return((a<b)?-1:((a>b)?1:0));};function sortTextDesc(a,b){if(table.config.sortLocaleCompare)return b.localeCompare(a);return((b<a)?-1:((b>a)?1:0));};function sortNumeric(a,b){return a-b;};function sortNumericDesc(a,b){return b-a;};function getCachedSortType(parsers,i){return parsers[i].type;};this.construct=function(settings){return this.each(function(){if(!this.tHead||!this.tBodies)return;var $this,$document,$headers,cache,config,shiftDown=0,sortOrder;this.config={};config=$.extend(this.config,$.tablesorter.defaults,settings);$this=$(this);$.data(this,"tablesorter",config);$headers=buildHeaders(this);this.config.parsers=buildParserCache(this,$headers);cache=buildCache(this);var sortCSS=[config.cssDesc,config.cssAsc];fixColumnWidth(this);$headers.click(function(e){var totalRows=($this[0].tBodies[0]&&$this[0].tBodies[0].rows.length)||0;if(!this.sortDisabled&&totalRows>0){$this.trigger("sortStart");var $cell=$(this);var i=this.column;this.order=this.count++%2;if(this.lockedOrder)this.order=this.lockedOrder;if(!e[config.sortMultiSortKey]){config.sortList=[];if(config.sortForce!=null){var a=config.sortForce;for(var j=0;j<a.length;j++){if(a[j][0]!=i){config.sortList.push(a[j]);}}}config.sortList.push([i,this.order]);}else{if(isValueInArray(i,config.sortList)){for(var j=0;j<config.sortList.length;j++){var s=config.sortList[j],o=config.headerList[s[0]];if(s[0]==i){o.count=s[1];o.count++;s[1]=o.count%2;}}}else{config.sortList.push([i,this.order]);}};setTimeout(function(){setHeadersCss($this[0],$headers,config.sortList,sortCSS);appendToTable($this[0],multisort($this[0],config.sortList,cache));},1);return false;}}).mousedown(function(){if(config.cancelSelection){this.onselectstart=function(){return false};return false;}});$this.bind("update",function(){var me=this;setTimeout(function(){me.config.parsers=buildParserCache(me,$headers);cache=buildCache(me);},1);}).bind("updateCell",function(e,cell){var config=this.config;var pos=[(cell.parentNode.rowIndex-1),cell.cellIndex];cache.normalized[pos[0]][pos[1]]=config.parsers[pos[1]].format(getElementText(config,cell),cell);}).bind("sorton",function(e,list){$(this).trigger("sortStart");config.sortList=list;var sortList=config.sortList;updateHeaderSortCount(this,sortList);setHeadersCss(this,$headers,sortList,sortCSS);appendToTable(this,multisort(this,sortList,cache));}).bind("appendCache",function(){appendToTable(this,cache);}).bind("applyWidgetId",function(e,id){getWidgetById(id).format(this);}).bind("applyWidgets",function(){applyWidget(this);});if($.metadata&&($(this).metadata()&&$(this).metadata().sortlist)){config.sortList=$(this).metadata().sortlist;}if(config.sortList.length>0){$this.trigger("sorton",[config.sortList]);}applyWidget(this);});};this.addParser=function(parser){var l=parsers.length,a=true;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==parser.id.toLowerCase()){a=false;}}if(a){parsers.push(parser);};};this.addWidget=function(widget){widgets.push(widget);};this.formatFloat=function(s){var i=parseFloat(s);return(isNaN(i))?0:i;};this.formatInt=function(s){var i=parseInt(s);return(isNaN(i))?0:i;};this.isDigit=function(s,config){return/^[-+]?\d*$/.test($.trim(s.replace(/[,.']/g,'')));};this.clearTableBody=function(table){if($.browser.msie){function empty(){while(this.firstChild)this.removeChild(this.firstChild);}empty.apply(table.tBodies[0]);}else{table.tBodies[0].innerHTML="";}};}});$.fn.extend({tablesorter:$.tablesorter.construct});var ts=$.tablesorter;ts.addParser({id:"text",is:function(s){return true;},format:function(s){return $.trim(s.toLocaleLowerCase());},type:"text"});ts.addParser({id:"digit",is:function(s,table){var c=table.config;return $.tablesorter.isDigit(s,c);},format:function(s){return $.tablesorter.formatFloat(s);},type:"numeric"});ts.addParser({id:"currency",is:function(s){return/^[£$€?.]/.test(s);},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/[£$€]/g),""));},type:"numeric"});ts.addParser({id:"ipAddress",is:function(s){return/^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);},format:function(s){var a=s.split("."),r="",l=a.length;for(var i=0;i<l;i++){var item=a[i];if(item.length==2){r+="0"+item;}else{r+=item;}}return $.tablesorter.formatFloat(r);},type:"numeric"});ts.addParser({id:"url",is:function(s){return/^(https?|ftp|file):\/\/$/.test(s);},format:function(s){return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//),''));},type:"text"});ts.addParser({id:"isoDate",is:function(s){return/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);},format:function(s){return $.tablesorter.formatFloat((s!="")?new Date(s.replace(new RegExp(/-/g),"/")).getTime():"0");},type:"numeric"});ts.addParser({id:"percent",is:function(s){return/\%$/.test($.trim(s));},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g),""));},type:"numeric"});ts.addParser({id:"usLongDate",is:function(s){return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/));},format:function(s){return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"shortDate",is:function(s){return/\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);},format:function(s,table){var c=table.config;s=s.replace(/\-/g,"/");if(c.dateFormat=="us"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$1/$2");}else if(c.dateFormat=="uk"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$2/$1");}else if(c.dateFormat=="dd/mm/yy"||c.dateFormat=="dd-mm-yy"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/,"$1/$2/$3");}return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"time",is:function(s){return/^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);},format:function(s){return $.tablesorter.formatFloat(new Date("2000/01/01 "+s).getTime());},type:"numeric"});ts.addParser({id:"metadata",is:function(s){return false;},format:function(s,table,cell){var c=table.config,p=(!c.parserMetadataName)?'sortValue':c.parserMetadataName;return $(cell).metadata()[p];},type:"numeric"});ts.addWidget({id:"zebra",format:function(table){if(table.config.debug){var time=new Date();}var $tr,row=-1,odd;$("tr:visible",table.tBodies[0]).each(function(i){$tr=$(this);if(!$tr.hasClass(table.config.cssChildRow))row++;odd=(row%2==0);$tr.removeClass(table.config.widgetZebra.css[odd?0:1]).addClass(table.config.widgetZebra.css[odd?1:0])});if(table.config.debug){$.tablesorter.benchmark("Applying Zebra widget",time);}}});})(jQuery);
\ No newline at end of file
similarity index 59%
rename from score/tablesorter-theme/.htaccess
rename to score/js/.htaccess
index c52e0e3..ecf32d3 100644 (file)
@@ -1,5 +1,5 @@
 deny from all
 
 deny from all
 
-<Files ~ "(\.gif|\.css)$">
+<Files ~ "\.js$">
 allow from all
 </Files>
 allow from all
 </Files>
diff --git a/score/popularity_ranking.js b/score/popularity_ranking.js
deleted file mode 100644 (file)
index e4af128..0000000
+++ /dev/null
@@ -1,57 +0,0 @@
-function storageAvailable(type) {
-         try {
-                   var storage = window[type],
-                             x = '__storage_test__';
-                   storage.setItem(x, x);
-                   storage.removeItem(x);
-                   return true;
-         }
-    catch(e) {
-        return e instanceof DOMException && (
-            // everything except Firefox
-            e.code === 22 ||
-                // Firefox
-                e.code === 1014 ||
-                // test name field too, because code might not be present
-                // everything except Firefox
-                e.name === 'QuotaExceededError' ||
-                // Firefox
-                e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
-            // acknowledge QuotaExceededError only if there's something already stored
-            storage.length !== 0;
-    }
-}
-
-function select_table(table_id)
-{
-    if (table_id === null) {
-        if (storageAvailable('sessionStorage')) {
-            table_id = sessionStorage.getItem('selected_table');
-        }
-        table_id = table_id ? table_id : "race_id";
-    }
-
-    $("table.statistics_table").hide();
-    $("div#" + table_id + " table.statistics_table").show();
-
-    $("a.table_select").css('font-weight', 'normal').css('font-size', 'small');
-    $("a.table_select#" + table_id).css('font-weight', 'bold').css('font-size', 'large');
-
-    if (storageAvailable('sessionStorage')) {
-        sessionStorage.setItem('selected_table', table_id);
-    }
-}
-
-$(function(){
-    $(".tablesorter").tablesorter({
-        sortList: [[1, 1]],
-        headers: {
-            0: {sorter: false}
-        }
-    });
-    $(".table_select").on('click', function() {
-        select_table($(this).attr("id"));
-    });
-
-    select_table(null);
-});
index 0fb402a..71cbb8c 100644 (file)
@@ -6,157 +6,28 @@ ini_set('error_log', 'errors/'.pathinfo(__FILE__, PATHINFO_FILENAME).'.log');
 
 ini_set('zlib.output_compression', 'On');
 
 
 ini_set('zlib.output_compression', 'On');
 
-require_once "db_common.inc";
 require_once "web_template.inc";
 
 require_once "web_template.inc";
 
-function print_popularity_table($fp, $stat, $id_name, $name)
-{
-    fwrite(
-        $fp,
-        <<<EOM
-<div id="{$id_name}">
-<table class="tablesorter score statistics_table one_row">
-<thead>
-<tr>
-<th>$name</th>
-
-EOM
-    );
-
-    foreach ([
-        '計', '男性', '女性', '勝利', '平均スコア', '最大スコア',
-    ] as $name) {
-        fwrite($fp, "<th>${name}</th>\n");
-    }
-    fwrite($fp, "</tr>\n".
-           "</thead>\n");
-
-    foreach ($stat as $k => $s) {
-        $name_link = "<a href='score_ranking.php?{$id_name}={$s['id']}'>{$s['name']}</a></td>";
-        fwrite(
-            $fp,
-            <<<EOM
-<tr>
-<td>$name_link</td>
-<td class="number">{$s['total_count']}</td>
-<td class="number">{$s['male_count']}</td>
-<td class="number">{$s['female_count']}</td>
-<td class="number">{$s['winner_count']}</td>
-<td class="number">{$s['average_score']}</td>
-<td class="number">{$s['max_score']}</td>
-</tr>
-
-EOM
-        );
-    }
-
-    fwrite($fp, "</table>\n".
-           "</div>\n");
-}
-
-function print_realm_popularity_table($fp, $stat, $id_name)
-{
-    // 魔法領域の統計を職業ごとにグループ分け
-    $class_ids = array_unique(array_column($stat, "class_id"));
-    $class_realm_stat_list = array_fill_keys($class_ids, []);
-
-    foreach ($stat as $s) {
-        $class_realm_stat_list[intval($s["class_id"])][] = $s;
-    }
-
-    fwrite($fp, "<div id=\"{$id_name}\">");
-
-    // 職業ごとにテーブルを表示
-    foreach ($class_realm_stat_list as $class_id => $class_realm_stat) {
-        if (count($class_realm_stat) <= 1) {
-            continue; // 領域固定の職業は飛ばす
-        }
-
-        $class_name = $class_realm_stat[0]['class_name'];
-
-        fwrite(
-            $fp,
-            <<<EOM
-<table class="tablesorter score statistics_table one_row" id="${id_name}">
-<thead>
-<tr>
-<th>{$class_name}</th>
-
-EOM
-        );
-        foreach ([
-            '計', '男性', '女性', '勝利', '平均スコア', '最大スコア',
-        ] as $th_name) {
-            fwrite($fp, "<th>${th_name}</th>\n");
-        }
-        fwrite($fp, "</tr>\n".
-               "</thead>\n");
-
-        foreach ($class_realm_stat as $realm) {
-            $name_link = "<a href='score_ranking.php?class_id={$class_id}&{$id_name}={$realm['realm_id']}'>{$realm['realm_name']}</a></td>";
-            fwrite(
-                $fp,
-                <<<EOM
-<tr>
-<td>$name_link</td>
-<td class="number">{$realm['total_count']}</td>
-<td class="number">{$realm['male_count']}</td>
-<td class="number">{$realm['female_count']}</td>
-<td class="number">{$realm['winner_count']}</td>
-<td class="number">{$realm['average_score']}</td>
-<td class="number">{$realm['max_score']}</td>
-</tr>
-
-EOM
-            );
-        }
-
-        fwrite($fp, "</table>\n");
-    }
-    fwrite($fp, "</div>\n");
-}
-
-$db = new ScoreDB();
-
-$time_start = microtime(true);
-
-$statistics = $db->get_statistics_tables('total_count');
-
-$query_time = microtime(true) - $time_start;
-
 $wt = new WebTemplate();
 
 $wt->add_head_contents('<meta name="robots" content="none" />');
 $wt->add_head_contents('<link rel="stylesheet" type="text/css" href="css/score-table.css">');
 $wt = new WebTemplate();
 
 $wt->add_head_contents('<meta name="robots" content="none" />');
 $wt->add_head_contents('<link rel="stylesheet" type="text/css" href="css/score-table.css">');
-$wt->add_head_contents('<link rel="stylesheet" type="text/css" href="tablesorter-theme/style.css">');
 $wt->add_head_contents(
     <<<EOM
 $wt->add_head_contents(
     <<<EOM
-<script
-src="https://code.jquery.com/jquery-3.3.1.min.js"
-integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
-crossorigin="anonymous"></script>
+<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
+<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
 EOM
 );
 EOM
 );
-$wt->add_head_contents('<script src="jquery.tablesorter.min.js" type="text/javascript"></script>');
-$wt->add_head_contents('<script src="popularity_ranking.js" type="text/javascript"></script>');
+//$wt->add_head_contents('<script src="react-tutorial/js/bundle.js" type="text/javascript"></script>');
 $wt->set_title("変愚蛮怒 スコアランキング 人気のある種族・職業・性格・魔法領域");
 
 $fp = $wt->main_contents_fp();
 $wt->set_title("変愚蛮怒 スコアランキング 人気のある種族・職業・性格・魔法領域");
 
 $fp = $wt->main_contents_fp();
-fwrite($fp, "<h2>人気のある種族・職業・性格・魔法領域</h2>\n");
-//fprintf($fp, "<small>(%.2f 秒)</small>", $query_time);
 fwrite(
     $fp,
     <<<EOM
 fwrite(
     $fp,
     <<<EOM
-<nobr>[ <a href="javascript:void(0)" class="table_select" id="race_id">種族</a> | <a href="javascript:void(0)" class="table_select" id="class_id">職業</a> | <a href="javascript:void(0)" class="table_select" id="personality_id">性格</a> ] [ <a href="javascript:void(0)" class="table_select" id="realm_id1">魔法領域1</a> | <a href="javascript:void(0)" class="table_select" id="realm_id2">魔法領域2</a> ]</nobr>
-
+<h2>人気のある種族・職業・性格・魔法領域</h2>
+<div id="content"></div>
+<script src="js/popularity_ranking.bundle.js" type="text/javascript"></script>
 EOM
 EOM
-
 );
 );
-
-print_popularity_table($fp, $statistics['race'], 'race_id', "種族");
-print_popularity_table($fp, $statistics['class'], 'class_id', "職業");
-print_popularity_table($fp, $statistics['personality'], 'personality_id', "性格");
-print_realm_popularity_table($fp, $statistics['realm1'], 'realm_id1');
-print_realm_popularity_table($fp, $statistics['realm2'], 'realm_id2');
-
 $wt->print_page();
 $wt->print_page();
diff --git a/score/src/popurality_ranking.tsx b/score/src/popurality_ranking.tsx
new file mode 100644 (file)
index 0000000..e6aa257
--- /dev/null
@@ -0,0 +1,483 @@
+import React from "react";
+import ReactDOM from "react-dom";
+
+const name2j: { [key: string]: string } = {
+    class: "職業",
+    personality: "性格",
+    race: "種族",
+    realm1: "魔法領域1",
+    realm2: "魔法領域2",
+};
+
+const column2j: { [col: string]: string } = {
+    average_score: "平均スコア",
+    female_count: "女性",
+    male_count: "男性",
+    max_score: "最大スコア",
+    total_count: "計",
+    winner_count: "勝利",
+};
+
+const columnOrder = [
+    "total_count",
+    "male_count",
+    "female_count",
+    "winner_count",
+    "average_score",
+    "max_score",
+];
+
+/**
+ * 表示テーブル選択ボタンコンポーネントプロパティ
+ */
+interface ITableSelectButtonProps {
+    /** ボタンが選択状態かどうか */
+    selected: boolean;
+    /** ボタンの銘板 */
+    name: string;
+    /** ボタンがクリックされた時に呼び出されるコールバック関数 */
+    onClick: () => void;
+}
+
+/**
+ * 表示テーブル選択ボタンコンポーネント
+ */
+// tslint:disable-next-line:max-classes-per-file
+class TableSelectButton extends React.Component<ITableSelectButtonProps> {
+    public shouldComponentUpdate(nextProps: ITableSelectButtonProps) {
+        return this.props.selected !== nextProps.selected;
+    }
+
+    public render() {
+        if (this.props.selected) {
+            return (
+                <b>
+                    {name2j[this.props.name]}
+                </b>
+            );
+        } else {
+            return (
+                <a href="javascript:void(0)" onClick={() => this.props.onClick()}>
+                    {name2j[this.props.name]}
+                </a>
+            );
+        }
+    }
+}
+
+/**
+ * 表示テーブル選択コンポーネントプロパティ
+ */
+interface ITableSelectProps {
+    /** 選択中のテーブル名称 */
+    selectedTableName: string;
+    /**
+     * 選択テーブル切替時に呼び出されるコールバック関数
+     * @param name 新たに選択されたテーブル名称
+     */
+    onSelectChange: (name: string) => void;
+}
+
+/**
+ * 表示テーブル選択コンポーネント
+ */
+// tslint:disable-next-line:max-classes-per-file
+class TableSelector extends React.Component<ITableSelectProps> {
+    public render() {
+        return (
+            <div>
+                [ {this.renderSelectButton("race")} | {this.renderSelectButton("class")} |
+                 {this.renderSelectButton("personality")} ]
+                [ {this.renderSelectButton("realm1")} | {this.renderSelectButton("realm2")} ]
+            </div>
+        );
+    }
+
+    private renderSelectButton(name: string) {
+        return <TableSelectButton
+            selected={this.props.selectedTableName === name}
+            name={name}
+            onClick={() => this.props.onSelectChange(name)} />;
+    }
+}
+
+/**
+ * テーブルヘッダコンポーネントプロパティ
+ */
+interface ITableHeaderProps {
+    /** テーブル名称 */
+    tableName: string;
+    /** ソートキーカラム */
+    sortKeyColumn: string;
+    /** ソート順 */
+    sortOrder: SortOrder;
+    /**
+     * ヘッダをクリックした時に呼ばれるコールバック関数
+     * @param clickColumn クリックしたカラムの名称
+     */
+    onClick: (clickColumn: string) => void;
+}
+
+/**
+ * テーブルヘッダコンポーネント
+ */
+function TableHeader(props: ITableHeaderProps) {
+    return (
+        <thead>
+            <tr>
+                <th>{props.tableName}</th>
+                {columnOrder.map((col) => {
+                    let className = "sort";
+                    if (props.sortKeyColumn === col) {
+                        className += " ";
+                        className += (props.sortOrder === SortOrder.Ascend) ? "ascend" : "descend";
+                    }
+                    return (
+                        <th className={className} onClick={() => props.onClick(col)}>
+                            {column2j[col]}
+                        </th>
+                    );
+                })}
+            </tr>
+        </thead>
+    );
+}
+
+/**
+ * テーブル行データコンポーネントプロパティ
+ */
+interface ITableDataRowProps {
+    /** スコアランキングのURLのリンクに渡すパラメータ */
+    linkParam: string;
+    /** 行データの名称(第1カラムに表示される文字列) */
+    rowName: string;
+    /** 行データ */
+    row_data: { [key: string]: string | number };
+}
+
+/**
+ * テーブル行データコンポーネント
+ */
+function TableDataRow(props: ITableDataRowProps) {
+    return (
+        <tr key={props.row_data.id}>
+            <td>
+                <a href={`score_ranking.php?${props.linkParam}`}>
+                    {props.rowName}
+                </a>
+            </td>
+            {columnOrder.map((col) =>
+                <td className="number">{props.row_data[col]}</td>)}
+        </tr>
+    );
+}
+
+/**
+ * ソート順序列挙体
+ */
+enum SortOrder {
+    /** 昇順 */
+    Ascend,
+    /** 降順 */
+    Descend,
+}
+
+/**
+ * 人気データテーブルコンポーネントプロパティ
+ */
+interface IPopuralityTableProps {
+    /** データ内容 */
+    data: Array<{ [col: string]: any }>;
+    /** データ名称 */
+    name: string;
+    /** テーブルの表示/非表示 */
+    visible: boolean;
+}
+
+/**
+ * 人気データテーブルコンポーネントステータス
+ */
+interface IPopuralityTableState {
+    /** データソートのキーとするカラムの名称 */
+    sortKeyColumn: string;
+    /** データソートの順序 */
+    sortOrder: SortOrder;
+}
+
+/**
+ * 人気データテーブルコンポーネント
+ */
+// tslint:disable-next-line:max-classes-per-file
+class PopuralityTable extends React.Component<IPopuralityTableProps, IPopuralityTableState> {
+    constructor(props: IPopuralityTableProps) {
+        super(props);
+        this.state = {
+            sortKeyColumn: columnOrder[0],
+            sortOrder: SortOrder.Descend,
+        };
+    }
+
+    public render() {
+        if (!this.props.visible) {
+            return "";
+        }
+
+        const data = this.get_sorted_data();
+        const tableName = this.props.name;
+        return (
+            <table className="score statistics_table one_row">
+                <TableHeader
+                    tableName={name2j[tableName]}
+                    sortKeyColumn={this.state.sortKeyColumn}
+                    sortOrder={this.state.sortOrder}
+                    onClick={this.selectSortColumn.bind(this)}
+                />
+                <tbody>
+                    {data.map((row) =>
+                        <TableDataRow
+                            linkParam={`${tableName}_id=${row.id}`}
+                            rowName={row.name}
+                            row_data={row}
+                        />)}
+                </tbody>
+            </table>
+        );
+    }
+
+    /**
+     * ソートされたデータを得る
+     * @return ソートされたデータ
+     */
+    protected get_sorted_data() {
+        const sortedData = this.props.data.slice();
+
+        const col = this.state.sortKeyColumn;
+        const order = this.state.sortOrder;
+
+        sortedData.sort((a, b) =>
+            (order === (SortOrder.Ascend) ?
+                a[col] - b[col] : b[col] - a[col]));
+
+        return sortedData;
+    }
+
+    /**
+     * ソートするカラムを選択する
+     * @param column ソートするカラムの名称
+     */
+    protected selectSortColumn(column: string) {
+        let newSortOrder = SortOrder.Descend;
+        if (this.state.sortKeyColumn === column) {
+            newSortOrder =
+                (this.state.sortOrder === SortOrder.Ascend) ?
+                    SortOrder.Descend : SortOrder.Ascend;
+        }
+        this.setState({
+            sortKeyColumn: column,
+            sortOrder: newSortOrder,
+        });
+    }
+}
+
+/**
+ * 人気データテーブルコンポーネント(魔法領域)
+ */
+// tslint:disable-next-line:max-classes-per-file
+class PopuralityRealmTable extends PopuralityTable {
+    public render() {
+        if (!this.props.visible) {
+            return "";
+        }
+
+        const data = this.get_sorted_data();
+        const realm = this.props.name;
+        return (
+            <table className="score statistics_table one_row">
+                <TableHeader
+                    tableName={this.props.data[0].class_name}
+                    sortKeyColumn={this.state.sortKeyColumn}
+                    sortOrder={this.state.sortOrder}
+                    onClick={this.selectSortColumn.bind(this)}
+                />
+                <tbody>
+                    {data.map((row) =>
+                        <TableDataRow
+                            linkParam={`class_id=${row.class_id}&${realm}_id=${row.realm_id}`}
+                            rowName={row.realm_name}
+                            row_data={row}
+                        />)}
+                </tbody>
+            </table>
+        );
+    }
+}
+
+/**
+ * 人気データテーブル全体表示コンポーネントプロパティ
+ */
+interface IRankingTablesProps {
+    /** 表示選択中のテーブル名称 */
+    selectedTableName: string;
+    /** テーブルデータ */
+    data: { [col: string]: any[] };
+}
+
+/**
+ * 人気データテーブル全体表示コンポーネント
+ */
+// tslint:disable-next-line:max-classes-per-file
+class RankingTables extends React.Component<IRankingTablesProps> {
+    public shouldComponentUpdate(nextProps: IRankingTablesProps) {
+        return (this.props.data === null && nextProps.data !== null) ||
+            (this.props.selectedTableName !== nextProps.selectedTableName);
+    }
+
+    public render() {
+        const tables = Object.keys(name2j).map((name) => {
+            if (!name.startsWith("realm")) {
+                return (
+                    <div id={name} key={name}>
+                        <PopuralityTable
+                            data={this.props.data[name]}
+                            visible={this.props.selectedTableName === name}
+                            name={name} />
+                    </div>
+                );
+            } else {
+                const realmTables = this.props.data[name].map((i) => {
+                    return <PopuralityRealmTable
+                        data={i}
+                        name={name}
+                        visible={this.props.selectedTableName === name}
+                        key={i[0].class_id} />;
+                });
+                return <div id={name} key={name}>{realmTables}</div>;
+            }
+        });
+        return <div>{tables}</div>;
+    }
+}
+
+/**
+ * 人気データ表示コンポーネントプロパティ
+ */
+interface IPopuralityRankingProps {
+    /** 人気データ取得URL */
+    dataUrl: string;
+}
+
+/**
+ * 人気データ表示コンポーネントステータス
+ */
+interface IPopuralityRankingState {
+    /** 表示選択中テーブル名称 */
+    selectedTableName: string;
+    /** データ内容 */
+    data: { [col: string]: any[] };
+    /** データ表示状態を示すメッセージ */
+    stateMessage: string;
+}
+
+/**
+ * 人気データ表示コンポーネント
+ */
+// tslint:disable-next-line:max-classes-per-file
+class PopuralityRanking extends React.Component<IPopuralityRankingProps, IPopuralityRankingState> {
+    constructor(props: IPopuralityRankingProps) {
+        super(props);
+        const selectedTableName = this.storageAvailable("sessionStorage") ?
+            sessionStorage.getItem("selectedTableName") : null;
+
+        this.state = {
+            data: {},
+            selectedTableName: selectedTableName !== null ? selectedTableName : "race",
+            stateMessage: "Loading...",
+        };
+    }
+
+    public componentDidMount() {
+        fetch(this.props.dataUrl).then((response) => {
+            if (!response.ok) {
+                throw Error(`${response.status} ${response.statusText}`);
+            }
+            return response.json();
+        }).then((data) => {
+            data.realm1 = this.group_by_class(data.realm1);
+            data.realm2 = this.group_by_class(data.realm2);
+            this.setState({
+                data,
+                stateMessage: "Success",
+            });
+        }).catch((err) => {
+            this.setState({ stateMessage: err.message });
+        });
+    }
+
+    public componentDidUpdate() {
+        if (this.storageAvailable("sessionStorage")) {
+            sessionStorage.setItem("selectedTableName", this.state.selectedTableName);
+        }
+    }
+
+    public render() {
+        if (Object.keys(this.state.data).length === 0) {
+            return <div>{this.state.stateMessage}</div>;
+        }
+
+        return (
+            <div>
+                <TableSelector
+                    onSelectChange={this.selectTable.bind(this)}
+                    selectedTableName={this.state.selectedTableName}
+                />
+                <RankingTables
+                    data={this.state.data}
+                    selectedTableName={this.state.selectedTableName}
+                />
+            </div>
+        );
+    }
+
+    private storageAvailable(type: string) {
+        const storage = (window as any)[type];
+        try {
+            const x = "__storage_test__";
+            storage.setItem(x, x);
+            storage.removeItem(x);
+            return true;
+        } catch (e) {
+            return e instanceof DOMException && (
+                // everything except Firefox
+                e.code === 22 ||
+                // Firefox
+                e.code === 1014 ||
+                // test name field too, because code might not be present
+                // everything except Firefox
+                e.name === "QuotaExceededError" ||
+                // Firefox
+                e.name === "NS_ERROR_DOM_QUOTA_REACHED") &&
+                // acknowledge QuotaExceededError only if there's something already stored
+                storage.length !== 0;
+        }
+    }
+
+    private selectTable(tableName: string) {
+        this.setState({ selectedTableName: tableName });
+    }
+
+    private group_by_class(data: any[]) {
+        const result: any[] = [];
+        data.forEach((i) => {
+            if (result[i.class_id] === undefined) {
+                result[i.class_id] = [];
+            }
+            result[i.class_id].push(i);
+        });
+        return result.filter((e) => e.length > 1);
+    }
+}
+
+ReactDOM.render(
+    <PopuralityRanking dataUrl="get_popularity_ranking.php" />,
+    document.getElementById("content"),
+);
diff --git a/score/tablesorter-theme/asc.gif b/score/tablesorter-theme/asc.gif
deleted file mode 100644 (file)
index 92b872f..0000000
Binary files a/score/tablesorter-theme/asc.gif and /dev/null differ
diff --git a/score/tablesorter-theme/bg.gif b/score/tablesorter-theme/bg.gif
deleted file mode 100644 (file)
index 4cb50fc..0000000
Binary files a/score/tablesorter-theme/bg.gif and /dev/null differ
diff --git a/score/tablesorter-theme/desc.gif b/score/tablesorter-theme/desc.gif
deleted file mode 100644 (file)
index dae7050..0000000
Binary files a/score/tablesorter-theme/desc.gif and /dev/null differ
diff --git a/score/tablesorter-theme/style.css b/score/tablesorter-theme/style.css
deleted file mode 100644 (file)
index 5059b2f..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-/* tables */
-table.tablesorter thead tr .header {
-       background-image: url(bg.gif);
-       background-repeat: no-repeat;
-       background-position: center right;
-       cursor: pointer;
-}
-table.tablesorter thead tr .headerSortUp {
-       background-image: url(asc.gif);
-}
-table.tablesorter thead tr .headerSortDown {
-       background-image: url(desc.gif);
-}
-table.tablesorter thead tr .headerSortDown, table.tablesorter thead tr .headerSortUp {
-       border: 3px ridge #d27d00;
-}
diff --git a/tsconfig.json b/tsconfig.json
new file mode 100644 (file)
index 0000000..f4ce900
--- /dev/null
@@ -0,0 +1,57 @@
+{
+  "compilerOptions": {
+    /* Basic Options */
+    "target": "es2015",                       /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
+    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
+    // "lib": [],                             /* Specify library files to be included in the compilation. */
+    // "allowJs": true,                       /* Allow javascript files to be compiled. */
+    // "checkJs": true,                       /* Report errors in .js files. */
+    "jsx": "react",                           /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
+    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
+    "sourceMap": true,                        /* Generates corresponding '.map' file. */
+    // "outFile": "./",                       /* Concatenate and emit output to single file. */
+    // "outDir": "./",                        /* Redirect output structure to the directory. */
+    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
+    // "removeComments": true,                /* Do not emit comments to output. */
+    // "noEmit": true,                        /* Do not emit outputs. */
+    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
+    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
+    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
+
+    /* Strict Type-Checking Options */
+    "strict": true,                           /* Enable all strict type-checking options. */
+    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
+    // "strictNullChecks": true,              /* Enable strict null checks. */
+    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
+    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
+    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
+    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */
+
+    /* Additional Checks */
+    // "noUnusedLocals": true,                /* Report errors on unused locals. */
+    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
+    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
+    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */
+
+    /* Module Resolution Options */
+    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
+    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
+    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
+    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
+    // "typeRoots": [],                       /* List of folders to include type definitions from. */
+    // "types": [],                           /* Type declaration files to be included in compilation. */
+    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
+    "esModuleInterop": true                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
+    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
+
+    /* Source Map Options */
+    // "sourceRoot": "./",                    /* Specify the location where debugger should locate TypeScript files instead of source locations. */
+    // "mapRoot": "./",                       /* Specify the location where debugger should locate map files instead of generated locations. */
+    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
+    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
+
+    /* Experimental Options */
+    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
+    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
+  }
+}
diff --git a/tslint.json b/tslint.json
new file mode 100644 (file)
index 0000000..32fa6e5
--- /dev/null
@@ -0,0 +1,9 @@
+{
+    "defaultSeverity": "error",
+    "extends": [
+        "tslint:recommended"
+    ],
+    "jsRules": {},
+    "rules": {},
+    "rulesDirectory": []
+}
\ No newline at end of file
diff --git a/webpack.config.js b/webpack.config.js
new file mode 100644 (file)
index 0000000..0741165
--- /dev/null
@@ -0,0 +1,50 @@
+//import path from "path";
+const path = require("path");
+
+const src = path.resolve(__dirname, "score/src");
+const dist = path.resolve(__dirname, "score/js");
+
+module.exports = {
+    entry: {
+        "popularity_ranking": src + "/popurality_ranking.tsx"
+    },
+
+    output: {
+        path: dist,
+        filename: "[name].bundle.js"
+    },
+
+    devtool: "source-map",
+
+    resolve: {
+        // Add '.ts' and '.tsx' as resolvable extensions.
+        extensions: [".ts", ".tsx", ".js", ".jsx", ".json"]
+    },
+
+    module: {
+        rules: [
+            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
+            {
+                test: /\.tsx?$/,
+                loader: "awesome-typescript-loader"
+            },
+
+            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
+            {
+                enforce: "pre",
+                test: /\.js$/,
+                loader: "source-map-loader"
+            }
+        ]
+
+    },
+
+    // When importing a module whose path matches one of the following, just
+    // assume a corresponding global variable exists and use that instead.
+    // This is important because it allows us to avoid bundling all of our
+    // dependencies, which allows browsers to cache those libraries between builds.
+    externals: {
+        "react": "React",
+        "react-dom": "ReactDOM",
+    },
+};