Updates lol

This commit is contained in:
Pachira 2022-08-26 01:26:00 +00:00
parent 916c02a8e3
commit 559ad615bd
39 changed files with 15209 additions and 181 deletions

5
.gitmodules vendored
View file

@ -1,6 +1,3 @@
[submodule "lib/index"]
path = lib/index
url = https://github.com/flashwave/index.git
[submodule "public/whois/whois-php"]
path = public/whois/whois-php
url = https://git.flash.moe/flash/whois-php.git
url = https://git.flash.moe/flash/index.git

View file

@ -48,32 +48,32 @@ $router->get('/etc', function() {
[
'title' => 'flash.moe / 2014',
'desc' => 'The first iteration of flash.moe. Very simple and to the point.',
'link' => '//abyss.flash.moe/flash.moe2014',
'link' => '//2014.flash.moe',
],
[
'title' => 'flash.moe / 2015',
'desc' => 'My first attempt to make something with a properly thought out design. It\'s definitely a first attempt.',
'link' => '//abyss.flash.moe/flash.moe2015',
'link' => '//2015.flash.moe',
],
[
'title' => 'flash.moe / 2018',
'desc' => 'An attempt at a redesign that didn\'t go anywhere. I wanted to go all in on the pixel grid aesthetic but phones made it difficult so this was never used.',
'link' => '//abyss.flash.moe/flash.moe2018',
'link' => '//2018.flash.moe',
],
[
'title' => 'flash.moe / 2019',
'desc' => 'A return to basics. Just a blog, a bar with links and a list of projects. I attempted to add the necessary fallbacks to make this version of the site work well in IE5.5 and Netscape 4.',
'link' => '//abyss.flash.moe/flash.moe2019',
'link' => '//2019.flash.moe',
],
[
'title' => 'flash.moe / 2020',
'desc' => 'A refinement of the 2019 design, largely based on the same code also. Added more subpages but with a more consistent look.',
'link' => '//abyss.flash.moe/flash.moe2020',
'link' => '//2020.flash.moe',
],
[
'title' => 'flash.moe / 2021',
'desc' => 'I always thought previous iterations of flash.moe lacked personality. I threw out a lot of preconceptions when making the 2021 design and I think it paid off. Currently this is still the face of flash.moe but the backend is pretty much entirely different, I\'m planning an overhaul that puts more focus on the blog again and also fixes the JSON trash navigation issues.',
'link' => '//abyss.flash.moe/flash.moe2021',
'link' => '//2021.flash.moe',
],
];

View file

@ -0,0 +1 @@

View file

@ -0,0 +1,7 @@
Copyright 2018 Frelia (@execfera)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,165 @@
# charasort
A web based character sorter. Allows users to run through a manual merge sort of their favorite
characters from a set.
**Features**
* Entirely client side, no backend server required.
* Filtering out characters based on JSON based filters.
* Shareable links of sorter results.
* Versioning of sorter data - you may want to add characters and resources over time. Versioning keeps shareable links valid even if the base character data is changed.
The version in this repo is built for characters from the [Touhou Project](https://en.wikipedia.org/wiki/Touhou_Project)
game series, but the sorter can be easily edited to create any custom sorter desired.
## Related Sorters
Several others have created other sorters based on other concepts and series, see them [here](https://github.com/execfera/charasort/wiki)!
## Creating Your Own Sorter
This is a list of things you need to change for your sorter, for each file.
* `index.html`
* Sorter name: Change under `starting start button` and the `<title>` tags.
* Starting banner images: 120px x 180px, under `left sort image` and `right sort image`.
* OpenGraph tags: `og:site_name`, `og:description` and `og:image` will show up on embeds when linked to social media such as Facebook, Twitter and Discord.
* Sorter info: Insert whatever you like under the `info` tag.
* Website icon: Remember to get your own `favicon.ico`!
* `src/js/data.js`
Change `imageRoot` if you are not uploading your images to imgur.
* `src/js/data/YYYY-MM-DD.js`
Creating your own set of data is relatively simple. First, change the `dataSetVersion` date to the date when you are creating the dataset. Example: `dataSetVersion = 2018-02-20`. The actual filename does not matter, it is just for your own easy reference.
Further down, each file comprises of two sets of data: `characterData` and `options`.
`characterData` is an array of objects filled with character data. Its layout is as follows.
```
{
name: string,
img: string,
opts: {
key1: boolean | string[],
key2: boolean | string[],
...
}
}
```
Parameters:
* `name`: The name of the character to be displayed. **Required.**
* `img`: An image filename of the character, in 120px x 180px, to be added to `imageRoot` in `data.js`. **Required.**
* `opts`: An object of 'options' that will be used to filter out characters that will be used. Further explanation below. **Required.**
Example:
```
{
name: "Flandre Scarlet",
img: "OhaDcnc.png",
opts: {
series: ["book", "EoSD", "StB"],
stage: ["ex"],
loli: true
}
}
```
`options` is an array of objects that can take either two forms. The first form is a **Basic Filter**. The Basic Filter, when selected, removes any character that matches its criteria. Its layout is as follows.
```
{
name: string,
key: string,
tooltip?: string, // optional
checked?: boolean, // optional
}
```
Parameters:
* `name`: The name of the option to be displayed. **Required.**
* `key`: A shorthand reference, used to refer to it in the character data. **Required.**
* `tooltip`: Some optional information that appears when you hover over the option. If not provided, defaults to the option's name.
* `checked`: If set to `true`, this option will be checked when your sorter starts. If not provided, defaults to `false`.
Example:
```
{
name: 'Filter Lolis',
key: 'loli',
tooltip: 'Check this if you want to remove lolis from being listed.'
checked: true,
}
```
In this example, checking this option would remove the example 'Flandre Scarlet' above from the list of sorted characters, since she has `loli` set to `true`. The `checked` option is true, so in this sorter, it would be enabled by default.
The second form is a **Nested Inclusion Filter**. The Nested Inclusion Filter has a few sub-options under it. When selected, any options under it that are *not* selected will be excluded from the sort. Its layout is similar to the Basic Filter, except with an extra `sub` part, which lists the sub-options.
```
{
name: string,
key: string,
tooltip?: string, // optional
checked?: boolean, // optional
sub: [
{
name: string,
key: string,
tooltip?: string, // optional
checked?: boolean, // optional
},
{
name: string,
key: string,
tooltip?: string, // optional
checked?: boolean, // optional
},
...
]
}
```
This option will be often the only one you may need, since it is easy to use it for filtering by series.
Example:
```
{
name: 'Filter by Series Appearance',
key: 'series',
tooltip: 'Check this if you want to filter out certain series.'
checked: true,
sub: [
{ name: 'Books & CDs', key: 'book' },
{ name: 'Embodiment of Scarlet Devil', key: 'EoSD' },
{ name: 'Perfect Cherry Blossom', key: 'PCB' },
]
}
```
In this case, this would create a "Filter by Series Appearance" option, with the three listed sub-options. "Flandre Scarlet" above has both `book` and `EoSD` under `series`, so unless you uncheck both "Books & CDs" and "Embodiment of Scarlet Devil", she would still appear in the sort.
## Updating Your Own Sorter
When you need to add more characters to your sorter, you must create a new data file with a new date, and include it in your `index.html` file under the `<script src="src/js/data.js"></script>` line, while keeping your previous data files also included.
The script will automatically get the latest version, but will retain the previous versions in case someone keeps a shareable link from one of the previous versions.
## Credits
* [html2canvas](https://github.com/niklasvh/html2canvas/) for image generation.
* [seedrandom](https://github.com/davidbau/seedrandom) for PRNG used in character array shuffling.
* [lz-string](https://github.com/pieroxy/lz-string) for shareable link compression.
* [SpinKit](http://tobiasahlin.com/spinkit/) for loading animation.
* [thsort](http://mainyan.sakura.ne.jp/thsort.html) for the original inspiration.
## Known Issues
* Does not work with CloudFlare's Rocket Loader.
* Breaks on older versions of IE and mobile Safari, due to various incompatibilities.

View file

@ -0,0 +1,78 @@
<html>
<head>
<link rel="shortcut icon" href="src/assets/flashii.ico" type="image/x-icon">
<link rel="icon" href="src/assets/flashii.ico" type="image/x-icon">
<meta charset="utf-8">
<meta name="og:site_name" content="Flashii Member Sorting">
<meta name="og:description" content="A simple website for sorting Flashii member in a formatted list.">
<meta name="og:image" content="https://i.imgur.com/IZzJMk6.jpg">
<title>Flashii Member Sorting</title>
<link rel="stylesheet" type="text/css" href="src/css/reset.css">
<link rel="stylesheet" type="text/css" href="src/css/styles.css">
<script src="src/js/data.js"></script>
<script src="src/js/data/2022-06-21.js"></script>
<script src="src/js/html2canvas.min.js"></script>
<script src="src/js/lz-string.min.js"></script>
<script src="src/js/seedrandom.min.js"></script>
<script src="src/js/main.js"></script>
</head>
<body>
<div class="container">
<div class="progress">
<span class="progressbattle"></span>
<div class="progressbar">
<div class="progressfill"><span class="progresstext"></span></div>
</div>
</div>
<div class="sorter">
<img src="src/assets/defaultL.jpg" class="left sort image">
<div class="starting start button">Touhou Project Character Sorter<br><br>Click to Start!</div>
<div class="starting load button">Load <span></span></div>
<div class="loading button"><div></div><span>Loading...</span></div>
<div class="sorting tie button">Tie</div>
<div class="sorting undo button">Undo</div>
<div class="sorting save button">Save Progress</div>
<div class="finished save button">Generate Result URL</div>
<div class="finished getimg button">Generate Image</div>
<div class="finished list button">Generate Text List</div>
<img src="src/assets/defaultR.jpg" class="right sort image">
<div class="left sort text"><p></p></div>
<div class="right sort text"><p></p></div>
</div>
<div class="options"></div>
<div class="image selector">Display Images on Result: </div>
<div class="time taken"></div>
<div class="results"></div>
<div class="info">
<a href="https://github.com/execfera/charasort/">Yoinked from here</a> | <a class="clearsave">Clear Save Data</a>
<br><br>
<p>Sorter for Flashii members. Pick your sources, and hit the Start button.</p>
<p>Click on the mom you like better from the two, or tie them if you like them equally or don't know them.</p>
<br><br>
<p>Keyboard controls during sorting: H/LeftArrow (pick left) J/DownArrow (undo) K/UpArrow (tie) L/RightArrow (pick right) S (save progress).</p>
<p>Before sorting: S/Enter (start sorting) L (load progress).
<p>1/2/3 always correspond to the first/second/third buttons.</p>
</div>
</div>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

View file

@ -0,0 +1,48 @@
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}

View file

@ -0,0 +1,286 @@
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 16px;
}
.container {
display: flex;
flex-flow: column nowrap;
align-items: center;
margin-top: 1em;
}
.progress {
margin: 1em auto;
width: 500px;
display: none;
}
.progressbar {
position: relative;
width: 492px;
border: 1px solid black;
padding: 3px;
margin: 2px 0px;
}
.progresstext {
position: absolute;
width: 492px;
margin: 3px 0px;
text-align: center;
font-size: 0.7em;
}
.progressfill {
height: 20px;
background-color: lightgreen;
width: 0%;
}
.sorter {
margin: 0px auto;
display: grid;
grid-template-columns: 120px 1fr 120px;
grid-gap: 5px;
width: 420px;
}
.button {
border: 1px solid black;
text-align: center;
padding: 10%;
grid-column: 2 / 3;
cursor: pointer;
}
.starting.start.button {
grid-row: span 6;
}
.starting.load.button {
grid-row: span 3;
display: none;
}
.sorting.button, .finished.button {
grid-row: span 2;
display: none;
}
.loading.button {
grid-row: span 6;
display: none;
}
.loading.button > div {
width: 25px;
height: 25px;
margin: 50px auto;
background-color: #333;
border-radius: 100%;
-webkit-animation: sk-scaleout 1.0s infinite ease-in-out;
animation: sk-scaleout 1.0s infinite ease-in-out;
}
/* Animation taken from: http://tobiasahlin.com/spinkit/ */
.loading.button > span {
margin: auto auto 20%;
font-size: 0.7em;
}
@-webkit-keyframes sk-scaleout {
0% { -webkit-transform: scale(0) }
100% {
-webkit-transform: scale(1.0);
opacity: 0;
}
}
@keyframes sk-scaleout {
0% {
-webkit-transform: scale(0);
transform: scale(0);
} 100% {
-webkit-transform: scale(1.0);
transform: scale(1.0);
opacity: 0;
}
}
.sorter > .image {
width: 120px;
height: 180px;
margin: auto;
grid-row: 1 / 7;
cursor: pointer;
}
.sorter > .text {
width: 120px;
height: 60px;
display: none;
}
.sorter > .text > p {
margin: 0.5em 5px 0px;
width: calc(100%-10px);
text-align: center;
font-size: 0.8em;
line-height: 1.5em;
}
.sorter > .left {
grid-column: 1 / 2;
border: 1px solid #000000;
}
.sorter > .right {
grid-column: 3 / 4;
border: 1px solid #000000;
}
.options {
margin: 1em auto;
display: grid;
text-align: left;
grid-template-columns: repeat(3, 1fr);
grid-gap: 10px;
width: 450px;
}
.options > div {
font-size: 0.5625em;
}
label {
cursor: pointer;
}
label:hover {
color: #990000;
}
.options > .large.option, .options > hr {
grid-column: span 3;
text-align: center;
width: 100%;
}
.image.selector {
margin-top: 0.5em;
width: 500px;
display: none;
text-align: center;
font-size: 0.75em;
}
.time.taken {
margin-top: 0.5em;
width: 500px;
display: none;
text-align: center;
font-size: 0.75em;
}
.results {
font-size: 0.75em;
display: flex;
align-content: flex-start;
width: 80%;
margin: 2em auto;
}
@media all and (min-width: 600px) {
.results {
flex-flow: column wrap;
max-height: calc(5 * (175px + 2px) + 1 * (15px + 2px));
/* 2px for borders */
}
}
@media all and (max-width: 600px) {
.results {
flex-flow: column nowrap;
}
}
.result {
height: 15px;
margin-bottom: -1px;
display: grid;
width: 211px;
grid-template-columns: repeat(2, 1fr);
border: 1px solid #000;
margin-right: 5px;
}
.result.image {
height: 175px;
}
.result.image img {
height: 160px;
}
.result.spacer {
height: 1px;
background-color: #000;
}
.result.head {
background-color: #000;
color: #FFF;
}
.result > .left {
width: 35px;
padding: 1px 3px 1px 0.5em;
grid-column: 1 / 2;
text-align: right;
}
.result.image .left {
position: relative;
}
.result.image > .left span {
position: absolute;
top: 50%;
right: 3px;
margin-top: -0.375em;
}
.result > .right {
width: 160px;
padding: 1px 0em 1px 0em;
grid-column: 2 / 3;
border-left: 1px solid #000;
text-align: center;
}
.info {
margin: 2em auto 3em;
display: block;
text-align: center;
font-size: 0.6875em;
width: 80%;
line-height: 1.2em;
}
a {
color: #990000;
font-weight: bold;
text-decoration: none;
cursor: pointer;
}
a:hover {
color: #FF6600;
}
a:visited {
color: #6600FF;
}

View file

@ -0,0 +1,23 @@
/**
* @typedef {{name: string, key: string, tooltip?: string, checked?: boolean, sub?: {name: string, tooltip?: string, checked?: string}[]}[]} Options
* @typedef {{name: string, img: string, opts: Object<string, boolean|number[]}[]} CharData
*/
/**
* Data set. Characters will be removed from the sorting array based on selected options, working down the array.
*
* @type {Object.<string, {options: Options, characterData: CharData}>}
*/
const dataSet = {};
/**
* Data set version, in YYYY-MM-DD form.
*
* @example '2018-02-20'
*/
let dataSetVersion = '';
/**
* Image root, will be appended to the start of every image URL.
*/
const imageRoot = '';

View file

@ -0,0 +1,806 @@
dataSetVersion = "2017-05-01"; // Change this when creating a new data set version. YYYY-MM-DD format.
dataSet[dataSetVersion] = {};
dataSet[dataSetVersion].options = [
{
name: "Filter by Series Entry",
key: "series",
tooltip: "Check this to restrict to certain series.",
checked: false,
sub: [
{ name: "Books and CDs", key: "book" },
{ name: "The Highly Responsive to Prayers", tooltip: "01 - Reiiden", key: "HRtP" },
{ name: "The Story of Eastern Wonderland", tooltip: "02 - Fuumaroku", key: "SoEW" },
{ name: "Phantasmagoria of Dim.Dream", tooltip: "03 - Yumejikuu", key: "PoDD" },
{ name: "Lotus Land Story", tooltip: "04 - Gensoukyou", key: "LLS" },
{ name: "Mystic Square", tooltip: "05 - Kaikidan", key: "MS" },
{ name: "Embodiment of Scarlet Devil", tooltip: "06 - Koumakan", key: "EoSD" },
{ name: "Perfect Cherry Blossom", tooltip: "07 - Youyoumu", key: "PCB" },
{ name: "Immaterial and Missing Power", tooltip: "07.5 - Suimusou", key: "IaMP" },
{ name: "Imperishable Night", tooltip: "08 - Eiyashou", key: "IN" },
{ name: "Phantasmagoria of Flower View", tooltip: "09 - Kaeidzuka", key: "PoFV" },
{ name: "Shoot the Bullet", tooltip: "09.5 - Bunkachou", key: "StB" },
{ name: "Mountain of Faith", tooltip: "10 - Fuujinroku", key: "MoF" },
{ name: "Scarlet Weather Rhapsody", tooltip: "10.5 - Hisouten", key: "SWR" },
{ name: "Subterranean Animism", tooltip: "11 - Chireiden", key: "SA" },
{ name: "Undefined Fantastic Object", tooltip: "12 - Seirensen", key: "UFO" },
{ name: "Touhou Hisoutensoku", tooltip: "12.3 - Hisoutensoku", key: "Soku" },
{ name: "Double Spoiler", tooltip: "12.5 - Bunkachou", key: "DS" },
{ name: "Great Fairy Wars", tooltip: "12.8 - Daisensou", key: "GFW" },
{ name: "Ten Desires", tooltip: "13 - Shinreibyou", key: "TD" },
{ name: "Hopeless Masquerade", tooltip: "13.5 - Shinkirou", key: "HM" },
{ name: "Double Dealing Character", tooltip: "14 - Kishinjou", key: "DDC" },
{ name: "Impossible Spell Card", tooltip: "14.3 - Amanojaku", key: "ISC" },
{ name: "Urban Legend in Limbo", tooltip: "14.5 - Shinpiroku", key: "ULiL" },
{ name: "Legacy of Lunatic Kingdom", tooltip: "15 - Kanjuden", key: "LoLK" }
]
},
{
name: "Filter by Stage Enemy Appearances",
key: "stage",
tooltip: "Check this to restrict to characters that appear in certain stages as enemies.",
checked: false,
sub: [
{ name: "Stage 1", key: "st1" },
{ name: "Stage 2", key: "st2" },
{ name: "Stage 3", key: "st3" },
{ name: "Stage 4", key: "st4" },
{ name: "Stage 5/Penultimate", tooltip: "Stage 4 in 5-stage games, and Stage 8 in 9-stage games.", key: "st5" },
{ name: "Stage 6/Final", key: "st6" },
{ name: "Stage EX/Phantasm", key: "ex" }
]
},
{
name: "Remove PC-98 Duplicates",
key: "pc98",
tooltip: "Check this to remove PC-98 characters with a Windows counterpart."
},
{
name: "Remove Non-Girls",
key: "notgirl",
tooltip: "Check this to remove all non-female characters."
}
];
dataSet[dataSetVersion].characterData = [
{
name: "Hakurei Reimu",
img: "c5DqpgX.png",
opts: {
series: ["book", "EoSD", "PCB", "IaMP", "IN", "PoFV", "StB", "MoF", "SWR", "SA", "UFO", "Soku", "DS", "TD", "HM", "DDC", "ISC", "ULiL", "LoLK"],
stage: ["st4"]
}
},
{
name: "Kirisame Marisa",
img: "tJnkSzK.png",
opts: {
series: ["book", "EoSD", "PCB", "IaMP", "IN", "PoFV", "StB", "MoF", "SWR", "SA", "UFO", "Soku", "DS", "GFW", "TD", "HM", "DDC", "ISC", "ULiL", "LoLK"],
stage: ["st4", "ex"]
}
},
{
name: "Rumia",
img: "0YT7QlS.png",
opts: { series: ["book", "EoSD", "StB", "HM"], stage: ["st1"] }
},
{
name: "Daiyousei",
img: "NWlZud3.png",
opts: { series: ["book", "EoSD"], stage: ["st2", "ex"] }
},
{
name: "Cirno",
img: "qdveFSy.png",
opts: {
series: [ "book", "EoSD", "PCB", "PoFV", "StB", "Soku", "GFW", "HM", "DDC", "ISC"
],
stage: ["st2"]
}
},
{
name: "Hong Meiling",
img: "ptGp0x4.png",
opts: { series: ["book", "EoSD", "IaMP", "StB", "Soku"], stage: ["st3"] }
},
{
name: "Koakuma",
img: "vBKdDm4.png",
opts: { series: ["book", "EoSD"], stage: ["st4"] }
},
{
name: "Patchouli Knowledge",
img: "A7ZnuHo.png",
opts: {
series: ["book", "EoSD", "IaMP", "StB", "MoF", "Soku", "HM"],
stage: ["st4", "ex"]
}
},
{
name: "Izayoi Sakuya",
img: "sgZPf11.png",
opts: {
series: [ "book", "EoSD", "PCB", "IaMP", "IN", "PoFV", "StB", "MoF", "Soku", "HM", "DDC", "ISC"
],
stage: ["st5", "st6"]
}
},
{
name: "Remilia Scarlet",
img: "8UX7hKE.png",
opts: {
series: ["book", "EoSD", "IaMP", "IN", "StB", "MoF", "Soku", "HM", "ISC"],
stage: ["st6"]
}
},
{
name: "Flandre Scarlet",
img: "OhaDcnc.png",
opts: { series: ["book", "EoSD", "StB"], stage: ["ex"] }
},
{
name: "Letty Whiterock",
img: "MgzqjFK.png",
opts: { series: ["book", "PCB", "StB", "HM"], stage: ["st1"] }
},
{
name: "Chen",
img: "ohmetZh.png",
opts: {
series: ["book", "PCB", "IaMP", "StB", "MoF", "Soku", "HM"],
stage: ["st2", "ex"]
}
},
{
name: "Alice Margatroid",
img: "aDIf0pN.png",
opts: {
series: ["book", "PCB", "IaMP", "IN", "StB", "MoF", "Soku", "HM"],
stage: ["st3"]
}
},
{
name: "Lily White",
img: "2Pr8b2N.png",
opts: { series: ["book", "PCB", "PoFV", "HM"], stage: ["st4", "ex"] }
},
{
name: "Lunasa Prismriver",
img: "htOMdDQ.png",
opts: { series: ["book", "PCB", "PoFV", "HM"], stage: ["st4"] }
},
{
name: "Merlin Prismriver",
img: "PrRPujP.png",
opts: { series: ["book", "PCB", "PoFV", "HM"], stage: ["st4"] }
},
{
name: "Lyrica Prismriver",
img: "ze79bFC.png",
opts: { series: ["book", "PCB", "PoFV", "HM"], stage: ["st4"] }
},
{
name: "Konpaku Youmu",
img: "WMjyRLJ.png",
opts: {
series: [ "book", "PCB", "IaMP", "IN", "PoFV", "StB", "MoF", "Soku", "TD", "HM", "ISC"
],
stage: ["st5", "st6"]
}
},
{
name: "Saigyouji Yuyuko",
img: "VT9mTGb.png",
opts: {
series: [ "book", "PCB", "IaMP", "IN", "StB", "MoF", "Soku", "TD", "HM", "ISC"
],
stage: ["st1", "st6"]
}
},
{
name: "Yakumo Ran",
img: "rshnJPV.png",
opts: {
series: ["book", "PCB", "IaMP", "IN", "StB", "MoF", "Soku", "HM"],
stage: ["ex"]
}
},
{
name: "Yakumo Yukari",
img: "qsceD4I.png",
opts: {
series: ["book", "PCB", "IaMP", "IN", "StB", "MoF", "Soku", "HM", "ISC"],
stage: ["ex"]
}
},
{
name: "Ibuki Suika",
img: "pLdMjQ3.png",
opts: {
series: ["book", "IaMP", "StB", "MoF", "Soku", "DS", "HM", "ISC"],
stage: ["st6"]
}
},
{
name: "Wriggle Nightbug",
img: "8DLUAPf.png",
opts: { series: ["book", "IN", "StB", "HM"], stage: ["st1"] }
},
{
name: "Mystia Lorelei",
img: "6KyhLqE.png",
opts: { series: ["book", "IN", "PoFV", "StB", "HM"], stage: ["st2"] }
},
{
name: "Kamishirasawa Keine",
img: "99w0Chm.png",
opts: { series: ["book", "IN", "StB", "HM", "ISC"], stage: ["st3", "ex"] }
},
{
name: "Inaba Tewi",
img: "yqNfNje.png",
opts: { series: ["book", "IN", "PoFV", "StB", "HM"], stage: ["st5"] }
},
{
name: "Reisen Udongein Inaba",
img: "PrYzRcC.png",
opts: {
series: ["book", "IN", "PoFV", "StB", "Soku", "HM", "LoLK"],
stage: ["st5"]
}
},
{
name: "Yagokoro Eirin",
img: "ceo4DhK.png",
opts: { series: ["book", "IN", "StB", "HM"], stage: ["st6"] }
},
{
name: "Houraisan Kaguya",
img: "2YDuTk3.png",
opts: { series: ["book", "IN", "StB", "HM"], stage: ["st6"] }
},
{
name: "Fujiwara no Mokou",
img: "3zo4VKV.png",
opts: { series: ["book", "IN", "StB", "HM", "ISC", "ULiL"], stage: ["ex"] }
},
{
name: "Shameimaru Aya",
img: "8TLXMST.png",
opts: {
series: ["book", "PoFV", "StB", "MoF", "SWR", "Soku", "HM", "ISC"],
stage: ["st4"]
}
},
{
name: "Medicine Melancholy",
img: "IImsp7K.png",
opts: { series: ["book", "PoFV", "StB", "HM"], stage: ["st4"] }
},
{
name: "Kazami Yuuka",
img: "MZXJQq5.png",
opts: { series: ["book", "PoFV", "StB", "HM"], stage: ["st5"] }
},
{
name: "Onozuka Komachi",
img: "aX4WIH8.png",
opts: {
series: ["book", "PoFV", "StB", "MoF", "Soku", "HM"],
stage: ["st5"]
}
},
{
name: "Shiki Eiki, Yamaxanadu",
img: "nPBvatH.png",
opts: { series: ["book", "PoFV", "StB", "HM"], stage: ["st6"] }
},
{
name: "Aki Shizuha",
img: "3pDRgvR.png",
opts: { series: ["SWR", "DS", "HM"], stage: ["st1"] }
},
{
name: "Aki Minoriko",
img: "bV0DaN7.png",
opts: { series: ["SWR", "DS", "HM"], stage: ["st1"] }
},
{
name: "Kagiyama Hina",
img: "J11NjNj.png",
opts: { series: ["SWR", "DS", "HM"], stage: ["st2"] }
},
{
name: "Kawashiro Nitori",
img: "4Ufced2.png",
opts: { series: ["SWR", "DS", "HM", "ISC", "ULiL"], stage: ["st3"] }
},
{
name: "Inubashiri Momiji",
img: "qGMjnYk.png",
opts: { series: ["SWR", "DS", "ISC"], stage: ["st4"] }
},
{
name: "Kochiya Sanae",
img: "ATTRSWU.png",
opts: {
series: ["SWR", "SA", "UFO", "Soku", "DS", "TD", "HM", "ISC", "LoLK"],
stage: ["st5", "ex"]
}
},
{
name: "Yasaka Kanako",
img: "nQ78Lz7.png",
opts: { series: ["SWR", "Soku", "DS", "HM", "ISC"], stage: ["st6", "ex"] }
},
{
name: "Moriya Suwako",
img: "yJaD5ZV.png",
opts: { series: ["SWR", "SA", "Soku", "DS", "HM", "ISC"], stage: ["ex"] }
},
{
name: "Nagae Iku",
img: "xgAlECj.png",
opts: { series: ["MoF", "Soku", "DS", "HM"], stage: ["st5"] }
},
{
name: "Hinanawi Tenshi",
img: "tZLYivt.png",
opts: { series: ["MoF", "Soku", "DS", "HM", "ISC"], stage: ["st6"] }
},
{
name: "Kisume",
img: "VgJgaEf.png",
opts: { series: ["SA", "DS"], stage: ["st1"] }
},
{
name: "Kurodani Yamame",
img: "sqgJ2St.png",
opts: { series: ["SA", "DS", "HM"], stage: ["st1"] }
},
{
name: "Mizuhashi Parsee",
img: "lkoAJod.png",
opts: { series: ["SA", "DS", "HM"], stage: ["st2"] }
},
{
name: "Hoshiguma Yuugi",
img: "tDO653L.png",
opts: { series: ["SA", "DS", "HM"], stage: ["st3"] }
},
{
name: "Komeiji Satori",
img: "dup7Nt6.png",
opts: { series: ["SA", "DS", "HM"], stage: ["st4"] }
},
{
name: "Kaenbyou Rin (Orin)",
img: "uQjbw1W.png",
opts: { series: ["SA", "DS", "HM"], stage: ["st4", "st5", "st6"] }
},
{
name: "Reiuji Utsuho (Okuu)",
img: "DfdaXPW.png",
opts: { series: ["SA", "Soku", "DS", "HM"], stage: ["st6"] }
},
{
name: "Komeiji Koishi",
img: "wVCcens.png",
opts: { series: ["SA", "DS", "HM", "ULiL"], stage: ["ex"] }
},
{
name: "Nazrin",
img: "EpHQbiY.png",
opts: { series: ["UFO", "DS", "HM"], stage: ["st1", "st5"] }
},
{
name: "Tatara Kogasa",
img: "kJbv4dc.png",
opts: { series: ["UFO", "DS", "HM"], stage: ["st2", "ex"] }
},
{
name: "Kumoi Ichirin",
img: "Fyn5yVx.png",
opts: { series: ["UFO", "DS", "HM", "ULiL"], stage: ["st3"] }
},
{
name: "Murasa Minamitsu",
img: "39KYpvW.png",
opts: { series: ["UFO", "DS", "HM"], stage: ["st4"] }
},
{
name: "Toramaru Shou",
img: "8bMDDAo.png",
opts: { series: ["UFO", "DS", "HM"], stage: ["st5"] }
},
{
name: "Hijiri Byakuren",
img: "2ppPxny.png",
opts: { series: ["UFO", "DS", "HM", "ISC", "ULiL"], stage: ["st6"] }
},
{
name: "Houjuu Nue",
img: "zL4S8Mj.png",
opts: { series: ["UFO", "DS", "TD", "HM"], stage: ["st4", "st6", "ex"] }
},
{
name: "Himekaidou Hatate",
img: "LgvoTaJ.png",
opts: { series: ["DS", "HM", "ISC"], stage: ["ex"] }
},
{
name: "Sunny Milk",
img: "VbqXiB6.png",
opts: { series: ["book", "GFW", "HM"], stage: ["st1", "st2", "st3"] }
},
{
name: "Luna Child",
img: "OBqgP48.png",
opts: { series: ["book", "GFW", "HM"], stage: ["st1", "st2", "st3"] }
},
{
name: "Star Sapphire",
img: "sNw61ap.png",
opts: { series: ["book", "GFW", "HM"], stage: ["st1", "st2", "st3"] }
},
{
name: "Kasodani Kyouko",
img: "sLiqEBA.png",
opts: { series: ["TD", "HM", "ISC"], stage: ["st2"] }
},
{
name: "Miyako Yoshika",
img: "6jq6eh6.png",
opts: { series: ["TD", "HM", "ISC"], stage: ["st3", "st4"] }
},
{
name: "Kaku Seiga",
img: "090hLPL.png",
opts: { series: ["TD", "HM", "ISC"], stage: ["st4"] }
},
{
name: "Soga no Tojiko",
img: "y0UXwFO.png",
opts: { series: ["TD", "HM"], stage: ["st5"] }
},
{
name: "Mononobe no Futo",
img: "WTZ97LE.png",
opts: { series: ["TD", "HM", "ISC", "ULiL"], stage: ["st5"] }
},
{
name: "Toyosatomimi no Miko",
img: "3Xiqd22.png",
opts: { series: ["TD", "HM", "ISC", "ULiL"], stage: ["st6"] }
},
{
name: "Futatsuiwa Mamizou",
img: "gMpWdmA.png",
opts: { series: ["TD", "HM", "ISC", "ULiL"], stage: ["ex"] }
},
{
name: "Hata no Kokoro",
img: "fxCGmUk.png",
opts: { series: ["book", "HM", "ULiL"], stage: ["st6"] }
},
{
name: "Wakasagihime",
img: "brWCLVx.png",
opts: { series: ["DDC", "ISC"], stage: ["st1"] }
},
{
name: "Sekibanki",
img: "VAMLiJD.png",
opts: { series: ["DDC", "ISC"], stage: ["st2"] }
},
{
name: "Imaizumi Kagerou",
img: "b5UMjD8.png",
opts: { series: ["DDC", "ISC"], stage: ["st3"] }
},
{
name: "Tsukumo Benben",
img: "vWNeMaH.png",
opts: { series: ["DDC", "ISC"], stage: ["st4", "ex"] }
},
{
name: "Tsukumo Yatsuhashi",
img: "EJFQHQN.png",
opts: { series: ["DDC", "ISC"], stage: ["st4", "ex"] }
},
{
name: "Kijin Seija",
img: "16RUacj.png",
opts: { series: ["DDC", "ISC"], stage: ["st5", "st6"] }
},
{
name: "Sukuna Shinmyoumaru",
img: "Zl2tN7W.png",
opts: { series: ["DDC", "ISC", "ULiL"], stage: ["st6"] }
},
{
name: "Horikawa Raiko",
img: "SLLEccR.png",
opts: { series: ["DDC", "ISC"], stage: ["ex"] }
},
{
name: "Usami Sumireko",
img: "mc7ICW6.png",
opts: { series: ["ULiL"], stage: ["st6"] }
},
{
name: "Seiran",
img: "0ra00WG.png",
opts: { series: ["LoLK"], stage: ["st1"] }
},
{
name: "Ringo",
img: "xQOsFlZ.png",
opts: { series: ["LoLK"], stage: ["st2"] }
},
{
name: "Doremy Sweet",
img: "rGS7dyn.png",
opts: { series: ["LoLK"], stage: ["st3", "ex"] }
},
{
name: "Kishin Sagume",
img: "HLT338X.png",
opts: { series: ["LoLK"], stage: ["st4"] }
},
{
name: "Clownpiece",
img: "9Jje7ZQ.jpg",
opts: { series: ["LoLK"], stage: ["st5"] }
},
{
name: "Junko",
img: "NsfLZjY.jpg",
opts: { series: ["LoLK"], stage: ["st6", "ex"] }
},
{
name: "Hecatia Lapislazuli",
img: "EH3Ulol.png",
opts: { series: ["LoLK"], stage: ["ex"] }
},
{
name: "Hieda no Akyuu",
img: "ogONuLZ.png",
opts: { series: ["book"], stage: [] }
},
{ name: "Tokiko", img: "Y4maOc8.png", opts: { series: ["book"], stage: [] } },
{
name: "Rei'sen (Manga)",
img: "cWjCo2j.png",
opts: { series: ["book"], stage: [] }
},
{
name: "Watatsuki no Toyohime",
img: "uEBxsEX.png",
opts: { series: ["book"], stage: [] }
},
{
name: "Watatsuki no Yorihime",
img: "Txu2P7S.png",
opts: { series: ["book"], stage: [] }
},
{
name: "Maribel Hearn",
img: "XUI9vPo.png",
opts: { series: ["book"], stage: [] }
},
{
name: "Usami Renko",
img: "1P5EXRt.png",
opts: { series: ["book"], stage: [] }
},
{
name: "Ibaraki Kasen",
img: "dQHnPPe.png",
opts: { series: ["book", "ULiL"], stage: ["st5"] }
},
{
name: "Motoori Kosuzu",
img: "jEsJJo8.png",
opts: { series: ["book"], stage: [] }
},
{
name: "Hakurei Reimu (PC-98)",
img: "IZsGAMS.png",
opts: {
series: ["HRtP", "SoEW", "PoDD", "LLS", "MS"],
stage: ["st4"],
pc98: true
}
},
{
name: "Shingyoku (Female)",
img: "KuPiR2k.png",
opts: { series: ["HRtP"], stage: ["st1"] }
},
{
name: "Mima",
img: "odH03t2.png",
opts: {
series: ["HRtP", "SoEW", "PoDD", "MS"],
stage: ["st3", "st5", "st6"]
}
},
{
name: "Elis",
img: "ytnL1xd.png",
opts: { series: ["HRtP"], stage: ["st5"] }
},
{
name: "Kikuri",
img: "fX2Kqik.png",
opts: { series: ["HRtP"], stage: ["st5"] }
},
{
name: "Sariel",
img: "Wyc7YFw.png",
opts: { series: ["HRtP"], stage: ["st6"] }
},
{
name: "Konngara",
img: "dg9jLHv.png",
opts: { series: ["HRtP"], stage: ["st6"] }
},
{
name: "Rika",
img: "02Xb4pU.png",
opts: { series: ["SoEW"], stage: ["st1", "ex"] }
},
{
name: "Meira",
img: "p529JgT.png",
opts: { series: ["SoEW"], stage: ["st2"] }
},
{
name: "Kirisame Marisa (PC-98)",
img: "wxE7cBm.png",
opts: { series: ["SoEW", "PoDD", "LLS", "MS"], stage: ["st4"], pc98: true }
},
{ name: "Ellen", img: "3iNNL0c.png", opts: { series: ["PoDD"], stage: [] } },
{
name: "Kotohime",
img: "kRSGtpq.png",
opts: { series: ["PoDD"], stage: [] }
},
{
name: "Kana Anaberal",
img: "rBvKMk5.png",
opts: { series: ["PoDD"], stage: [] }
},
{
name: "Asakura Rikako",
img: "VIf5gUK.png",
opts: { series: ["PoDD"], stage: [] }
},
{
name: "Kitashirakawa Chiyuri",
img: "tZFBycy.png",
opts: { series: ["PoDD"], stage: ["st5"] }
},
{
name: "Okazaki Yumemi",
img: "c9rnG3n.png",
opts: { series: ["PoDD"], stage: ["st6"] }
},
{
name: "Ruukoto",
img: "dko67SJ.png",
opts: { series: ["PoDD"], stage: [] }
},
{
name: "Orange",
img: "m8wXE5U.png",
opts: { series: ["LLS"], stage: ["st1"] }
},
{
name: "Kurumi",
img: "0rvq1ph.png",
opts: { series: ["LLS"], stage: ["st2"] }
},
{
name: "Elly",
img: "iIPftHn.png",
opts: { series: ["LLS"], stage: ["st3"] }
},
{
name: "Yuuka (PC-98)",
img: "ivUSwxp.png",
opts: { series: ["LLS", "MS"], stage: ["st5", "st6"], pc98: true }
},
{
name: "Mugetsu",
img: "bYA9E16.png",
opts: { series: ["LLS"], stage: ["ex"] }
},
{
name: "Gengetsu",
img: "TIOTtV9.png",
opts: { series: ["LLS"], stage: ["ex"] }
},
{
name: "Sara",
img: "2QUbCrU.png",
opts: { series: ["MS"], stage: ["st1"] }
},
{
name: "Louise",
img: "nDM5aB6.png",
opts: { series: ["MS"], stage: ["st2", "st4"] }
},
{
name: "Alice (PC-98)",
img: "KaBuRTW.png",
opts: { series: ["MS"], stage: ["st3", "ex"], pc98: true }
},
{
name: "Yuki",
img: "FfcmDgp.png",
opts: { series: ["MS"], stage: ["st4"] }
},
{ name: "Mai", img: "r6w7TX1.png", opts: { series: ["MS"], stage: ["st4"] } },
{
name: "Yumeko",
img: "PcPqkdO.png",
opts: { series: ["MS"], stage: ["st5"] }
},
{
name: "Shinki",
img: "gPE95S7.png",
opts: { series: ["MS"], stage: ["st6"] }
},
{
name: "Mimi-chan",
img: "zBl2zlv.png",
opts: { series: ["PoDD"], stage: [], notgirl: true }
},
{
name: "Unzan",
img: "r5eWREh.png",
opts: { series: ["UFO", "DS", "HM", "ULiL"], stage: ["st3"], notgirl: true }
},
{
name: "Genji",
img: "LoUqOuH.png",
opts: { series: ["SoEW", "PoDD", "LLS", "MS"], stage: [], notgirl: true }
},
{
name: "Shingyoku (Male)",
img: "a5uwlgN.png",
opts: { series: ["HRtP"], stage: ["st1"], notgirl: true }
},
{
name: "YuugenMagan",
img: "IOW8GdU.png",
opts: { series: ["HRtP"], stage: ["st3"], notgirl: true }
},
{
name: "Evil Eye Sigma",
img: "rAFUMwE.png",
opts: { series: ["SoEW"], stage: ["ex"], notgirl: true }
},
{
name: "Great Catfish",
img: "BgRi9Oh.png",
opts: { series: ["Soku"], stage: ["st6"], notgirl: true }
},
{
name: "Morichika Rinnosuke",
img: "ITUhsGj.png",
opts: { series: ["book", "HM"], stage: [], notgirl: true }
},
{
name: "Fortune Teller",
img: "BYot23O.png",
opts: { series: ["book"], stage: [], notgirl: true }
},
{
name: "Hisoutensoku",
img: "P4JZ2it.png",
opts: { series: ["Soku"], stage: [], notgirl: true }
}
];

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1 @@
var LZString=function(){function o(o,r){if(!t[o]){t[o]={};for(var n=0;n<o.length;n++)t[o][o.charAt(n)]=n}return t[o][r]}var r=String.fromCharCode,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",t={},i={compressToBase64:function(o){if(null==o)return"";var r=i._compress(o,6,function(o){return n.charAt(o)});switch(r.length%4){default:case 0:return r;case 1:return r+"===";case 2:return r+"==";case 3:return r+"="}},decompressFromBase64:function(r){return null==r?"":""==r?null:i._decompress(r.length,32,function(e){return o(n,r.charAt(e))})},compressToUTF16:function(o){return null==o?"":i._compress(o,15,function(o){return r(o+32)})+" "},decompressFromUTF16:function(o){return null==o?"":""==o?null:i._decompress(o.length,16384,function(r){return o.charCodeAt(r)-32})},compressToUint8Array:function(o){for(var r=i.compress(o),n=new Uint8Array(2*r.length),e=0,t=r.length;t>e;e++){var s=r.charCodeAt(e);n[2*e]=s>>>8,n[2*e+1]=s%256}return n},decompressFromUint8Array:function(o){if(null===o||void 0===o)return i.decompress(o);for(var n=new Array(o.length/2),e=0,t=n.length;t>e;e++)n[e]=256*o[2*e]+o[2*e+1];var s=[];return n.forEach(function(o){s.push(r(o))}),i.decompress(s.join(""))},compressToEncodedURIComponent:function(o){return null==o?"":i._compress(o,6,function(o){return e.charAt(o)})},decompressFromEncodedURIComponent:function(r){return null==r?"":""==r?null:(r=r.replace(/ /g,"+"),i._decompress(r.length,32,function(n){return o(e,r.charAt(n))}))},compress:function(o){return i._compress(o,16,function(o){return r(o)})},_compress:function(o,r,n){if(null==o)return"";var e,t,i,s={},p={},u="",c="",a="",l=2,f=3,h=2,d=[],m=0,v=0;for(i=0;i<o.length;i+=1)if(u=o.charAt(i),Object.prototype.hasOwnProperty.call(s,u)||(s[u]=f++,p[u]=!0),c=a+u,Object.prototype.hasOwnProperty.call(s,c))a=c;else{if(Object.prototype.hasOwnProperty.call(p,a)){if(a.charCodeAt(0)<256){for(e=0;h>e;e++)m<<=1,v==r-1?(v=0,d.push(n(m)),m=0):v++;for(t=a.charCodeAt(0),e=0;8>e;e++)m=m<<1|1&t,v==r-1?(v=0,d.push(n(m)),m=0):v++,t>>=1}else{for(t=1,e=0;h>e;e++)m=m<<1|t,v==r-1?(v=0,d.push(n(m)),m=0):v++,t=0;for(t=a.charCodeAt(0),e=0;16>e;e++)m=m<<1|1&t,v==r-1?(v=0,d.push(n(m)),m=0):v++,t>>=1}l--,0==l&&(l=Math.pow(2,h),h++),delete p[a]}else for(t=s[a],e=0;h>e;e++)m=m<<1|1&t,v==r-1?(v=0,d.push(n(m)),m=0):v++,t>>=1;l--,0==l&&(l=Math.pow(2,h),h++),s[c]=f++,a=String(u)}if(""!==a){if(Object.prototype.hasOwnProperty.call(p,a)){if(a.charCodeAt(0)<256){for(e=0;h>e;e++)m<<=1,v==r-1?(v=0,d.push(n(m)),m=0):v++;for(t=a.charCodeAt(0),e=0;8>e;e++)m=m<<1|1&t,v==r-1?(v=0,d.push(n(m)),m=0):v++,t>>=1}else{for(t=1,e=0;h>e;e++)m=m<<1|t,v==r-1?(v=0,d.push(n(m)),m=0):v++,t=0;for(t=a.charCodeAt(0),e=0;16>e;e++)m=m<<1|1&t,v==r-1?(v=0,d.push(n(m)),m=0):v++,t>>=1}l--,0==l&&(l=Math.pow(2,h),h++),delete p[a]}else for(t=s[a],e=0;h>e;e++)m=m<<1|1&t,v==r-1?(v=0,d.push(n(m)),m=0):v++,t>>=1;l--,0==l&&(l=Math.pow(2,h),h++)}for(t=2,e=0;h>e;e++)m=m<<1|1&t,v==r-1?(v=0,d.push(n(m)),m=0):v++,t>>=1;for(;;){if(m<<=1,v==r-1){d.push(n(m));break}v++}return d.join("")},decompress:function(o){return null==o?"":""==o?null:i._decompress(o.length,32768,function(r){return o.charCodeAt(r)})},_decompress:function(o,n,e){var t,i,s,p,u,c,a,l,f=[],h=4,d=4,m=3,v="",w=[],A={val:e(0),position:n,index:1};for(i=0;3>i;i+=1)f[i]=i;for(p=0,c=Math.pow(2,2),a=1;a!=c;)u=A.val&A.position,A.position>>=1,0==A.position&&(A.position=n,A.val=e(A.index++)),p|=(u>0?1:0)*a,a<<=1;switch(t=p){case 0:for(p=0,c=Math.pow(2,8),a=1;a!=c;)u=A.val&A.position,A.position>>=1,0==A.position&&(A.position=n,A.val=e(A.index++)),p|=(u>0?1:0)*a,a<<=1;l=r(p);break;case 1:for(p=0,c=Math.pow(2,16),a=1;a!=c;)u=A.val&A.position,A.position>>=1,0==A.position&&(A.position=n,A.val=e(A.index++)),p|=(u>0?1:0)*a,a<<=1;l=r(p);break;case 2:return""}for(f[3]=l,s=l,w.push(l);;){if(A.index>o)return"";for(p=0,c=Math.pow(2,m),a=1;a!=c;)u=A.val&A.position,A.position>>=1,0==A.position&&(A.position=n,A.val=e(A.index++)),p|=(u>0?1:0)*a,a<<=1;switch(l=p){case 0:for(p=0,c=Math.pow(2,8),a=1;a!=c;)u=A.val&A.position,A.position>>=1,0==A.position&&(A.position=n,A.val=e(A.index++)),p|=(u>0?1:0)*a,a<<=1;f[d++]=r(p),l=d-1,h--;break;case 1:for(p=0,c=Math.pow(2,16),a=1;a!=c;)u=A.val&A.position,A.position>>=1,0==A.position&&(A.position=n,A.val=e(A.index++)),p|=(u>0?1:0)*a,a<<=1;f[d++]=r(p),l=d-1,h--;break;case 2:return w.join("")}if(0==h&&(h=Math.pow(2,m),m++),f[l])v=f[l];else{if(l!==d)return null;v=s+s.charAt(0)}w.push(v),f[d++]=s+v.charAt(0),h--,s=v,0==h&&(h=Math.pow(2,m),m++)}}};return i}();"function"==typeof define&&define.amd?define(function(){return LZString}):"undefined"!=typeof module&&null!=module&&(module.exports=LZString);

View file

@ -0,0 +1,836 @@
/** @type {CharData} */
let characterData = []; // Initial character data set used.
/** @type {CharData} */
let characterDataToSort = []; // Character data set after filtering.
/** @type {Options} */
let options = []; // Initial option set used.
let currentVersion = ''; // Which version of characterData and options are used.
/** @type {(boolean|boolean[])[]} */
let optTaken = []; // Records which options are set.
/** Save Data. Concatenated into array, joined into string (delimited by '|') and compressed with lz-string. */
let timestamp = 0; // savedata[0] (Unix time when sorter was started, used as initial PRNG seed and in dataset selection)
let timeTaken = 0; // savedata[1] (Number of ms elapsed when sorter ends, used as end-of-sort flag and in filename generation)
let choices = ''; // savedata[2] (String of '0', '1' and '2' that records what sorter choices are made)
let optStr = ''; // savedata[3] (String of '0' and '1' that denotes top-level option selection)
let suboptStr = ''; // savedata[4...n] (String of '0' and '1' that denotes nested option selection, separated by '|')
let timeError = false; // Shifts entire savedata array to the right by 1 and adds an empty element at savedata[0] if true.
/** Intermediate sorter data. */
let sortedIndexList = [];
let recordDataList = [];
let parentIndexList = [];
let tiedDataList = [];
let leftIndex = 0;
let leftInnerIndex = 0;
let rightIndex = 0;
let rightInnerIndex = 0;
let battleNo = 1;
let sortedNo = 0;
let pointer = 0;
/** A copy of intermediate sorter data is recorded for undo() purposes. */
let sortedIndexListPrev = [];
let recordDataListPrev = [];
let parentIndexListPrev = [];
let tiedDataListPrev = [];
let leftIndexPrev = 0;
let leftInnerIndexPrev = 0;
let rightIndexPrev = 0;
let rightInnerIndexPrev = 0;
let battleNoPrev = 1;
let sortedNoPrev = 0;
let pointerPrev = 0;
/** Miscellaneous sorter data that doesn't need to be saved for undo(). */
let finalCharacters = [];
let loading = false;
let totalBattles = 0;
let sorterURL = window.location.host + window.location.pathname;
let storedSaveType = localStorage.getItem(`${sorterURL}_saveType`);
/** Initialize script. */
function init() {
/** Define button behavior. */
document.querySelector('.starting.start.button').addEventListener('click', start);
document.querySelector('.starting.load.button').addEventListener('click', loadProgress);
document.querySelector('.left.sort.image').addEventListener('click', () => pick('left'));
document.querySelector('.right.sort.image').addEventListener('click', () => pick('right'));
document.querySelector('.sorting.tie.button').addEventListener('click', () => pick('tie'));
document.querySelector('.sorting.undo.button').addEventListener('click', undo);
document.querySelector('.sorting.save.button').addEventListener('click', () => saveProgress('Progress'));
document.querySelector('.finished.save.button').addEventListener('click', () => saveProgress('Last Result'));
document.querySelector('.finished.getimg.button').addEventListener('click', generateImage);
document.querySelector('.finished.list.button').addEventListener('click', generateTextList);
document.querySelector('.clearsave').addEventListener('click', clearProgress);
/** Define keyboard controls (up/down/left/right vimlike k/j/h/l). */
document.addEventListener('keypress', (ev) => {
/** If sorting is in progress. */
if (timestamp && !timeTaken && !loading && choices.length === battleNo - 1) {
switch(ev.key) {
case 's': case '3': saveProgress('Progress'); break;
case 'h': case 'ArrowLeft': pick('left'); break;
case 'l': case 'ArrowRight': pick('right'); break;
case 'k': case '1': case 'ArrowUp': pick('tie'); break;
case 'j': case '2': case 'ArrowDown': undo(); break;
default: break;
}
}
/** If sorting has ended. */
else if (timeTaken && choices.length === battleNo - 1) {
switch(ev.key) {
case 'k': case '1': saveProgress('Last Result'); break;
case 'j': case '2': generateImage(); break;
case 's': case '3': generateTextList(); break;
default: break;
}
} else { // If sorting hasn't started yet.
switch(ev.key) {
case '1': case 's': case 'Enter': start(); break;
case '2': case 'l': loadProgress(); break;
default: break;
}
}
});
document.querySelector('.image.selector').insertAdjacentElement('beforeend', document.createElement('select'));
/** Initialize image quantity selector for results. */
for (let i = 0; i <= 10; i++) {
const select = document.createElement('option');
select.value = i;
select.text = i;
if (i === 3) { select.selected = 'selected'; }
document.querySelector('.image.selector > select').insertAdjacentElement('beforeend', select);
}
document.querySelector('.image.selector > select').addEventListener('input', (e) => {
const imageNum = e.target.options[e.target.selectedIndex].value;
result(Number(imageNum));
});
/** Show load button if save data exists. */
if (storedSaveType) {
document.querySelector('.starting.load.button > span').insertAdjacentText('beforeend', storedSaveType);
document.querySelectorAll('.starting.button').forEach(el => {
el.style['grid-row'] = 'span 3';
el.style.display = 'block';
});
}
setLatestDataset();
/** Decode query string if available. */
if (window.location.search.slice(1) !== '') decodeQuery();
}
/** Begin sorting. */
function start() {
/** Copy data into sorting array to filter. */
characterDataToSort = characterData.slice(0);
/** Check selected options and convert to boolean array form. */
optTaken = [];
options.forEach(opt => {
if ('sub' in opt) {
if (!document.getElementById(`cbgroup-${opt.key}`).checked) optTaken.push(false);
else {
const suboptArray = opt.sub.reduce((arr, val, idx) => {
arr.push(document.getElementById(`cb-${opt.key}-${idx}`).checked);
return arr;
}, []);
optTaken.push(suboptArray);
}
} else { optTaken.push(document.getElementById(`cb-${opt.key}`).checked); }
});
/** Convert boolean array form to string form. */
optStr = '';
suboptStr = '';
optStr = optTaken
.map(val => !!val)
.reduce((str, val) => {
str += val ? '1' : '0';
return str;
}, optStr);
optTaken.forEach(val => {
if (Array.isArray(val)) {
suboptStr += '|';
suboptStr += val.reduce((str, val) => {
str += val ? '1' : '0';
return str;
}, '');
}
});
/** Filter out deselected nested criteria and remove selected criteria. */
options.forEach((opt, index) => {
if ('sub' in opt) {
if (optTaken[index]) {
const subArray = optTaken[index].reduce((subList, subBool, subIndex) => {
if (subBool) { subList.push(options[index].sub[subIndex].key); }
return subList;
}, []);
characterDataToSort = characterDataToSort.filter(char => {
if (!(opt.key in char.opts)) console.warn(`Warning: ${opt.key} not set for ${char.name}.`);
return opt.key in char.opts && char.opts[opt.key].some(key => subArray.includes(key));
});
}
} else if (optTaken[index]) {
characterDataToSort = characterDataToSort.filter(char => !char.opts[opt.key]);
}
});
if (characterDataToSort.length < 2) {
alert('Cannot sort with less than two characters. Please reselect.');
return;
}
/** Shuffle character array with timestamp seed. */
timestamp = timestamp || new Date().getTime();
if (new Date(timestamp) < new Date(currentVersion)) { timeError = true; }
Math.seedrandom(timestamp);
characterDataToSort = characterDataToSort
.map(a => [Math.random(), a])
.sort((a,b) => a[0] - b[0])
.map(a => a[1]);
/**
* tiedDataList will keep a record of indexes on which characters are equal (i.e. tied)
* to another one. recordDataList will have an interim list of sorted elements during
* the mergesort process.
*/
recordDataList = characterDataToSort.map(() => 0);
tiedDataList = characterDataToSort.map(() => -1);
/**
* Put a list of indexes that we'll be sorting into sortedIndexList. These will refer back
* to characterDataToSort.
*
* Begin splitting each element into little arrays and spread them out over sortedIndexList
* increasing its length until it become arrays of length 1 and you can't split it anymore.
*
* parentIndexList indicates each element's parent (i.e. where it was split from), except
* for the first element, which has no parent.
*/
sortedIndexList[0] = characterDataToSort.map((val, idx) => idx);
parentIndexList[0] = -1;
let midpoint = 0; // Indicates where to split the array.
let marker = 1; // Indicates where to place our newly split array.
for (let i = 0; i < sortedIndexList.length; i++) {
if (sortedIndexList[i].length > 1) {
let parent = sortedIndexList[i];
midpoint = Math.ceil(parent.length / 2);
sortedIndexList[marker] = parent.slice(0, midpoint); // Split the array in half, and put the left half into the marked index.
totalBattles += sortedIndexList[marker].length; // The result's length will add to our total number of comparisons.
parentIndexList[marker] = i; // Record where it came from.
marker++; // Increment the marker to put the right half into.
sortedIndexList[marker] = parent.slice(midpoint, parent.length); // Put the right half next to its left half.
totalBattles += sortedIndexList[marker].length; // The result's length will add to our total number of comparisons.
parentIndexList[marker] = i; // Record where it came from.
marker++; // Rinse and repeat, until we get arrays of length 1. This is initialization of merge sort.
}
}
leftIndex = sortedIndexList.length - 2; // Start with the second last value and...
rightIndex = sortedIndexList.length - 1; // the last value in the sorted list and work our way down to index 0.
leftInnerIndex = 0; // Inner indexes, because we'll be comparing the left array
rightInnerIndex = 0; // to the right array, in order to merge them into one sorted array.
/** Disable all checkboxes and hide/show appropriate parts while we preload the images. */
document.querySelectorAll('input[type=checkbox]').forEach(cb => cb.disabled = true);
document.querySelectorAll('.starting.button').forEach(el => el.style.display = 'none');
document.querySelector('.loading.button').style.display = 'block';
document.querySelector('.progress').style.display = 'block';
loading = true;
preloadImages().then(() => {
loading = false;
document.querySelector('.loading.button').style.display = 'none';
document.querySelectorAll('.sorting.button').forEach(el => el.style.display = 'block');
document.querySelectorAll('.sort.text').forEach(el => el.style.display = 'block');
display();
});
}
/** Displays the current state of the sorter. */
function display() {
const percent = Math.floor(sortedNo * 100 / totalBattles);
const leftCharIndex = sortedIndexList[leftIndex][leftInnerIndex];
const rightCharIndex = sortedIndexList[rightIndex][rightInnerIndex];
const leftChar = characterDataToSort[leftCharIndex];
const rightChar = characterDataToSort[rightCharIndex];
const charNameDisp = name => {
const charName = reduceTextWidth(name, 'Arial 12.8px', 220);
const charTooltip = name !== charName ? name : '';
return `<p title="${charTooltip}">${charName}</p>`;
};
progressBar(`Battle No. ${battleNo}`, percent);
document.querySelector('.left.sort.image').src = leftChar.img;
document.querySelector('.right.sort.image').src = rightChar.img;
document.querySelector('.left.sort.text').innerHTML = charNameDisp(leftChar.name);
document.querySelector('.right.sort.text').innerHTML = charNameDisp(rightChar.name);
/** Autopick if choice has been given. */
if (choices.length !== battleNo - 1) {
switch (Number(choices[battleNo - 1])) {
case 0: pick('left'); break;
case 1: pick('right'); break;
case 2: pick('tie'); break;
default: break;
}
} else { saveProgress('Autosave'); }
}
/**
* Sort between two character choices or tie.
*
* @param {'left'|'right'|'tie'} sortType
*/
function pick(sortType) {
if ((timeTaken && choices.length === battleNo - 1) || loading) { return; }
else if (!timestamp) { return start(); }
sortedIndexListPrev = sortedIndexList.slice(0);
recordDataListPrev = recordDataList.slice(0);
parentIndexListPrev = parentIndexList.slice(0);
tiedDataListPrev = tiedDataList.slice(0);
leftIndexPrev = leftIndex;
leftInnerIndexPrev = leftInnerIndex;
rightIndexPrev = rightIndex;
rightInnerIndexPrev = rightInnerIndex;
battleNoPrev = battleNo;
sortedNoPrev = sortedNo;
pointerPrev = pointer;
/**
* For picking 'left' or 'right':
*
* Input the selected character's index into recordDataList. Increment the pointer of
* recordDataList. Then, check if there are any ties with this character, and keep
* incrementing until we find no more ties.
*/
switch (sortType) {
case 'left': {
if (choices.length === battleNo - 1) { choices += '0'; }
recordData('left');
while (tiedDataList[recordDataList[pointer - 1]] != -1) {
recordData('left');
}
break;
}
case 'right': {
if (choices.length === battleNo - 1) { choices += '1'; }
recordData('right');
while (tiedDataList[recordDataList [pointer - 1]] != -1) {
recordData('right');
}
break;
}
/**
* For picking 'tie' (i.e. heretics):
*
* Proceed as if we picked the 'left' character. Then, we record the right character's
* index value into the list of ties (at the left character's index) and then proceed
* as if we picked the 'right' character.
*/
case 'tie': {
if (choices.length === battleNo - 1) { choices += '2'; }
recordData('left');
while (tiedDataList[recordDataList[pointer - 1]] != -1) {
recordData('left');
}
tiedDataList[recordDataList[pointer - 1]] = sortedIndexList[rightIndex][rightInnerIndex];
recordData('right');
while (tiedDataList[recordDataList [pointer - 1]] != -1) {
recordData('right');
}
break;
}
default: return;
}
/**
* Once we reach the limit of the 'right' character list, we
* insert all of the 'left' characters into the record, or vice versa.
*/
const leftListLen = sortedIndexList[leftIndex].length;
const rightListLen = sortedIndexList[rightIndex].length;
if (leftInnerIndex < leftListLen && rightInnerIndex === rightListLen) {
while (leftInnerIndex < leftListLen) {
recordData('left');
}
} else if (leftInnerIndex === leftListLen && rightInnerIndex < rightListLen) {
while (rightInnerIndex < rightListLen) {
recordData('right');
}
}
/**
* Once we reach the end of both 'left' and 'right' character lists, we can remove
* the arrays from the initial mergesort array, since they are now recorded. This
* record is a sorted version of both lists, so we can replace their original
* (unsorted) parent with a sorted version. Purge the record afterwards.
*/
if (leftInnerIndex === leftListLen && rightInnerIndex === rightListLen) {
for (let i = 0; i < leftListLen + rightListLen; i++) {
sortedIndexList[parentIndexList[leftIndex]][i] = recordDataList[i];
}
sortedIndexList.pop();
sortedIndexList.pop();
leftIndex = leftIndex - 2;
rightIndex = rightIndex - 2;
leftInnerIndex = 0;
rightInnerIndex = 0;
sortedIndexList.forEach((val, idx) => recordDataList[idx] = 0);
pointer = 0;
}
/**
* If, after shifting the 'left' index on the sorted list, we reach past the beginning
* of the sorted array, that means the entire array is now sorted. The original unsorted
* array in index 0 is now replaced with a sorted version, and we will now output this.
*/
if (leftIndex < 0) {
timeTaken = timeTaken || new Date().getTime() - timestamp;
progressBar(`Battle No. ${battleNo} - Completed!`, 100);
result();
} else {
battleNo++;
display();
}
}
/**
* Records data in recordDataList.
*
* @param {'left'|'right'} sortType Record from the left or the right character array.
*/
function recordData(sortType) {
if (sortType === 'left') {
recordDataList[pointer] = sortedIndexList[leftIndex][leftInnerIndex];
leftInnerIndex++;
} else {
recordDataList[pointer] = sortedIndexList[rightIndex][rightInnerIndex];
rightInnerIndex++;
}
pointer++;
sortedNo++;
}
/**
* Modifies the progress bar.
*
* @param {string} indicator
* @param {number} percentage
*/
function progressBar(indicator, percentage) {
document.querySelector('.progressbattle').innerHTML = indicator;
document.querySelector('.progressfill').style.width = `${percentage}%`;
document.querySelector('.progresstext').innerHTML = `${percentage}%`;
}
/**
* Shows the result of the sorter.
*
* @param {number} [imageNum=3] Number of images to display. Defaults to 3.
*/
function result(imageNum = 3) {
document.querySelectorAll('.finished.button').forEach(el => el.style.display = 'block');
document.querySelector('.image.selector').style.display = 'block';
document.querySelector('.time.taken').style.display = 'block';
document.querySelectorAll('.sorting.button').forEach(el => el.style.display = 'none');
document.querySelectorAll('.sort.text').forEach(el => el.style.display = 'none');
document.querySelector('.options').style.display = 'none';
document.querySelector('.info').style.display = 'none';
const header = '<div class="result head"><div class="left">Order</div><div class="right">Name</div></div>';
const timeStr = `This sorter was completed on ${new Date(timestamp + timeTaken).toString()} and took ${msToReadableTime(timeTaken)}. <a href="${location.protocol}//${sorterURL}">Do another sorter?</a>`;
const imgRes = (char, num) => {
const charName = reduceTextWidth(char.name, 'Arial 12px', 160);
const charTooltip = char.name !== charName ? char.name : '';
return `<div class="result image"><div class="left"><span>${num}</span></div><div class="right"><img src="${char.img}"><div><span title="${charTooltip}">${charName}</span></div></div></div>`;
}
const res = (char, num) => {
const charName = reduceTextWidth(char.name, 'Arial 12px', 160);
const charTooltip = char.name !== charName ? char.name : '';
return `<div class="result"><div class="left">${num}</div><div class="right"><span title="${charTooltip}">${charName}</span></div></div>`;
}
let rankNum = 1;
let tiedRankNum = 1;
let imageDisplay = imageNum;
const finalSortedIndexes = sortedIndexList[0].slice(0);
const resultTable = document.querySelector('.results');
const timeElem = document.querySelector('.time.taken');
resultTable.innerHTML = header;
timeElem.innerHTML = timeStr;
characterDataToSort.forEach((val, idx) => {
const characterIndex = finalSortedIndexes[idx];
const character = characterDataToSort[characterIndex];
if (imageDisplay-- > 0) {
resultTable.insertAdjacentHTML('beforeend', imgRes(character, rankNum));
} else {
resultTable.insertAdjacentHTML('beforeend', res(character, rankNum));
}
finalCharacters.push({ rank: rankNum, name: character.name });
if (idx < characterDataToSort.length - 1) {
if (tiedDataList[characterIndex] === finalSortedIndexes[idx + 1]) {
tiedRankNum++; // Indicates how many people are tied at the same rank.
} else {
rankNum += tiedRankNum; // Add it to the actual ranking, then reset it.
tiedRankNum = 1; // The default value is 1, so it increments as normal if no ties.
}
}
});
}
/** Undo previous choice. */
function undo() {
if (timeTaken) { return; }
choices = battleNo === battleNoPrev ? choices : choices.slice(0, -1);
sortedIndexList = sortedIndexListPrev.slice(0);
recordDataList = recordDataListPrev.slice(0);
parentIndexList = parentIndexListPrev.slice(0);
tiedDataList = tiedDataListPrev.slice(0);
leftIndex = leftIndexPrev;
leftInnerIndex = leftInnerIndexPrev;
rightIndex = rightIndexPrev;
rightInnerIndex = rightInnerIndexPrev;
battleNo = battleNoPrev;
sortedNo = sortedNoPrev;
pointer = pointerPrev;
display();
}
/**
* Save progress to local browser storage.
*
* @param {'Autosave'|'Progress'|'Last Result'} saveType
*/
function saveProgress(saveType) {
const saveData = generateSavedata();
localStorage.setItem(`${sorterURL}_saveData`, saveData);
localStorage.setItem(`${sorterURL}_saveType`, saveType);
if (saveType !== 'Autosave') {
const saveURL = `${location.protocol}//${sorterURL}?${saveData}`;
const inProgressText = 'You may click Load Progress after this to resume, or use this URL.';
const finishedText = 'You may use this URL to share this result, or click Load Last Result to view it again.';
window.prompt(saveType === 'Last Result' ? finishedText : inProgressText, saveURL);
}
}
/**
* Load progress from local browser storage.
*/
function loadProgress() {
const saveData = localStorage.getItem(`${sorterURL}_saveData`);
if (saveData) decodeQuery(saveData);
}
/**
* Clear progress from local browser storage.
*/
function clearProgress() {
storedSaveType = '';
localStorage.removeItem(`${sorterURL}_saveData`);
localStorage.removeItem(`${sorterURL}_saveType`);
document.querySelectorAll('.starting.start.button').forEach(el => el.style['grid-row'] = 'span 6');
document.querySelectorAll('.starting.load.button').forEach(el => el.style.display = 'none');
}
function generateImage() {
const timeFinished = timestamp + timeTaken;
const tzoffset = (new Date()).getTimezoneOffset() * 60000;
const filename = 'sort-' + (new Date(timeFinished - tzoffset)).toISOString().slice(0, -5).replace('T', '(') + ').png';
html2canvas(document.querySelector('.results')).then(canvas => {
const dataURL = canvas.toDataURL();
const imgButton = document.querySelector('.finished.getimg.button');
const resetButton = document.createElement('a');
imgButton.removeEventListener('click', generateImage);
imgButton.innerHTML = '';
imgButton.insertAdjacentHTML('beforeend', `<a href="${dataURL}" download="${filename}">Download Image</a><br><br>`);
resetButton.insertAdjacentText('beforeend', 'Reset');
resetButton.addEventListener('click', (event) => {
imgButton.addEventListener('click', generateImage);
imgButton.innerHTML = 'Generate Image';
event.stopPropagation();
});
imgButton.insertAdjacentElement('beforeend', resetButton);
});
}
function generateTextList() {
const data = finalCharacters.reduce((str, char) => {
str += `${char.rank}. ${char.name}<br>`;
return str;
}, '');
const oWindow = window.open("", "", "height=640,width=480");
oWindow.document.write(data);
}
function generateSavedata() {
const saveData = `${timeError?'|':''}${timestamp}|${timeTaken}|${choices}|${optStr}${suboptStr}`;
return LZString.compressToEncodedURIComponent(saveData);
}
/** Retrieve latest character data and options from dataset. */
function setLatestDataset() {
/** Set some defaults. */
timestamp = 0;
timeTaken = 0;
choices = '';
const latestDateIndex = Object.keys(dataSet)
.map(date => new Date(date))
.reduce((latestDateIndex, currentDate, currentIndex, array) => {
return currentDate > array[latestDateIndex] ? currentIndex : latestDateIndex;
}, 0);
currentVersion = Object.keys(dataSet)[latestDateIndex];
characterData = dataSet[currentVersion].characterData;
options = dataSet[currentVersion].options;
populateOptions();
}
/** Populate option list. */
function populateOptions() {
const optList = document.querySelector('.options');
const optInsert = (name, id, tooltip, checked = true, disabled = false) => {
return `<div><label title="${tooltip?tooltip:name}"><input id="cb-${id}" type="checkbox" ${checked?'checked':''} ${disabled?'disabled':''}> ${name}</label></div>`;
};
const optInsertLarge = (name, id, tooltip, checked = true) => {
return `<div class="large option"><label title="${tooltip?tooltip:name}"><input id="cbgroup-${id}" type="checkbox" ${checked?'checked':''}> ${name}</label></div>`;
};
/** Clear out any previous options. */
optList.innerHTML = '';
/** Insert sorter options and set grouped option behavior. */
options.forEach(opt => {
if ('sub' in opt) {
optList.insertAdjacentHTML('beforeend', optInsertLarge(opt.name, opt.key, opt.tooltip, opt.checked));
opt.sub.forEach((subopt, subindex) => {
optList.insertAdjacentHTML('beforeend', optInsert(subopt.name, `${opt.key}-${subindex}`, subopt.tooltip, subopt.checked, opt.checked === false));
});
optList.insertAdjacentHTML('beforeend', '<hr>');
const groupbox = document.getElementById(`cbgroup-${opt.key}`);
groupbox.parentElement.addEventListener('click', () => {
opt.sub.forEach((subopt, subindex) => {
document.getElementById(`cb-${opt.key}-${subindex}`).disabled = !groupbox.checked;
if (groupbox.checked) { document.getElementById(`cb-${opt.key}-${subindex}`).checked = true; }
});
});
} else {
optList.insertAdjacentHTML('beforeend', optInsert(opt.name, opt.key, opt.tooltip, opt.checked));
}
});
}
/**
* Decodes compressed shareable link query string.
* @param {string} queryString
*/
function decodeQuery(queryString = window.location.search.slice(1)) {
let successfulLoad;
try {
/**
* Retrieve data from compressed string.
* @type {string[]}
*/
const decoded = LZString.decompressFromEncodedURIComponent(queryString).split('|');
if (!decoded[0]) {
decoded.splice(0, 1);
timeError = true;
}
timestamp = Number(decoded.splice(0, 1)[0]);
timeTaken = Number(decoded.splice(0, 1)[0]);
choices = decoded.splice(0, 1)[0];
const optDecoded = decoded.splice(0, 1)[0];
const suboptDecoded = decoded.slice(0);
/**
* Get latest data set version from before the timestamp.
* If timestamp is before or after any of the datasets, get the closest one.
* If timestamp is between any of the datasets, get the one in the past, but if timeError is set, get the one in the future.
*/
const seedDate = { str: timestamp, val: new Date(timestamp) };
const dateMap = Object.keys(dataSet)
.map(date => {
return { str: date, val: new Date(date) };
})
const beforeDateIndex = dateMap
.reduce((prevIndex, currDate, currIndex) => {
return currDate.val < seedDate.val ? currIndex : prevIndex;
}, -1);
const afterDateIndex = dateMap.findIndex(date => date.val > seedDate.val);
if (beforeDateIndex === -1) {
currentVersion = dateMap[afterDateIndex].str;
} else if (afterDateIndex === -1) {
currentVersion = dateMap[beforeDateIndex].str;
} else {
currentVersion = dateMap[timeError ? afterDateIndex : beforeDateIndex].str;
}
options = dataSet[currentVersion].options;
characterData = dataSet[currentVersion].characterData;
/** Populate option list and decode options selected. */
populateOptions();
let suboptDecodedIndex = 0;
options.forEach((opt, index) => {
if ('sub' in opt) {
const optIsTrue = optDecoded[index] === '1';
document.getElementById(`cbgroup-${opt.key}`).checked = optIsTrue;
opt.sub.forEach((subopt, subindex) => {
const subIsTrue = optIsTrue ? suboptDecoded[suboptDecodedIndex][subindex] === '1' : true;
document.getElementById(`cb-${opt.key}-${subindex}`).checked = subIsTrue;
document.getElementById(`cb-${opt.key}-${subindex}`).disabled = optIsTrue;
});
suboptDecodedIndex = suboptDecodedIndex + optIsTrue ? 1 : 0;
} else { document.getElementById(`cb-${opt.key}`).checked = optDecoded[index] === '1'; }
});
successfulLoad = true;
} catch (err) {
console.error(`Error loading shareable link: ${err}`);
setLatestDataset(); // Restore to default function if loading link does not work.
}
if (successfulLoad) { start(); }
}
/**
* Preloads images in the filtered character data and converts to base64 representation.
*/
function preloadImages() {
const totalLength = characterDataToSort.length;
let imagesLoaded = 0;
const loadImage = async (src) => {
const blob = await fetch(src).then(res => res.blob());
return new Promise((res, rej) => {
const reader = new FileReader();
reader.onload = ev => {
progressBar(`Loading Image ${++imagesLoaded}`, Math.floor(imagesLoaded * 100 / totalLength));
res(ev.target.result);
};
reader.onerror = rej;
reader.readAsDataURL(blob);
});
};
return Promise.all(characterDataToSort.map(async (char, idx) => {
characterDataToSort[idx].img = await loadImage(imageRoot + char.img);
}));
}
/**
* Returns a readable time string from milliseconds.
*
* @param {number} milliseconds
*/
function msToReadableTime (milliseconds) {
let t = Math.floor(milliseconds/1000);
const years = Math.floor(t / 31536000);
t = t - (years * 31536000);
const months = Math.floor(t / 2592000);
t = t - (months * 2592000);
const days = Math.floor(t / 86400);
t = t - (days * 86400);
const hours = Math.floor(t / 3600);
t = t - (hours * 3600);
const minutes = Math.floor(t / 60);
t = t - (minutes * 60);
const content = [];
if (years) content.push(years + " year" + (years > 1 ? "s" : ""));
if (months) content.push(months + " month" + (months > 1 ? "s" : ""));
if (days) content.push(days + " day" + (days > 1 ? "s" : ""));
if (hours) content.push(hours + " hour" + (hours > 1 ? "s" : ""));
if (minutes) content.push(minutes + " minute" + (minutes > 1 ? "s" : ""));
if (t) content.push(t + " second" + (t > 1 ? "s" : ""));
return content.slice(0,3).join(', ');
}
/**
* Reduces text to a certain rendered width.
*
* @param {string} text Text to reduce.
* @param {string} font Font applied to text. Example "12px Arial".
* @param {number} width Width of desired width in px.
*/
function reduceTextWidth(text, font, width) {
const canvas = reduceTextWidth.canvas || (reduceTextWidth.canvas = document.createElement("canvas"));
const context = canvas.getContext("2d");
context.font = font;
if (context.measureText(text).width < width * 0.8) {
return text;
} else {
let reducedText = text;
while (context.measureText(reducedText).width + context.measureText('..').width > width * 0.8) {
reducedText = reducedText.slice(0, -1);
}
return reducedText + '..';
}
}
window.onload = init;

View file

@ -0,0 +1 @@
!function(a,b){function c(c,j,k){var n=[];j=1==j?{entropy:!0}:j||{};var s=g(f(j.entropy?[c,i(a)]:null==c?h():c,3),n),t=new d(n),u=function(){for(var a=t.g(m),b=p,c=0;a<q;)a=(a+c)*l,b*=l,c=t.g(1);for(;a>=r;)a/=2,b/=2,c>>>=1;return(a+c)/b};return u.int32=function(){return 0|t.g(4)},u.quick=function(){return t.g(4)/4294967296},u.double=u,g(i(t.S),a),(j.pass||k||function(a,c,d,f){return f&&(f.S&&e(f,t),a.state=function(){return e(t,{})}),d?(b[o]=a,c):a})(u,s,"global"in j?j.global:this==b,j.state)}function d(a){var b,c=a.length,d=this,e=0,f=d.i=d.j=0,g=d.S=[];for(c||(a=[c++]);e<l;)g[e]=e++;for(e=0;e<l;e++)g[e]=g[f=s&f+a[e%c]+(b=g[e])],g[f]=b;(d.g=function(a){for(var b,c=0,e=d.i,f=d.j,g=d.S;a--;)b=g[e=s&e+1],c=c*l+g[s&(g[e]=g[f=s&f+b])+(g[f]=b)];return d.i=e,d.j=f,c})(l)}function e(a,b){return b.i=a.i,b.j=a.j,b.S=a.S.slice(),b}function f(a,b){var c,d=[],e=typeof a;if(b&&"object"==e)for(c in a)try{d.push(f(a[c],b-1))}catch(a){}return d.length?d:"string"==e?a:a+"\0"}function g(a,b){for(var c,d=a+"",e=0;e<d.length;)b[s&e]=s&(c^=19*b[s&e])+d.charCodeAt(e++);return i(b)}function h(){try{var b;return j&&(b=j.randomBytes)?b=b(l):(b=new Uint8Array(l),(k.crypto||k.msCrypto).getRandomValues(b)),i(b)}catch(b){var c=k.navigator,d=c&&c.plugins;return[+new Date,k,d,k.screen,i(a)]}}function i(a){return String.fromCharCode.apply(0,a)}var j,k=this,l=256,m=6,n=52,o="random",p=b.pow(l,m),q=b.pow(2,n),r=2*q,s=l-1;if(b["seed"+o]=c,g(b.random(),a),"object"==typeof module&&module.exports){module.exports=c;try{j=require("crypto")}catch(a){}}else"function"==typeof define&&define.amd&&define(function(){return c})}([],Math);

BIN
public/fwroot.crt Normal file

Binary file not shown.

View file

@ -45,30 +45,24 @@ if(isset($_POST['temp']) && isset($_POST['hash']) && isset($_POST['time'])) {
return;
}
if(isset($_GET['since'])) {
$since = (int)filter_input(INPUT_GET, 'since', FILTER_SANITIZE_NUMBER_INT);
$temps = $pdo->prepare('SELECT `temp_celcius`, UNIX_TIMESTAMP(`temp_datetime`) AS `temp_datetime` FROM `fm_temperature` WHERE `temp_datetime` > FROM_UNIXTIME(:since) AND `temp_datetime` > NOW() - INTERVAL 1 DAY ORDER BY `temp_datetime` ASC LIMIT 288');
$temps->bindValue('since', $since);
if(isset($_GET['latest'])) {
$temps = $pdo->prepare('SELECT `temp_celcius` AS `tc`, UNIX_TIMESTAMP(`temp_datetime`) AS `dt` FROM `fm_temperature` ORDER BY `temp_datetime` DESC LIMIT 1');
$temps->execute();
header('Content-Type: application/json; charset=utf-8');
echo json_encode($temps->fetch(PDO::FETCH_ASSOC));
return;
}
if(isset($_GET['daily'])) {
$temps = $pdo->prepare('SELECT AVG(`temp_celcius`) AS `tc`, DATE_FORMAT(MIN(`temp_datetime`), \'%H:%i\') AS `ts` FROM `fm_temperature` WHERE `temp_datetime` > NOW() - INTERVAL 1 DAY GROUP BY FLOOR(UNIX_TIMESTAMP(`temp_datetime`) / (15 * 60)) ORDER BY `temp_datetime` ASC LIMIT 96');
$temps->execute();
header('Content-Type: application/json; charset=utf-8');
echo json_encode($temps->fetchAll(PDO::FETCH_ASSOC));
return;
}
if(isset($_GET['since_3mo'])) {
$since = (int)filter_input(INPUT_GET, 'since_3mo', FILTER_SANITIZE_NUMBER_INT);
$temps = $pdo->prepare('SELECT MAX(`temp_celcius`) AS `temp_celcius_max`, AVG(`temp_celcius`) AS `temp_celcius_avg`, MIN(`temp_celcius`) AS `temp_celcius_min`, UNIX_TIMESTAMP(DATE(`temp_datetime`)) AS `temp_datetime` FROM `fm_temperature` WHERE `temp_datetime` > DATE(FROM_UNIXTIME(:since)) AND `temp_datetime` > NOW() - INTERVAL 3 MONTH GROUP BY DATE(`temp_datetime`) ORDER BY `temp_datetime` ASC LIMIT 92');
$temps->bindValue('since', $since);
$temps->execute();
header('Content-Type: application/json; charset=utf-8');
echo json_encode($temps->fetchAll(PDO::FETCH_ASSOC));
return;
}
if(isset($_GET['since_6mo'])) {
$since = (int)filter_input(INPUT_GET, 'since_6mo', FILTER_SANITIZE_NUMBER_INT);
$temps = $pdo->prepare('SELECT MAX(`temp_celcius`) AS `temp_celcius_max`, AVG(`temp_celcius`) AS `temp_celcius_avg`, MIN(`temp_celcius`) AS `temp_celcius_min`, UNIX_TIMESTAMP(DATE(`temp_datetime`)) AS `temp_datetime` FROM `fm_temperature` WHERE `temp_datetime` > DATE(FROM_UNIXTIME(:since)) AND `temp_datetime` > NOW() - INTERVAL 6 MONTH GROUP BY DATE(`temp_datetime`) ORDER BY `temp_datetime` ASC LIMIT 92');
$temps->bindValue('since', $since);
if(isset($_GET['weekly'])) {
$temps = $pdo->prepare('SELECT MAX(`temp_celcius`) AS `tcmax`, AVG(`temp_celcius`) AS `tcavg`, MIN(`temp_celcius`) AS `tcmin`, DATE_FORMAT(`temp_datetime`, \'%X-%V\') AS `tw` FROM `fm_temperature` WHERE `temp_datetime` > NOW() - INTERVAL 1 YEAR GROUP BY YEARWEEK(`temp_datetime`) ORDER BY `temp_datetime` ASC LIMIT 52');
$temps->execute();
header('Content-Type: application/json; charset=utf-8');
echo json_encode($temps->fetchAll(PDO::FETCH_ASSOC));
@ -110,6 +104,9 @@ if(!empty($_GET['siri'])) {
font: 12px/20px Tahoma, Geneva, 'Dejavu Sans', Arial, Helvetica, sans-serif;
padding: 1px;
}
h2 {
font-family: 'Electrolize', Verdana, 'Dejavu Sans', Arial, Helvetica, sans-serif;
}
.current {
text-align: center;
background-color: #333;
@ -131,6 +128,45 @@ if(!empty($_GET['siri'])) {
margin: 10px;
padding: 10px;
border-radius: 10px;
color: #666;
}
.chart-legend {
text-align: center;
}
.chart-body {
width: 100%;
height: 400px;
text-align: center;
}
.chart-labels {
width: 100%;
text-align: center;
}
.legend {
display: inline-block;
text-align: left;
min-width: 100px;
}
.legend-icon {
background-color: var(--lc);
width: 10px;
height: 10px;
display: inline-block;
}
.legend-name {
color: var(--lc);
font-weight: 700;
display: inline-block;
}
.bars {
height: 100%;
display: inline-block;
bottom: 0;
}
.bars-bar {
width: 100%;
bottom: 0;
position: absolute;
}
</style>
</head>
@ -144,188 +180,263 @@ if(!empty($_GET['siri'])) {
<span id="-last-datetime">--:--:--</span>
</div>
</div>
<div class="chart">
<canvas id="-chart" width="400" height="170"></canvas>
<div class="chart" id="-chart-hr">
<h2>15 minutely Temperature (24hr)</h2>
<p style="font-size: .8em">Add 1 or 2 hours to the displayed hour, I cannot be bothered to handle it myself.</p>
<div class="chart-body">
</div>
<div class="chart-labels" style="height: 35px;">
</div>
</div>
<div class="chart">
<canvas id="-chart-mo" width="400" height="170"></canvas>
<div class="chart" id="-chart-wk">
<h2>Weekly Temperature (1yr)</h2>
<div class="chart-legend">
<div class="legend" style="--lc: #800;">
<div class="legend-icon"></div>
<div class="legend-name">Maximum</div>
</div>
<div class="legend" style="--lc: #080;">
<div class="legend-icon"></div>
<div class="legend-name">Average</div>
</div>
<div class="legend" style="--lc: #008;">
<div class="legend-icon"></div>
<div class="legend-name">Minimum</div>
</div>
</div>
<div class="chart-body">
</div>
<div class="chart-labels" style="height: 40px;">
</div>
</div>
</div>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js@3.3.2/dist/chart.min.js"></script>
<script type="text/javascript">
var temp = {
last: 0,
lastMo: 0,
history: [],
historyMo: [],
lastTemp: null,
lastDateTime: null,
chart: null,
chartMo: null,
chartHr: null,
chartHrBody: null,
chartHrLabels: null,
chartHrBars: 24 * 60 / 15,
chartWk: null,
chartWkBody: null,
chartWkLabels: null,
chartWkBars: 52,
};
temp.getLastTemperature = function() {
if(this.history.length === 0)
return {temp_datetime: 0, temp_celcius: 0};
return this.history[this.history.length - 1];
temp.weightedNumber = function(n1, n2, w) {
w = Math.min(1, Math.max(0, w));
return Math.round((n1 * w) + (n2 * (1 - w)));
};
temp.refresh = function() {
temp.weightedColour = function(c1, c2, w) {
if(typeof c1 === 'number')
c1 = [(c1 >> 16) & 0xFF, (c1 >> 8) & 0xFF, c1 & 0xFF];
if(typeof c2 === 'number')
c2 = [(c2 >> 16) & 0xFF, (c2 >> 8) & 0xFF, c2 & 0xFF];
var rgb = [
this.weightedNumber(c1[0], c2[0], w),
this.weightedNumber(c1[1], c2[1], w),
this.weightedNumber(c1[2], c2[2], w),
];
return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
};
temp.weightedColourHex = function(c1, c2, w) {
return '#' + this.weightedColour(c1, c2, w).toString(16).padStart(6, '0');
};
temp.refreshLatest = function() {
var xhr = new XMLHttpRequest;
xhr.onload = function() {
var temps = JSON.parse(xhr.responseText);
for(var i = 0; i < temps.length; ++i) {
var temp = temps[i];
this.last = temp.temp_datetime;
this.history.push(temp);
}
this.refreshUI();
this.updateLatest(JSON.parse(xhr.responseText));
}.bind(this);
xhr.open('GET', '/temp.php?since=' + encodeURIComponent(parseInt(this.last).toString()));
xhr.open('GET', '/temp.php?latest');
xhr.send();
};
temp.refreshUI = function() {
var temp = this.getLastTemperature();
this.lastTemp.textContent = (parseInt(temp.temp_celcius * 10) / 10).toFixed(1).toLocaleString();
this.lastDateTime.textContent = new Date(temp.temp_datetime * 1000).toLocaleString();
var take = Math.min(288, this.history.length),
dataset = this.chart.data.datasets[0];
this.chart.data.labels = [];
dataset.data = [];
for(var i = this.history.length - take; i < this.history.length; ++i) {
var temp = this.history[i];
this.chart.data.labels.push(new Date(temp.temp_datetime * 1000).toLocaleString());
dataset.data.push(temp.temp_celcius);
}
this.chart.update();
temp.updateLatest = function(temp) {
this.lastTemp.textContent = (parseInt(temp.tc * 10) / 10).toFixed(1).toLocaleString();
this.lastDateTime.textContent = new Date(temp.dt * 1000).toLocaleString();
};
temp.refreshMo = function() {
temp.refreshHr = function() {
var xhr = new XMLHttpRequest;
xhr.onload = function() {
var temps = JSON.parse(xhr.responseText);
for(var i = 0; i < temps.length; ++i) {
var temp = temps[i];
this.lastMo = temp.temp_datetime;
this.historyMo.push(temp);
}
this.refreshUIMo();
this.updateHr(JSON.parse(xhr.responseText));
}.bind(this);
xhr.open('GET', '/temp.php?since_6mo=' + encodeURIComponent(parseInt(this.lastMo).toString()));
xhr.open('GET', '/temp.php?daily');
xhr.send();
};
temp.refreshUIMo = function() {
var take = Math.min(92, this.historyMo.length),
datasetMax = this.chartMo.data.datasets[0],
datasetAvg = this.chartMo.data.datasets[1],
datasetMin = this.chartMo.data.datasets[2];
this.chart.data.labels = [];
datasetMax.data = [];
datasetAvg.data = [];
datasetMin.data = [];
for(var i = this.historyMo.length - take; i < this.historyMo.length; ++i) {
var temp = this.historyMo[i];
this.chartMo.data.labels.push(new Date(temp.temp_datetime * 1000).toDateString());
datasetMax.data.push(temp.temp_celcius_max);
datasetAvg.data.push(temp.temp_celcius_avg);
datasetMin.data.push(temp.temp_celcius_min);
}
temp.updateHr = function(temps) {
this.chartHrBody.innerHTML = '';
this.chartHrLabels.innerHTML = '';
this.chartMo.update();
for(var i = 0; i < temps.length; ++i) {
var temp = temps[i],
width = (100 / (temps.length + 12)).toString() + '%';
var label = document.createElement('div'),
labelTxt = document.createElement('div');
labelTxt.textContent = temp.ts;
labelTxt.style.transform = 'rotate(270deg)';
labelTxt.style.fontSize = '.8em';
labelTxt.style.top = '15px';
label.title = temp.ts;
label.className = 'chart-body-bars bars';
label.style.width = width;
label.style.margin = '0 .5px';
label.appendChild(labelTxt);
this.chartHrLabels.appendChild(label);
var bars = document.createElement('div');
bars.className = 'chart-body-bars bars';
bars.style.width = width;
bars.style.margin = '0 .5px';
this.chartHrBody.appendChild(bars);
var bar = document.createElement('div'),
barTxt = document.createElement('div');
bar.className = 'bars-bar';
var weight = ((temp.tc - 15) / 20);
barTxt.textContent = temp.tc.toFixed(1);
barTxt.style.transform = 'rotate(270deg)';
barTxt.style.fontSize = '.8em';
barTxt.style.top = '5px';
barTxt.style.color = '#fff';
bar.appendChild(barTxt);
bar.title = temp.tc.toFixed(2) + ' °C';
bar.style.backgroundColor = this.weightedColourHex(0xFF0000, 0xFF, weight);
bar.style.overflow = 'hidden';
bar.style.height = (weight * 100).toString() + '%';
bars.appendChild(bar);
}
};
temp.refreshWk = function() {
var xhr = new XMLHttpRequest;
xhr.onload = function() {
this.updateWk(JSON.parse(xhr.responseText));
}.bind(this);
xhr.open('GET', '/temp.php?weekly');
xhr.send();
};
temp.updateWk = function(temps) {
this.chartWkBody.innerHTML = '';
this.chartWkLabels.innerHTML = '';
for(var i = 0; i < temps.length; ++i) {
var temp = temps[i],
width = (100 / (this.chartWkBars + 3)).toString() + '%';
var label = document.createElement('div'),
labelTxt = document.createElement('div');
labelTxt.textContent = temp.tw;
labelTxt.style.transform = 'rotate(270deg)';
labelTxt.style.fontSize = '.8em';
labelTxt.style.top = '20px';
label.title = temp.tw;
label.className = 'chart-body-bars bars';
label.style.width = width;
label.style.margin = '0 .5px';
label.appendChild(labelTxt);
this.chartWkLabels.appendChild(label);
var bars = document.createElement('div');
bars.className = 'chart-body-bars bars';
bars.style.width = width;
bars.style.margin = '0 .5px';
this.chartWkBody.appendChild(bars);
var max = document.createElement('div'),
maxTxt = document.createElement('div'),
avg = document.createElement('div'),
avgTxt = document.createElement('div'),
min = document.createElement('div'),
minTxt = document.createElement('div');
max.className = avg.className = min.className = 'bars-bar';
var wMin = (temp.tcmin - 15) / 15,
wAvg = (temp.tcavg - 20) / 10,
wMax = (temp.tcmax - 20) / 15;
maxTxt.textContent = temp.tcmax.toFixed(1);
maxTxt.style.transform = 'rotate(270deg)';
maxTxt.style.fontSize = '.8em';
maxTxt.style.top = '5px';
maxTxt.style.color = '#fff';
max.appendChild(maxTxt);
max.title = temp.tcmax.toFixed(2) + ' °C';
max.style.backgroundColor = this.weightedColourHex(0xFF0000, 0x800000, wMax);
max.style.overflow = 'hidden';
max.style.height = (((temp.tcmax - 15) / 20) * 100).toString() + '%';
bars.appendChild(max);
avgTxt.textContent = temp.tcavg.toFixed(1);
avgTxt.style.transform = 'rotate(270deg)';
avgTxt.style.fontSize = '.8em';
avgTxt.style.top = '5px';
avgTxt.style.color = '#fff';
avg.appendChild(avgTxt);
avg.title = temp.tcavg.toFixed(2) + ' °C';
avg.style.backgroundColor = this.weightedColourHex(0xFF00, 0x8000, wAvg);
avg.style.overflow = 'hidden';
avg.style.height = (((temp.tcavg - 15) / 20) * 100).toString() + '%';
bars.appendChild(avg);
minTxt.textContent = temp.tcmin.toFixed(1);
minTxt.style.transform = 'rotate(270deg)';
minTxt.style.fontSize = '.8em';
minTxt.style.top = '5px';
minTxt.style.color = '#fff';
min.appendChild(minTxt);
min.title = temp.tcmin.toFixed(2) + ' °C';
min.style.backgroundColor = this.weightedColourHex(0x80, 0xFF, wMin);
min.style.overflow = 'hidden';
min.style.height = (((temp.tcmin - 15) / 20) * 100).toString() + '%';
bars.appendChild(min);
}
};
temp.loadFake = function() {
this.updateHr(this.fakeForHourly());
this.updateWk(this.fakeForWeekly());
};
temp.fakeForHourly = function() {
var temps = [];
for(var i = 0; i < this.chartHrBars; ++i)
temps.push({ tc: (20 * ((i + 1) / this.chartHrBars)) + 15, ts: i.toString() });
return temps;
};
temp.fakeForWeekly = function() {
var wMin = (temp.tcmin - 15) / 15,
wAvg = (temp.tcavg - 20) / 10,
wMax = (temp.tcmax - 20) / 15;
var temps = [];
for(var i = 0; i < this.chartWkBars; ++i)
temps.push({
tcmax: (15 * ((i + 1) / this.chartWkBars)) + 20,
tcavg: (10 * ((i + 1) / this.chartWkBars)) + 20,
tcmin: (15 * ((i + 1) / this.chartWkBars)) + 15,
tw: i.toString(),
});
return temps;
};
window.onload = function() {
temp.lastTemp = document.getElementById('-last-temp');
temp.lastDateTime = document.getElementById('-last-datetime');
var ctx = document.getElementById('-chart').getContext('2d');
temp.chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [
{
label: 'Temperature',
data: [],
borderColor: '#111',
backgroundColor: '#222',
},
],
},
options: {
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Temperature History',
},
},
scales: {
y: {
suggestedMax: 34,
suggestedMin: 20,
ticks: {
stepSize: 1,
},
},
},
},
});
temp.chartHr = document.getElementById('-chart-hr');
temp.chartHrBody = temp.chartHr.getElementsByClassName('chart-body')[0];
temp.chartHrLabels = temp.chartHr.getElementsByClassName('chart-labels')[0];
temp.refresh();
setInterval(temp.refresh.bind(temp), 5 * 60 * 1000);
temp.chartWk = document.getElementById('-chart-wk');
temp.chartWkBody = temp.chartWk.getElementsByClassName('chart-body')[0];
temp.chartWkLabels = temp.chartWk.getElementsByClassName('chart-labels')[0];
var ctxMo = document.getElementById('-chart-mo').getContext('2d');
temp.chartMo = new Chart(ctxMo, {
type: 'line',
data: {
datasets: [
{
label: 'Maximum Temperature',
data: [],
borderColor: '#400',
backgroundColor: '#800',
},
{
label: 'Average Temperature',
data: [],
borderColor: '#040',
backgroundColor: '#080',
},
{
label: 'Minimum Temperature',
data: [],
borderColor: '#004',
backgroundColor: '#008',
},
],
},
options: {
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Daily Temperature (6 months)',
},
},
scales: {
y: {
suggestedMax: 34,
suggestedMin: 20,
ticks: {
stepSize: 1,
},
},
},
},
});
temp.refreshLatest();
setInterval(temp.refreshLatest.bind(temp), 5 * 60 * 1000);
temp.refreshMo();
setInterval(temp.refreshMo.bind(temp), 31 * 24 * 60 * 1000);
temp.refreshHr();
setInterval(temp.refreshHr.bind(temp), 15 * 60 * 1000);
temp.refreshWk();
setInterval(temp.refreshWk.bind(temp), 7 * 24 * 60 * 1000);
};
</script>
</body>
</html>
</html>

331
public/temp2.php Normal file
View file

@ -0,0 +1,331 @@
<?php
define('FM_TEMP_KEY', 'kND861svbydCLywutu78tRmlpWdzoRLPcVZSrnxerh3KbLwfwvfvgC5hzax8gvYm');
define('FM_TEMP_INT', 10);
ini_set('display_errors', 'on');
error_reporting(-1);
date_default_timezone_set('UTC');
mb_internal_encoding('UTF-8');
try {
$pdo = new PDO('mysql:unix_socket=/var/run/mysqld/mysqld.sock;dbname=website;charset=utf8mb4', 'website', 'A3NjVvHRkHAxiYgk8MM4ZrCwrLVyPIYX', [
PDO::ATTR_CASE => PDO::CASE_NATURAL,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
PDO::ATTR_STRINGIFY_FETCHES => false,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::MYSQL_ATTR_INIT_COMMAND => "
SET SESSION
sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION',
time_zone = '+00:00';
",
]);
} catch(Exception $ex) {
http_response_code(500);
echo '<h3>Unable to connect to database</h3>';
die($ex->getMessage());
}
if(isset($_POST['temp']) && isset($_POST['hash']) && isset($_POST['time'])) {
$temp = (string)filter_input(INPUT_POST, 'temp');
$hash = (string)filter_input(INPUT_POST, 'hash');
$time = (string)filter_input(INPUT_POST, 'time', FILTER_SANITIZE_NUMBER_INT);
if(!hash_equals(hash_hmac('sha256', $temp . '|' . $time, FM_TEMP_KEY), $hash))
return;
$time = floor((int)json_decode($time) / FM_TEMP_INT);
if($time !== floor(time() / FM_TEMP_INT))
return;
$insert = $pdo->prepare('INSERT INTO `fm_temperature` (`temp_celcius`) VALUES (:temp)');
$insert->bindValue('temp', (string)json_decode($temp));
$insert->execute();
return;
}
if(isset($_GET['since'])) {
$since = (int)filter_input(INPUT_GET, 'since', FILTER_SANITIZE_NUMBER_INT);
$temps = $pdo->prepare('SELECT `temp_celcius`, UNIX_TIMESTAMP(`temp_datetime`) AS `temp_datetime` FROM `fm_temperature` WHERE `temp_datetime` > FROM_UNIXTIME(:since) AND `temp_datetime` > NOW() - INTERVAL 1 DAY ORDER BY `temp_datetime` ASC LIMIT 288');
$temps->bindValue('since', $since);
$temps->execute();
header('Content-Type: application/json; charset=utf-8');
echo json_encode($temps->fetchAll(PDO::FETCH_ASSOC));
return;
}
if(isset($_GET['since_3mo'])) {
$since = (int)filter_input(INPUT_GET, 'since_3mo', FILTER_SANITIZE_NUMBER_INT);
$temps = $pdo->prepare('SELECT MAX(`temp_celcius`) AS `temp_celcius_max`, AVG(`temp_celcius`) AS `temp_celcius_avg`, MIN(`temp_celcius`) AS `temp_celcius_min`, UNIX_TIMESTAMP(DATE(`temp_datetime`)) AS `temp_datetime` FROM `fm_temperature` WHERE `temp_datetime` > DATE(FROM_UNIXTIME(:since)) AND `temp_datetime` > NOW() - INTERVAL 3 MONTH GROUP BY DATE(`temp_datetime`) ORDER BY `temp_datetime` ASC LIMIT 92');
$temps->bindValue('since', $since);
$temps->execute();
header('Content-Type: application/json; charset=utf-8');
echo json_encode($temps->fetchAll(PDO::FETCH_ASSOC));
return;
}
if(isset($_GET['since_6mo'])) {
$since = (int)filter_input(INPUT_GET, 'since_6mo', FILTER_SANITIZE_NUMBER_INT);
$temps = $pdo->prepare('SELECT MAX(`temp_celcius`) AS `temp_celcius_max`, AVG(`temp_celcius`) AS `temp_celcius_avg`, MIN(`temp_celcius`) AS `temp_celcius_min`, UNIX_TIMESTAMP(DATE(`temp_datetime`)) AS `temp_datetime` FROM `fm_temperature` WHERE `temp_datetime` > DATE(FROM_UNIXTIME(:since)) AND `temp_datetime` > NOW() - INTERVAL 6 MONTH GROUP BY DATE(`temp_datetime`) ORDER BY `temp_datetime` ASC LIMIT 92');
$temps->bindValue('since', $since);
$temps->execute();
header('Content-Type: application/json; charset=utf-8');
echo json_encode($temps->fetchAll(PDO::FETCH_ASSOC));
return;
}
if(!empty($_GET['siri'])) {
header('Content-Type: text/plain; charset=utf-8');
$temps = $pdo->prepare('SELECT `temp_celcius`, UNIX_TIMESTAMP(`temp_datetime`) AS `temp_datetime` FROM `fm_temperature` ORDER BY `temp_datetime` DESC LIMIT 1');
$temps->execute();
$temps = $temps->fetch(PDO::FETCH_ASSOC);
date_default_timezone_set('Europe/Amsterdam');
printf('It was %2$.1f°C at %1$s.', date('H:i:s', $temps['temp_datetime']), $temps['temp_celcius']);
return;
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>Room Temperature</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
<link href="/css/electrolize/style.css" type="text/css" rel="stylesheet"/>
<style type="text/css">
* {
margin: 0;
padding: 0;
box-sizing: border-box;
position: relative;
outline-style: none;
}
html, body {
width: 100%;
height: 100%;
}
body {
background-color: #111;
color: #fff;
font: 12px/20px Tahoma, Geneva, 'Dejavu Sans', Arial, Helvetica, sans-serif;
padding: 1px;
}
.current {
text-align: center;
background-color: #333;
margin: 10px;
padding: 10px;
border-radius: 10px;
}
.current-temp {
font-family: 'Electrolize', Verdana, 'Dejavu Sans', Arial, Helvetica, sans-serif;
font-size: 3em;
line-height: 1.2em;
}
.current-datetime {
font-size: .9em;
line-height: 1.4em;
}
.chart {
background-color: #ddd;
margin: 10px;
padding: 10px;
border-radius: 10px;
}
</style>
</head>
<body>
<div class="main">
<div class="current">
<div class="current-temp">
<span id="-last-temp">--</span> °C
</div>
<div class="current-datetime">
<span id="-last-datetime">--:--:--</span>
</div>
</div>
<div class="chart">
<canvas id="-chart" width="400" height="170"></canvas>
</div>
<div class="chart">
<canvas id="-chart-mo" width="400" height="170"></canvas>
</div>
</div>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js@3.3.2/dist/chart.min.js"></script>
<script type="text/javascript">
var temp = {
last: 0,
lastMo: 0,
history: [],
historyMo: [],
lastTemp: null,
lastDateTime: null,
chart: null,
chartMo: null,
};
temp.getLastTemperature = function() {
if(this.history.length === 0)
return {temp_datetime: 0, temp_celcius: 0};
return this.history[this.history.length - 1];
};
temp.refresh = function() {
var xhr = new XMLHttpRequest;
xhr.onload = function() {
var temps = JSON.parse(xhr.responseText);
for(var i = 0; i < temps.length; ++i) {
var temp = temps[i];
this.last = temp.temp_datetime;
this.history.push(temp);
}
this.refreshUI();
}.bind(this);
xhr.open('GET', '/temp2.php?since=' + encodeURIComponent(parseInt(this.last).toString()));
xhr.send();
};
temp.refreshUI = function() {
var temp = this.getLastTemperature();
this.lastTemp.textContent = (parseInt(temp.temp_celcius * 10) / 10).toFixed(1).toLocaleString();
this.lastDateTime.textContent = new Date(temp.temp_datetime * 1000).toLocaleString();
var take = Math.min(288, this.history.length),
dataset = this.chart.data.datasets[0];
this.chart.data.labels = [];
dataset.data = [];
for(var i = this.history.length - take; i < this.history.length; ++i) {
var temp = this.history[i];
this.chart.data.labels.push(new Date(temp.temp_datetime * 1000).toLocaleString());
dataset.data.push(temp.temp_celcius);
}
this.chart.update();
};
temp.refreshMo = function() {
var xhr = new XMLHttpRequest;
xhr.onload = function() {
var temps = JSON.parse(xhr.responseText);
for(var i = 0; i < temps.length; ++i) {
var temp = temps[i];
this.lastMo = temp.temp_datetime;
this.historyMo.push(temp);
}
this.refreshUIMo();
}.bind(this);
xhr.open('GET', '/temp2.php?since_6mo=' + encodeURIComponent(parseInt(this.lastMo).toString()));
xhr.send();
};
temp.refreshUIMo = function() {
var take = Math.min(92, this.historyMo.length),
datasetMax = this.chartMo.data.datasets[0],
datasetAvg = this.chartMo.data.datasets[1],
datasetMin = this.chartMo.data.datasets[2];
this.chart.data.labels = [];
datasetMax.data = [];
datasetAvg.data = [];
datasetMin.data = [];
for(var i = this.historyMo.length - take; i < this.historyMo.length; ++i) {
var temp = this.historyMo[i];
this.chartMo.data.labels.push(new Date(temp.temp_datetime * 1000).toDateString());
datasetMax.data.push(temp.temp_celcius_max);
datasetAvg.data.push(temp.temp_celcius_avg);
datasetMin.data.push(temp.temp_celcius_min);
}
this.chartMo.update();
};
window.onload = function() {
temp.lastTemp = document.getElementById('-last-temp');
temp.lastDateTime = document.getElementById('-last-datetime');
var ctx = document.getElementById('-chart').getContext('2d');
temp.chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [
{
label: 'Temperature',
data: [],
borderColor: '#111',
backgroundColor: '#222',
},
],
},
options: {
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Temperature History',
},
},
scales: {
y: {
suggestedMax: 34,
suggestedMin: 20,
ticks: {
stepSize: 1,
},
},
},
},
});
temp.refresh();
setInterval(temp.refresh.bind(temp), 5 * 60 * 1000);
var ctxMo = document.getElementById('-chart-mo').getContext('2d');
temp.chartMo = new Chart(ctxMo, {
type: 'line',
data: {
datasets: [
{
label: 'Maximum Temperature',
data: [],
borderColor: '#400',
backgroundColor: '#800',
},
{
label: 'Average Temperature',
data: [],
borderColor: '#040',
backgroundColor: '#080',
},
{
label: 'Minimum Temperature',
data: [],
borderColor: '#004',
backgroundColor: '#008',
},
],
},
options: {
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Daily Temperature (6 months)',
},
},
scales: {
y: {
suggestedMax: 34,
suggestedMin: 20,
ticks: {
stepSize: 1,
},
},
},
},
});
temp.refreshMo();
setInterval(temp.refreshMo.bind(temp), 31 * 24 * 60 * 1000);
};
</script>
</body>
</html>