Add form for manga
This commit is contained in:
parent
49bd468aa4
commit
d746de34ea
3
.gitignore
vendored
3
.gitignore
vendored
@ -4,8 +4,9 @@
|
|||||||
vendor
|
vendor
|
||||||
app/cache/*
|
app/cache/*
|
||||||
app/logs/*
|
app/logs/*
|
||||||
public/images/*
|
|
||||||
public/js/cache/*
|
public/js/cache/*
|
||||||
|
public/images/*
|
||||||
|
public/cache/*
|
||||||
composer.lock
|
composer.lock
|
||||||
*.sqlite
|
*.sqlite
|
||||||
*.db
|
*.db
|
||||||
|
@ -42,9 +42,9 @@ A self-hosted client that allows custom formatting of data from the hummingbird
|
|||||||
2. Configure settings in `app/config/config.php` to your liking
|
2. Configure settings in `app/config/config.php` to your liking
|
||||||
3. Create the following directories if they don't exist, and make sure they are world writable
|
3. Create the following directories if they don't exist, and make sure they are world writable
|
||||||
* app/cache
|
* app/cache
|
||||||
|
* public/js/cache
|
||||||
* public/images/manga
|
* public/images/manga
|
||||||
* public/images/anime
|
* public/images/anime
|
||||||
* public/cache
|
|
||||||
|
|
||||||
#### Anime Collection Additional Installation
|
#### Anime Collection Additional Installation
|
||||||
* Run `php /vendor/bin/phinx migrate -e development` to create the database tables
|
* Run `php /vendor/bin/phinx migrate -e development` to create the database tables
|
||||||
|
@ -56,4 +56,4 @@ $path_to = '';
|
|||||||
| The folder where javascript files exist, in relation to the document root
|
| The folder where javascript files exist, in relation to the document root
|
||||||
|
|
|
|
||||||
*/
|
*/
|
||||||
$js_root = $config['asset_dir'] . '/';
|
$js_root = $config['asset_dir'] . '/js/';
|
@ -13,92 +13,45 @@
|
|||||||
|
|
||||||
// --------------------------------------------------------------------------
|
// --------------------------------------------------------------------------
|
||||||
|
|
||||||
$bower_packages = ['jquery', 'datatables', 'mustache.js'];
|
|
||||||
$bower_file_map = [];
|
|
||||||
|
|
||||||
foreach($bower_packages as $package)
|
|
||||||
{
|
|
||||||
$bower_file_map[$package] = [];
|
|
||||||
$json = json_decode(file_get_contents(__DIR__ . "/../../public/bower_components/{$package}/bower.json"));
|
|
||||||
|
|
||||||
if ( ! is_array($json->main))
|
|
||||||
{
|
|
||||||
$json->main = [$json->main];
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach($json->main as $file)
|
|
||||||
{
|
|
||||||
if (stristr($file, '.js') !== FALSE)
|
|
||||||
{
|
|
||||||
array_push($bower_file_map[$package], "bower_components/{$package}/{$file}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Merge together bower configs and local files
|
|
||||||
*
|
|
||||||
* @param string|array $bower - array of bower components to include
|
|
||||||
* @param string|array $local - array of local js files to include
|
|
||||||
* @return array - group array
|
|
||||||
*/
|
|
||||||
function create_group($bower, $local=[])
|
|
||||||
{
|
|
||||||
global $bower_file_map;
|
|
||||||
$group = [];
|
|
||||||
|
|
||||||
foreach((array) $bower as $component)
|
|
||||||
{
|
|
||||||
$group = array_merge($group, $bower_file_map[$component]);
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach((array) $local as $file)
|
|
||||||
{
|
|
||||||
$group[] = $file;
|
|
||||||
}
|
|
||||||
|
|
||||||
return $group;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This is the config array for javascript files to concatenate and minify
|
* This is the config array for javascript files to concatenate and minify
|
||||||
*/
|
*/
|
||||||
$map = [
|
return [
|
||||||
/*
|
/*
|
||||||
For each group create an array like so
|
For each group create an array like so
|
||||||
|
|
||||||
'my_group' => array(
|
'my_group' => array(
|
||||||
'path/to/js/file1.js',
|
'path/to/file1.js',
|
||||||
'path/to/js/file2.js'
|
'path/to/file2.js'
|
||||||
),
|
),
|
||||||
*/
|
*/
|
||||||
'base' => create_group('jquery', [
|
'base' => [
|
||||||
'js/base.js',
|
'lib/zepto.js',
|
||||||
]),
|
'base/base.js',
|
||||||
'event' => create_group([], 'js/events.js'),
|
],
|
||||||
'table' => create_group([], 'js/sort_tables.js'),
|
'event' => [
|
||||||
'table_edit' => create_group([], [
|
'base/events.js',
|
||||||
'js/sort_tables.js',
|
],
|
||||||
'js/anime_edit.js',
|
'table' => [
|
||||||
'js/manga_edit.js',
|
'base/sort_tables.js',
|
||||||
]),
|
],
|
||||||
'edit' => create_group([],[
|
'table_edit' => [
|
||||||
'js/anime_edit.js',
|
'sort_tables.js',
|
||||||
'js/manga_edit.js'
|
'anime_edit.js',
|
||||||
]),
|
'manga_edit.js',
|
||||||
'anime_collection' => create_group('mustache.js', [
|
],
|
||||||
'bower_components/jquery-throttle-debounce/jquery.ba-throttle-debounce.js',
|
'edit' => [
|
||||||
'js/anime_collection.js'
|
'anime_edit.js',
|
||||||
]),
|
'manga_edit.js',
|
||||||
'manga_collection' => create_group('mustache.js', [
|
],
|
||||||
'bower_components/jquery-throttle-debounce/jquery.ba-throttle-debounce.js',
|
'anime_collection' => [
|
||||||
'js/manga_collection.js'
|
'lib/mustache.js',
|
||||||
]),
|
'anime_collection.js',
|
||||||
|
],
|
||||||
|
'manga_collection' => [
|
||||||
|
'lib/mustache.js',
|
||||||
|
'manga_collection.js',
|
||||||
|
],
|
||||||
];
|
];
|
||||||
|
|
||||||
//print_r($map);
|
|
||||||
//die();
|
|
||||||
|
|
||||||
return $map;
|
|
||||||
|
|
||||||
// End of js_groups.php
|
// End of js_groups.php
|
@ -56,6 +56,38 @@ return [
|
|||||||
'action' => 'add',
|
'action' => 'add',
|
||||||
'verb' => 'post'
|
'verb' => 'post'
|
||||||
],
|
],
|
||||||
|
'anime_detail' => [
|
||||||
|
'path' => '/anime/details/{id}',
|
||||||
|
'action' => 'details',
|
||||||
|
'tokens' => [
|
||||||
|
'id' => '[a-z0-9\-]+'
|
||||||
|
]
|
||||||
|
],
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
// Manga Routes
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
'manga_search' => [
|
||||||
|
'path' => '/manga/search',
|
||||||
|
'action' => 'search',
|
||||||
|
],
|
||||||
|
'manga_add_form' => [
|
||||||
|
'path' => '/manga/add',
|
||||||
|
'action' => 'add_form',
|
||||||
|
'verb' => 'get'
|
||||||
|
],
|
||||||
|
'manga_add' => [
|
||||||
|
'path' => '/manga/add',
|
||||||
|
'action' => 'add',
|
||||||
|
'verb' => 'post'
|
||||||
|
],
|
||||||
|
'manga_edit_form' => [
|
||||||
|
'path' => '/manga/edit/{id}{status}',
|
||||||
|
'action' => 'edit',
|
||||||
|
'tokens' => [
|
||||||
|
'id' => '[0-9a-z_]+',
|
||||||
|
'status' => '[a-zA-z\- ]+',
|
||||||
|
]
|
||||||
|
],
|
||||||
// ---------------------------------------------------------------------
|
// ---------------------------------------------------------------------
|
||||||
// Anime Collection Routes
|
// Anime Collection Routes
|
||||||
// ---------------------------------------------------------------------
|
// ---------------------------------------------------------------------
|
||||||
|
@ -0,0 +1,39 @@
|
|||||||
|
<?php if ($auth->is_authenticated()): ?>
|
||||||
|
<main>
|
||||||
|
<h2>Add Manga to your List</h2>
|
||||||
|
<form action="<?= $action_url ?>" method="post">
|
||||||
|
<section>
|
||||||
|
<div class="cssload-loader" hidden="hidden">
|
||||||
|
<div class="cssload-inner cssload-one"></div>
|
||||||
|
<div class="cssload-inner cssload-two"></div>
|
||||||
|
<div class="cssload-inner cssload-three"></div>
|
||||||
|
</div>
|
||||||
|
<label for="search">Search for manga by name: <input type="search" id="search" /></label>
|
||||||
|
<section id="series_list" class="media-wrap">
|
||||||
|
</section>
|
||||||
|
</section>
|
||||||
|
<br />
|
||||||
|
<table class="form">
|
||||||
|
<tbody>
|
||||||
|
<tr>
|
||||||
|
<td><label for="status">Reading Status</label></td>
|
||||||
|
<td>
|
||||||
|
<select name="status" id="status">
|
||||||
|
<?php foreach($status_list as $status_key => $status_title): ?>
|
||||||
|
<option value="<?= $status_key ?>"><?= $status_title ?></option>
|
||||||
|
<?php endforeach ?>
|
||||||
|
</select>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td> </td>
|
||||||
|
<td>
|
||||||
|
<button type="submit">Save</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</form>
|
||||||
|
</main>
|
||||||
|
<script src="<?= $urlGenerator->asset_url('js.php?g=manga_collection') ?>"></script>
|
||||||
|
<?php endif ?>
|
@ -1,4 +1,7 @@
|
|||||||
<main>
|
<main>
|
||||||
|
<?php if ($auth->is_authenticated()): ?>
|
||||||
|
<a class="bracketed" href="<?= $urlGenerator->url('manga/add') ?>">Add Item</a>
|
||||||
|
<?php endif ?>
|
||||||
<?php if (empty($sections)): ?>
|
<?php if (empty($sections)): ?>
|
||||||
<h3>There's nothing here!</h3>
|
<h3>There's nothing here!</h3>
|
||||||
<?php else: ?>
|
<?php else: ?>
|
||||||
|
@ -1,4 +1,7 @@
|
|||||||
<main>
|
<main>
|
||||||
|
<?php if ($auth->is_authenticated()): ?>
|
||||||
|
<a class="bracketed" href="<?= $urlGenerator->url('manga/add') ?>">Add Item</a>
|
||||||
|
<?php endif ?>
|
||||||
<?php if (empty($sections)): ?>
|
<?php if (empty($sections)): ?>
|
||||||
<h3>There's nothing here!</h3>
|
<h3>There's nothing here!</h3>
|
||||||
<?php else: ?>
|
<?php else: ?>
|
||||||
|
@ -1,20 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "HummingbirdAnimeClient",
|
|
||||||
"homepage": "https://github.com/timw4mail/HummingBirdAnimeClient",
|
|
||||||
"authors": [
|
|
||||||
"Timothy J Warren <tim@timshomepage.net>"
|
|
||||||
],
|
|
||||||
"description": "Frontend stuff for php app",
|
|
||||||
"main": "",
|
|
||||||
"moduleType": [
|
|
||||||
"globals"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
|
||||||
"private": true,
|
|
||||||
"dependencies": {
|
|
||||||
"jquery": "^2.2.0",
|
|
||||||
"datatables": "DataTables#^1.10.10",
|
|
||||||
"jquery-throttle-debounce": "*",
|
|
||||||
"mustache.js": "mustache#^2.2.1"
|
|
||||||
}
|
|
||||||
}
|
|
@ -12,7 +12,7 @@ button {
|
|||||||
}
|
}
|
||||||
|
|
||||||
table {
|
table {
|
||||||
/*width:85%;*/
|
min-width: 85%;
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -19,7 +19,7 @@ button {
|
|||||||
}
|
}
|
||||||
|
|
||||||
table {
|
table {
|
||||||
/*width:85%;*/
|
min-width:85%;
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -31,7 +31,6 @@ td {
|
|||||||
thead td, thead th {
|
thead td, thead th {
|
||||||
padding:0.5em;
|
padding:0.5em;
|
||||||
padding:0.5rem;
|
padding:0.5rem;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
input[type=number] {
|
input[type=number] {
|
||||||
|
@ -89,7 +89,8 @@ function google_min($new_file)
|
|||||||
// Show error if exists
|
// Show error if exists
|
||||||
if ( ! empty($error_obj->errors))
|
if ( ! empty($error_obj->errors))
|
||||||
{
|
{
|
||||||
echo json_encode($error_obj, JSON_PRETTY_PRINT);
|
$error_json = json_encode($error_obj, JSON_PRETTY_PRINT);
|
||||||
|
echo "console.error(${error_json});";
|
||||||
die();
|
die();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2,17 +2,9 @@
|
|||||||
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
function search(query, callback)
|
const search = (tempHtml, query) => {
|
||||||
{
|
|
||||||
var endpoint = '//' + document.location.host + '/collection/search';
|
|
||||||
return $.get(AnimeClient.url('/collection/search'), {'query':query}, callback);
|
|
||||||
}
|
|
||||||
|
|
||||||
$.get('/public/templates/ajax-search-results.html').done(tempHtml => {
|
|
||||||
$('#search').on('keypress', $.throttle(750, function(e) {
|
|
||||||
$('.cssload-loader').removeAttr('hidden');
|
$('.cssload-loader').removeAttr('hidden');
|
||||||
let query = encodeURIComponent($(this).val());
|
$.get(AnimeClient.url('/collection/search'), {'query':query}, (searchResults, status) => {
|
||||||
$.get(AnimeClient.url('/collection/search'), {'query':query}).done((searchResults) => {
|
|
||||||
$('.cssload-loader').attr('hidden', 'hidden');
|
$('.cssload-loader').attr('hidden', 'hidden');
|
||||||
|
|
||||||
// Give mustache a key to iterate over
|
// Give mustache a key to iterate over
|
||||||
@ -22,25 +14,16 @@
|
|||||||
|
|
||||||
Mustache.parse(tempHtml);
|
Mustache.parse(tempHtml);
|
||||||
$('#series_list').html(Mustache.render(tempHtml, searchResults));
|
$('#series_list').html(Mustache.render(tempHtml, searchResults));
|
||||||
}).fail(() => {
|
|
||||||
$('.cssload-loader').attr('hidden', 'hidden');
|
|
||||||
});
|
});
|
||||||
}));
|
|
||||||
});
|
|
||||||
|
|
||||||
/*$.get('/public/templates/ajax-search-results.html', tempHtml => {
|
|
||||||
$('#search').on('keypress', $.throttle(750, function(e) {
|
|
||||||
var query = encodeURIComponent($(this).val());
|
|
||||||
search(query, function(searchResults) {
|
|
||||||
// Give mustache a key to iterate over
|
|
||||||
searchResults = {
|
|
||||||
anime: searchResults
|
|
||||||
};
|
};
|
||||||
|
|
||||||
Mustache.parse(tempHtml);
|
$.get('/public/templates/anime-ajax-search-results.html', tempHtml => {
|
||||||
var rendered = Mustache.render(tempHtml, searchResults);
|
$('#search').on('keypress', AnimeClient.throttle(250, function(e) {
|
||||||
$('#series_list').html(rendered);
|
let query = encodeURIComponent($(this).val());
|
||||||
});
|
console.log($(this).val());
|
||||||
|
|
||||||
|
search(tempHtml, query);
|
||||||
}));
|
}));
|
||||||
});*/
|
});
|
||||||
})(jQuery, AnimeClient);
|
|
||||||
|
})(Zepto, AnimeClient);
|
@ -1,14 +1,12 @@
|
|||||||
/**
|
/**
|
||||||
* Javascript for editing anime, if logged in
|
* Javascript for editing anime, if logged in
|
||||||
*/
|
*/
|
||||||
(($, AnimeClient, w) => {
|
(($, AnimeClient) => {
|
||||||
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
// Action to increment episode count
|
// Action to increment episode count
|
||||||
$('body.anime.list').on('click', '.plus_one', function(e) {
|
$('body.anime.list').on('click', '.plus_one', function(e) {
|
||||||
//e.stopPropagation();
|
|
||||||
|
|
||||||
let self = this;
|
let self = this;
|
||||||
let this_sel = $(this);
|
let this_sel = $(this);
|
||||||
let parent_sel = $(this).closest('article, td');
|
let parent_sel = $(this).closest('article, td');
|
||||||
@ -39,22 +37,24 @@
|
|||||||
$.ajax({
|
$.ajax({
|
||||||
data: data,
|
data: data,
|
||||||
dataType: 'json',
|
dataType: 'json',
|
||||||
method: 'POST',
|
type: 'POST',
|
||||||
mimeType: 'application/json',
|
mimeType: 'application/json',
|
||||||
url: AnimeClient.url('/anime/update'),
|
url: AnimeClient.url('/anime/update'),
|
||||||
}).done((res) => {
|
success: (res) => {
|
||||||
if (res.status === 'completed') {
|
if (res.status === 'completed') {
|
||||||
$(this).closest('article, tr').hide();
|
$(this).closest('article, tr').hide();
|
||||||
}
|
}
|
||||||
|
|
||||||
AnimeClient.showMessage('success', `Sucessfully updated ${title}`);
|
AnimeClient.showMessage('success', `Sucessfully updated ${title}`);
|
||||||
parent_sel.find('.completed_number').text(++watched_count);
|
parent_sel.find('.completed_number').text(++watched_count);
|
||||||
|
AnimeClient.scrollToTop();
|
||||||
// scroll to top
|
},
|
||||||
w.scroll(0,0);
|
error: (xhr, errorType, error) => {
|
||||||
}).fail(() => {
|
console.error(error);
|
||||||
AnimeClient.showMessage('error', `Failed to updated ${title}`);
|
AnimeClient.showMessage('error', `Failed to updated ${title}. `);
|
||||||
|
AnimeClient.scrollToTop();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
})(jQuery, AnimeClient, window);
|
})(Zepto, AnimeClient);
|
@ -1,45 +0,0 @@
|
|||||||
const AnimeClient = (function($) {
|
|
||||||
|
|
||||||
'use strict';
|
|
||||||
|
|
||||||
return {
|
|
||||||
/**
|
|
||||||
* Display a message box
|
|
||||||
*
|
|
||||||
* @param {String} type - message type: info, error, success
|
|
||||||
* @param {String} message - the message itself
|
|
||||||
* @return {void}
|
|
||||||
*/
|
|
||||||
showMessage(type, message) {
|
|
||||||
let template = `
|
|
||||||
<div class="message ${type}">
|
|
||||||
<span class="icon"></span>
|
|
||||||
${message}
|
|
||||||
<span class="close"></span>
|
|
||||||
</div>`;
|
|
||||||
|
|
||||||
if ($(".message").length > 0)
|
|
||||||
{
|
|
||||||
$(".message").replaceWith(template);
|
|
||||||
$(".message").show();
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
$("header").append(template);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
/**
|
|
||||||
* Generate a full url from a relative path
|
|
||||||
*
|
|
||||||
* @param {String} path - url path
|
|
||||||
* @return {String} - full url
|
|
||||||
*/
|
|
||||||
url(path) {
|
|
||||||
let uri = `//${document.location.host}`;
|
|
||||||
uri += (path.charAt(0) === '/') ? path : `/${path}`;
|
|
||||||
|
|
||||||
return uri;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
})(jQuery);
|
|
74
public/js/base/base.js
Normal file
74
public/js/base/base.js
Normal file
@ -0,0 +1,74 @@
|
|||||||
|
const AnimeClient = (function($, w) {
|
||||||
|
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
return {
|
||||||
|
/**
|
||||||
|
* Scroll to the top of the Page
|
||||||
|
*
|
||||||
|
* @return {void}
|
||||||
|
*/
|
||||||
|
scrollToTop() {
|
||||||
|
w.scroll(0,0);
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Display a message box
|
||||||
|
*
|
||||||
|
* @param {String} type - message type: info, error, success
|
||||||
|
* @param {String} message - the message itself
|
||||||
|
* @return {void}
|
||||||
|
*/
|
||||||
|
showMessage(type, message) {
|
||||||
|
let template = `
|
||||||
|
<div class="message ${type}">
|
||||||
|
<span class="icon"></span>
|
||||||
|
${message}
|
||||||
|
<span class="close"></span>
|
||||||
|
</div>`;
|
||||||
|
|
||||||
|
if ($(".message").length > 0) {
|
||||||
|
$(".message").replaceWith(template);
|
||||||
|
$(".message").show();
|
||||||
|
} else {
|
||||||
|
$("header").append(template);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Generate a full url from a relative path
|
||||||
|
*
|
||||||
|
* @param {String} path - url path
|
||||||
|
* @return {String} - full url
|
||||||
|
*/
|
||||||
|
url(path) {
|
||||||
|
let uri = `//${document.location.host}`;
|
||||||
|
uri += (path.charAt(0) === '/') ? path : `/${path}`;
|
||||||
|
|
||||||
|
return uri;
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Throttle execution of a function
|
||||||
|
*
|
||||||
|
* @see https://remysharp.com/2010/07/21/throttling-function-calls
|
||||||
|
* @see https://jsfiddle.net/jonathansampson/m7G64/
|
||||||
|
* @param {Number} interval - the minimum throttle time in ms
|
||||||
|
* @param {Function} fn - the function to throttle
|
||||||
|
* @param {Object} scope - the 'this' object for the function
|
||||||
|
* @return {void}
|
||||||
|
*/
|
||||||
|
throttle(interval, fn, scope) {
|
||||||
|
var wait = false;
|
||||||
|
return function () {
|
||||||
|
var context = scope || this;
|
||||||
|
var args = arguments;
|
||||||
|
|
||||||
|
if ( ! wait) {
|
||||||
|
fn.apply(context, args);
|
||||||
|
wait = true;
|
||||||
|
setTimeout(function() {
|
||||||
|
wait = false;
|
||||||
|
}, interval);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
})(Zepto, window);
|
@ -1,5 +1,5 @@
|
|||||||
/**
|
/**
|
||||||
* jQuery event handlers
|
* Event handlers
|
||||||
*/
|
*/
|
||||||
(($) => {
|
(($) => {
|
||||||
|
|
||||||
@ -10,4 +10,4 @@
|
|||||||
$(this).hide();
|
$(this).hide();
|
||||||
});
|
});
|
||||||
|
|
||||||
})(jQuery);
|
})(Zepto);
|
629
public/js/lib/mustache.js
Normal file
629
public/js/lib/mustache.js
Normal file
@ -0,0 +1,629 @@
|
|||||||
|
/*!
|
||||||
|
* mustache.js - Logic-less {{mustache}} templates with JavaScript
|
||||||
|
* http://github.com/janl/mustache.js
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*global define: false Mustache: true*/
|
||||||
|
|
||||||
|
(function defineMustache (global, factory) {
|
||||||
|
if (typeof exports === 'object' && exports && typeof exports.nodeName !== 'string') {
|
||||||
|
factory(exports); // CommonJS
|
||||||
|
} else if (typeof define === 'function' && define.amd) {
|
||||||
|
define(['exports'], factory); // AMD
|
||||||
|
} else {
|
||||||
|
global.Mustache = {};
|
||||||
|
factory(global.Mustache); // script, wsh, asp
|
||||||
|
}
|
||||||
|
}(this, function mustacheFactory (mustache) {
|
||||||
|
|
||||||
|
var objectToString = Object.prototype.toString;
|
||||||
|
var isArray = Array.isArray || function isArrayPolyfill (object) {
|
||||||
|
return objectToString.call(object) === '[object Array]';
|
||||||
|
};
|
||||||
|
|
||||||
|
function isFunction (object) {
|
||||||
|
return typeof object === 'function';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* More correct typeof string handling array
|
||||||
|
* which normally returns typeof 'object'
|
||||||
|
*/
|
||||||
|
function typeStr (obj) {
|
||||||
|
return isArray(obj) ? 'array' : typeof obj;
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeRegExp (string) {
|
||||||
|
return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Null safe way of checking whether or not an object,
|
||||||
|
* including its prototype, has a given property
|
||||||
|
*/
|
||||||
|
function hasProperty (obj, propName) {
|
||||||
|
return obj != null && typeof obj === 'object' && (propName in obj);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
|
||||||
|
// See https://github.com/janl/mustache.js/issues/189
|
||||||
|
var regExpTest = RegExp.prototype.test;
|
||||||
|
function testRegExp (re, string) {
|
||||||
|
return regExpTest.call(re, string);
|
||||||
|
}
|
||||||
|
|
||||||
|
var nonSpaceRe = /\S/;
|
||||||
|
function isWhitespace (string) {
|
||||||
|
return !testRegExp(nonSpaceRe, string);
|
||||||
|
}
|
||||||
|
|
||||||
|
var entityMap = {
|
||||||
|
'&': '&',
|
||||||
|
'<': '<',
|
||||||
|
'>': '>',
|
||||||
|
'"': '"',
|
||||||
|
"'": ''',
|
||||||
|
'/': '/',
|
||||||
|
'`': '`',
|
||||||
|
'=': '='
|
||||||
|
};
|
||||||
|
|
||||||
|
function escapeHtml (string) {
|
||||||
|
return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap (s) {
|
||||||
|
return entityMap[s];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
var whiteRe = /\s*/;
|
||||||
|
var spaceRe = /\s+/;
|
||||||
|
var equalsRe = /\s*=/;
|
||||||
|
var curlyRe = /\s*\}/;
|
||||||
|
var tagRe = /#|\^|\/|>|\{|&|=|!/;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Breaks up the given `template` string into a tree of tokens. If the `tags`
|
||||||
|
* argument is given here it must be an array with two string values: the
|
||||||
|
* opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
|
||||||
|
* course, the default is to use mustaches (i.e. mustache.tags).
|
||||||
|
*
|
||||||
|
* A token is an array with at least 4 elements. The first element is the
|
||||||
|
* mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
|
||||||
|
* did not contain a symbol (i.e. {{myValue}}) this element is "name". For
|
||||||
|
* all text that appears outside a symbol this element is "text".
|
||||||
|
*
|
||||||
|
* The second element of a token is its "value". For mustache tags this is
|
||||||
|
* whatever else was inside the tag besides the opening symbol. For text tokens
|
||||||
|
* this is the text itself.
|
||||||
|
*
|
||||||
|
* The third and fourth elements of the token are the start and end indices,
|
||||||
|
* respectively, of the token in the original template.
|
||||||
|
*
|
||||||
|
* Tokens that are the root node of a subtree contain two more elements: 1) an
|
||||||
|
* array of tokens in the subtree and 2) the index in the original template at
|
||||||
|
* which the closing tag for that section begins.
|
||||||
|
*/
|
||||||
|
function parseTemplate (template, tags) {
|
||||||
|
if (!template)
|
||||||
|
return [];
|
||||||
|
|
||||||
|
var sections = []; // Stack to hold section tokens
|
||||||
|
var tokens = []; // Buffer to hold the tokens
|
||||||
|
var spaces = []; // Indices of whitespace tokens on the current line
|
||||||
|
var hasTag = false; // Is there a {{tag}} on the current line?
|
||||||
|
var nonSpace = false; // Is there a non-space char on the current line?
|
||||||
|
|
||||||
|
// Strips all whitespace tokens array for the current line
|
||||||
|
// if there was a {{#tag}} on it and otherwise only space.
|
||||||
|
function stripSpace () {
|
||||||
|
if (hasTag && !nonSpace) {
|
||||||
|
while (spaces.length)
|
||||||
|
delete tokens[spaces.pop()];
|
||||||
|
} else {
|
||||||
|
spaces = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
hasTag = false;
|
||||||
|
nonSpace = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var openingTagRe, closingTagRe, closingCurlyRe;
|
||||||
|
function compileTags (tagsToCompile) {
|
||||||
|
if (typeof tagsToCompile === 'string')
|
||||||
|
tagsToCompile = tagsToCompile.split(spaceRe, 2);
|
||||||
|
|
||||||
|
if (!isArray(tagsToCompile) || tagsToCompile.length !== 2)
|
||||||
|
throw new Error('Invalid tags: ' + tagsToCompile);
|
||||||
|
|
||||||
|
openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*');
|
||||||
|
closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1]));
|
||||||
|
closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1]));
|
||||||
|
}
|
||||||
|
|
||||||
|
compileTags(tags || mustache.tags);
|
||||||
|
|
||||||
|
var scanner = new Scanner(template);
|
||||||
|
|
||||||
|
var start, type, value, chr, token, openSection;
|
||||||
|
while (!scanner.eos()) {
|
||||||
|
start = scanner.pos;
|
||||||
|
|
||||||
|
// Match any text between tags.
|
||||||
|
value = scanner.scanUntil(openingTagRe);
|
||||||
|
|
||||||
|
if (value) {
|
||||||
|
for (var i = 0, valueLength = value.length; i < valueLength; ++i) {
|
||||||
|
chr = value.charAt(i);
|
||||||
|
|
||||||
|
if (isWhitespace(chr)) {
|
||||||
|
spaces.push(tokens.length);
|
||||||
|
} else {
|
||||||
|
nonSpace = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
tokens.push([ 'text', chr, start, start + 1 ]);
|
||||||
|
start += 1;
|
||||||
|
|
||||||
|
// Check for whitespace on the current line.
|
||||||
|
if (chr === '\n')
|
||||||
|
stripSpace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Match the opening tag.
|
||||||
|
if (!scanner.scan(openingTagRe))
|
||||||
|
break;
|
||||||
|
|
||||||
|
hasTag = true;
|
||||||
|
|
||||||
|
// Get the tag type.
|
||||||
|
type = scanner.scan(tagRe) || 'name';
|
||||||
|
scanner.scan(whiteRe);
|
||||||
|
|
||||||
|
// Get the tag value.
|
||||||
|
if (type === '=') {
|
||||||
|
value = scanner.scanUntil(equalsRe);
|
||||||
|
scanner.scan(equalsRe);
|
||||||
|
scanner.scanUntil(closingTagRe);
|
||||||
|
} else if (type === '{') {
|
||||||
|
value = scanner.scanUntil(closingCurlyRe);
|
||||||
|
scanner.scan(curlyRe);
|
||||||
|
scanner.scanUntil(closingTagRe);
|
||||||
|
type = '&';
|
||||||
|
} else {
|
||||||
|
value = scanner.scanUntil(closingTagRe);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Match the closing tag.
|
||||||
|
if (!scanner.scan(closingTagRe))
|
||||||
|
throw new Error('Unclosed tag at ' + scanner.pos);
|
||||||
|
|
||||||
|
token = [ type, value, start, scanner.pos ];
|
||||||
|
tokens.push(token);
|
||||||
|
|
||||||
|
if (type === '#' || type === '^') {
|
||||||
|
sections.push(token);
|
||||||
|
} else if (type === '/') {
|
||||||
|
// Check section nesting.
|
||||||
|
openSection = sections.pop();
|
||||||
|
|
||||||
|
if (!openSection)
|
||||||
|
throw new Error('Unopened section "' + value + '" at ' + start);
|
||||||
|
|
||||||
|
if (openSection[1] !== value)
|
||||||
|
throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
|
||||||
|
} else if (type === 'name' || type === '{' || type === '&') {
|
||||||
|
nonSpace = true;
|
||||||
|
} else if (type === '=') {
|
||||||
|
// Set the tags for the next time around.
|
||||||
|
compileTags(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make sure there are no open sections when we're done.
|
||||||
|
openSection = sections.pop();
|
||||||
|
|
||||||
|
if (openSection)
|
||||||
|
throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
|
||||||
|
|
||||||
|
return nestTokens(squashTokens(tokens));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Combines the values of consecutive text tokens in the given `tokens` array
|
||||||
|
* to a single token.
|
||||||
|
*/
|
||||||
|
function squashTokens (tokens) {
|
||||||
|
var squashedTokens = [];
|
||||||
|
|
||||||
|
var token, lastToken;
|
||||||
|
for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
|
||||||
|
token = tokens[i];
|
||||||
|
|
||||||
|
if (token) {
|
||||||
|
if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
|
||||||
|
lastToken[1] += token[1];
|
||||||
|
lastToken[3] = token[3];
|
||||||
|
} else {
|
||||||
|
squashedTokens.push(token);
|
||||||
|
lastToken = token;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return squashedTokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Forms the given array of `tokens` into a nested tree structure where
|
||||||
|
* tokens that represent a section have two additional items: 1) an array of
|
||||||
|
* all tokens that appear in that section and 2) the index in the original
|
||||||
|
* template that represents the end of that section.
|
||||||
|
*/
|
||||||
|
function nestTokens (tokens) {
|
||||||
|
var nestedTokens = [];
|
||||||
|
var collector = nestedTokens;
|
||||||
|
var sections = [];
|
||||||
|
|
||||||
|
var token, section;
|
||||||
|
for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
|
||||||
|
token = tokens[i];
|
||||||
|
|
||||||
|
switch (token[0]) {
|
||||||
|
case '#':
|
||||||
|
case '^':
|
||||||
|
collector.push(token);
|
||||||
|
sections.push(token);
|
||||||
|
collector = token[4] = [];
|
||||||
|
break;
|
||||||
|
case '/':
|
||||||
|
section = sections.pop();
|
||||||
|
section[5] = token[2];
|
||||||
|
collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
collector.push(token);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nestedTokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A simple string scanner that is used by the template parser to find
|
||||||
|
* tokens in template strings.
|
||||||
|
*/
|
||||||
|
function Scanner (string) {
|
||||||
|
this.string = string;
|
||||||
|
this.tail = string;
|
||||||
|
this.pos = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns `true` if the tail is empty (end of string).
|
||||||
|
*/
|
||||||
|
Scanner.prototype.eos = function eos () {
|
||||||
|
return this.tail === '';
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tries to match the given regular expression at the current position.
|
||||||
|
* Returns the matched text if it can match, the empty string otherwise.
|
||||||
|
*/
|
||||||
|
Scanner.prototype.scan = function scan (re) {
|
||||||
|
var match = this.tail.match(re);
|
||||||
|
|
||||||
|
if (!match || match.index !== 0)
|
||||||
|
return '';
|
||||||
|
|
||||||
|
var string = match[0];
|
||||||
|
|
||||||
|
this.tail = this.tail.substring(string.length);
|
||||||
|
this.pos += string.length;
|
||||||
|
|
||||||
|
return string;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Skips all text until the given regular expression can be matched. Returns
|
||||||
|
* the skipped string, which is the entire tail if no match can be made.
|
||||||
|
*/
|
||||||
|
Scanner.prototype.scanUntil = function scanUntil (re) {
|
||||||
|
var index = this.tail.search(re), match;
|
||||||
|
|
||||||
|
switch (index) {
|
||||||
|
case -1:
|
||||||
|
match = this.tail;
|
||||||
|
this.tail = '';
|
||||||
|
break;
|
||||||
|
case 0:
|
||||||
|
match = '';
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
match = this.tail.substring(0, index);
|
||||||
|
this.tail = this.tail.substring(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.pos += match.length;
|
||||||
|
|
||||||
|
return match;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents a rendering context by wrapping a view object and
|
||||||
|
* maintaining a reference to the parent context.
|
||||||
|
*/
|
||||||
|
function Context (view, parentContext) {
|
||||||
|
this.view = view;
|
||||||
|
this.cache = { '.': this.view };
|
||||||
|
this.parent = parentContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new context using the given view with this context
|
||||||
|
* as the parent.
|
||||||
|
*/
|
||||||
|
Context.prototype.push = function push (view) {
|
||||||
|
return new Context(view, this);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the value of the given name in this context, traversing
|
||||||
|
* up the context hierarchy if the value is absent in this context's view.
|
||||||
|
*/
|
||||||
|
Context.prototype.lookup = function lookup (name) {
|
||||||
|
var cache = this.cache;
|
||||||
|
|
||||||
|
var value;
|
||||||
|
if (cache.hasOwnProperty(name)) {
|
||||||
|
value = cache[name];
|
||||||
|
} else {
|
||||||
|
var context = this, names, index, lookupHit = false;
|
||||||
|
|
||||||
|
while (context) {
|
||||||
|
if (name.indexOf('.') > 0) {
|
||||||
|
value = context.view;
|
||||||
|
names = name.split('.');
|
||||||
|
index = 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Using the dot notion path in `name`, we descend through the
|
||||||
|
* nested objects.
|
||||||
|
*
|
||||||
|
* To be certain that the lookup has been successful, we have to
|
||||||
|
* check if the last object in the path actually has the property
|
||||||
|
* we are looking for. We store the result in `lookupHit`.
|
||||||
|
*
|
||||||
|
* This is specially necessary for when the value has been set to
|
||||||
|
* `undefined` and we want to avoid looking up parent contexts.
|
||||||
|
**/
|
||||||
|
while (value != null && index < names.length) {
|
||||||
|
if (index === names.length - 1)
|
||||||
|
lookupHit = hasProperty(value, names[index]);
|
||||||
|
|
||||||
|
value = value[names[index++]];
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
value = context.view[name];
|
||||||
|
lookupHit = hasProperty(context.view, name);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lookupHit)
|
||||||
|
break;
|
||||||
|
|
||||||
|
context = context.parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
cache[name] = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isFunction(value))
|
||||||
|
value = value.call(this.view);
|
||||||
|
|
||||||
|
return value;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A Writer knows how to take a stream of tokens and render them to a
|
||||||
|
* string, given a context. It also maintains a cache of templates to
|
||||||
|
* avoid the need to parse the same template twice.
|
||||||
|
*/
|
||||||
|
function Writer () {
|
||||||
|
this.cache = {};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clears all cached templates in this writer.
|
||||||
|
*/
|
||||||
|
Writer.prototype.clearCache = function clearCache () {
|
||||||
|
this.cache = {};
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses and caches the given `template` and returns the array of tokens
|
||||||
|
* that is generated from the parse.
|
||||||
|
*/
|
||||||
|
Writer.prototype.parse = function parse (template, tags) {
|
||||||
|
var cache = this.cache;
|
||||||
|
var tokens = cache[template];
|
||||||
|
|
||||||
|
if (tokens == null)
|
||||||
|
tokens = cache[template] = parseTemplate(template, tags);
|
||||||
|
|
||||||
|
return tokens;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* High-level method that is used to render the given `template` with
|
||||||
|
* the given `view`.
|
||||||
|
*
|
||||||
|
* The optional `partials` argument may be an object that contains the
|
||||||
|
* names and templates of partials that are used in the template. It may
|
||||||
|
* also be a function that is used to load partial templates on the fly
|
||||||
|
* that takes a single argument: the name of the partial.
|
||||||
|
*/
|
||||||
|
Writer.prototype.render = function render (template, view, partials) {
|
||||||
|
var tokens = this.parse(template);
|
||||||
|
var context = (view instanceof Context) ? view : new Context(view);
|
||||||
|
return this.renderTokens(tokens, context, partials, template);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Low-level method that renders the given array of `tokens` using
|
||||||
|
* the given `context` and `partials`.
|
||||||
|
*
|
||||||
|
* Note: The `originalTemplate` is only ever used to extract the portion
|
||||||
|
* of the original template that was contained in a higher-order section.
|
||||||
|
* If the template doesn't use higher-order sections, this argument may
|
||||||
|
* be omitted.
|
||||||
|
*/
|
||||||
|
Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate) {
|
||||||
|
var buffer = '';
|
||||||
|
|
||||||
|
var token, symbol, value;
|
||||||
|
for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
|
||||||
|
value = undefined;
|
||||||
|
token = tokens[i];
|
||||||
|
symbol = token[0];
|
||||||
|
|
||||||
|
if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate);
|
||||||
|
else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate);
|
||||||
|
else if (symbol === '>') value = this.renderPartial(token, context, partials, originalTemplate);
|
||||||
|
else if (symbol === '&') value = this.unescapedValue(token, context);
|
||||||
|
else if (symbol === 'name') value = this.escapedValue(token, context);
|
||||||
|
else if (symbol === 'text') value = this.rawValue(token);
|
||||||
|
|
||||||
|
if (value !== undefined)
|
||||||
|
buffer += value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return buffer;
|
||||||
|
};
|
||||||
|
|
||||||
|
Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate) {
|
||||||
|
var self = this;
|
||||||
|
var buffer = '';
|
||||||
|
var value = context.lookup(token[1]);
|
||||||
|
|
||||||
|
// This function is used to render an arbitrary template
|
||||||
|
// in the current context by higher-order sections.
|
||||||
|
function subRender (template) {
|
||||||
|
return self.render(template, context, partials);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!value) return;
|
||||||
|
|
||||||
|
if (isArray(value)) {
|
||||||
|
for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
|
||||||
|
buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate);
|
||||||
|
}
|
||||||
|
} else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') {
|
||||||
|
buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
|
||||||
|
} else if (isFunction(value)) {
|
||||||
|
if (typeof originalTemplate !== 'string')
|
||||||
|
throw new Error('Cannot use higher-order sections without the original template');
|
||||||
|
|
||||||
|
// Extract the portion of the original template that the section contains.
|
||||||
|
value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);
|
||||||
|
|
||||||
|
if (value != null)
|
||||||
|
buffer += value;
|
||||||
|
} else {
|
||||||
|
buffer += this.renderTokens(token[4], context, partials, originalTemplate);
|
||||||
|
}
|
||||||
|
return buffer;
|
||||||
|
};
|
||||||
|
|
||||||
|
Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate) {
|
||||||
|
var value = context.lookup(token[1]);
|
||||||
|
|
||||||
|
// Use JavaScript's definition of falsy. Include empty arrays.
|
||||||
|
// See https://github.com/janl/mustache.js/issues/186
|
||||||
|
if (!value || (isArray(value) && value.length === 0))
|
||||||
|
return this.renderTokens(token[4], context, partials, originalTemplate);
|
||||||
|
};
|
||||||
|
|
||||||
|
Writer.prototype.renderPartial = function renderPartial (token, context, partials) {
|
||||||
|
if (!partials) return;
|
||||||
|
|
||||||
|
var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
|
||||||
|
if (value != null)
|
||||||
|
return this.renderTokens(this.parse(value), context, partials, value);
|
||||||
|
};
|
||||||
|
|
||||||
|
Writer.prototype.unescapedValue = function unescapedValue (token, context) {
|
||||||
|
var value = context.lookup(token[1]);
|
||||||
|
if (value != null)
|
||||||
|
return value;
|
||||||
|
};
|
||||||
|
|
||||||
|
Writer.prototype.escapedValue = function escapedValue (token, context) {
|
||||||
|
var value = context.lookup(token[1]);
|
||||||
|
if (value != null)
|
||||||
|
return mustache.escape(value);
|
||||||
|
};
|
||||||
|
|
||||||
|
Writer.prototype.rawValue = function rawValue (token) {
|
||||||
|
return token[1];
|
||||||
|
};
|
||||||
|
|
||||||
|
mustache.name = 'mustache.js';
|
||||||
|
mustache.version = '2.2.1';
|
||||||
|
mustache.tags = [ '{{', '}}' ];
|
||||||
|
|
||||||
|
// All high-level mustache.* functions use this writer.
|
||||||
|
var defaultWriter = new Writer();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clears all cached templates in the default writer.
|
||||||
|
*/
|
||||||
|
mustache.clearCache = function clearCache () {
|
||||||
|
return defaultWriter.clearCache();
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses and caches the given template in the default writer and returns the
|
||||||
|
* array of tokens it contains. Doing this ahead of time avoids the need to
|
||||||
|
* parse templates on the fly as they are rendered.
|
||||||
|
*/
|
||||||
|
mustache.parse = function parse (template, tags) {
|
||||||
|
return defaultWriter.parse(template, tags);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders the `template` with the given `view` and `partials` using the
|
||||||
|
* default writer.
|
||||||
|
*/
|
||||||
|
mustache.render = function render (template, view, partials) {
|
||||||
|
if (typeof template !== 'string') {
|
||||||
|
throw new TypeError('Invalid template! Template should be a "string" ' +
|
||||||
|
'but "' + typeStr(template) + '" was given as the first ' +
|
||||||
|
'argument for mustache#render(template, view, partials)');
|
||||||
|
}
|
||||||
|
|
||||||
|
return defaultWriter.render(template, view, partials);
|
||||||
|
};
|
||||||
|
|
||||||
|
// This is here for backwards compatibility with 0.4.x.,
|
||||||
|
/*eslint-disable */ // eslint wants camel cased function name
|
||||||
|
mustache.to_html = function to_html (template, view, partials, send) {
|
||||||
|
/*eslint-enable*/
|
||||||
|
|
||||||
|
var result = mustache.render(template, view, partials);
|
||||||
|
|
||||||
|
if (isFunction(send)) {
|
||||||
|
send(result);
|
||||||
|
} else {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Export the escaping function so that the user may override it.
|
||||||
|
// See https://github.com/janl/mustache.js/issues/244
|
||||||
|
mustache.escape = escapeHtml;
|
||||||
|
|
||||||
|
// Export these mainly for testing, but also for advanced usage.
|
||||||
|
mustache.Scanner = Scanner;
|
||||||
|
mustache.Context = Context;
|
||||||
|
mustache.Writer = Writer;
|
||||||
|
|
||||||
|
}));
|
1577
public/js/lib/zepto.js
Normal file
1577
public/js/lib/zepto.js
Normal file
File diff suppressed because it is too large
Load Diff
26
public/js/manga_collection.js
Normal file
26
public/js/manga_collection.js
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
(($, AnimeClient) => {
|
||||||
|
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
const search = (tempHtml, query) => {
|
||||||
|
$('.cssload-loader').removeAttr('hidden');
|
||||||
|
$.get(AnimeClient.url('/manga/search'), {'query':query,}, (searchResults, status) => {
|
||||||
|
$('.cssload-loader').attr('hidden', 'hidden');
|
||||||
|
|
||||||
|
Mustache.parse(tempHtml);
|
||||||
|
$('#series_list').html(Mustache.render(tempHtml, searchResults));
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
$.get('/public/templates/manga-ajax-search-results.html', tempHtml => {
|
||||||
|
$('#search').on('keyup', AnimeClient.throttle(250, function(e) {
|
||||||
|
let query = encodeURIComponent($(this).val());
|
||||||
|
if (query === '') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
search(tempHtml, query);
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
})(Zepto, AnimeClient);
|
@ -1,20 +1,20 @@
|
|||||||
/**
|
/**
|
||||||
* Javascript for editing manga, if logged in
|
* Javascript for editing manga, if logged in
|
||||||
*/
|
*/
|
||||||
(($, AnimeClient, w) => {
|
(($, AnimeClient) => {
|
||||||
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
$('body.manga.list').on('click', '.edit_buttons button', function(e) {
|
$('.manga.list').on('click', '.edit_buttons button', function(e) {
|
||||||
let this_sel = $(this);
|
let this_sel = $(this);
|
||||||
let parent_sel = $(this).closest("article");
|
let parent_sel = $(this).closest("article");
|
||||||
let manga_id = parent_sel.attr("id").replace("manga-", "");
|
let manga_id = parent_sel.attr("id").replace("manga-", "");
|
||||||
let type = this_sel.is(".plus_one_chapter") ? 'chapter' : 'volume';
|
let type = this_sel.is(".plus_one_chapter") ? 'chapter' : 'volume';
|
||||||
let completed = parseInt(parent_sel.find(`.${type}s_read`).text(), 10);
|
let completed = parseInt(parent_sel.find(`.${type}s_read`).text(), 10);
|
||||||
let total = parseInt(parent_sel.find(`.${type}_count`).text(), 10);
|
let total = parseInt(parent_sel.find(`.${type}_count`).text(), 10);
|
||||||
|
let manga_name = parent_sel.find('.name').html();
|
||||||
|
|
||||||
if (isNaN(completed))
|
if (isNaN(completed)) {
|
||||||
{
|
|
||||||
completed = 0;
|
completed = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -28,18 +28,20 @@
|
|||||||
$.ajax({
|
$.ajax({
|
||||||
data: data,
|
data: data,
|
||||||
dataType: 'json',
|
dataType: 'json',
|
||||||
method: 'POST',
|
type: 'POST',
|
||||||
mimeType: 'application/json',
|
mimeType: 'application/json',
|
||||||
url: AnimeClient.url('/manga/update'),
|
url: AnimeClient.url('/manga/update'),
|
||||||
}).done((res) => {
|
success: (res, status) => {
|
||||||
parent_sel.find(`.${type}s_read`).text(completed);
|
parent_sel.find(`.${type}s_read`).text(completed);
|
||||||
AnimeClient.showMessage('success', `Sucessfully updated ${res.body.manga[0].romaji_title}`);
|
AnimeClient.showMessage('success', `Sucessfully updated ${manga_name}`);
|
||||||
|
AnimeClient.scrollToTop();
|
||||||
// scroll to top
|
},
|
||||||
w.scroll(0,0);
|
error: (xhr, errorType, error) => {
|
||||||
}).fail(() => {
|
console.error(error);
|
||||||
AnimeClient.showMessage('error', `Failed to updated ${res.body.manga[0].romaji_title}`);
|
AnimeClient.showMessage('error', `Failed to updated ${manga_name}`);
|
||||||
|
AnimeClient.scrollToTop();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
})(jQuery, AnimeClient, window);
|
})(Zepto, AnimeClient);
|
10
public/templates/manga-ajax-search-results.html
Normal file
10
public/templates/manga-ajax-search-results.html
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
{{#search}}
|
||||||
|
<article class="media search">
|
||||||
|
<div class="name" style="background-image:url({{image}})">
|
||||||
|
<input type="radio" class="big-check" id="{{link}}" name="id" value="{{link}}" />
|
||||||
|
<label for="{{link}}">
|
||||||
|
<span>{{title}}</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
{{/search}}
|
@ -382,11 +382,13 @@ class Controller {
|
|||||||
* Output a JSON Response
|
* Output a JSON Response
|
||||||
*
|
*
|
||||||
* @param mixed $data
|
* @param mixed $data
|
||||||
|
* @param int $code - the http status code
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
protected function outputJSON($data = [])
|
protected function outputJSON($data = [], $code = 200)
|
||||||
{
|
{
|
||||||
$view = new JsonView($this->container);
|
$view = new JsonView($this->container);
|
||||||
|
$view->setStatusCode($code);
|
||||||
$view->setOutput($data);
|
$view->setOutput($data);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -249,11 +249,8 @@ class Anime extends BaseController {
|
|||||||
*/
|
*/
|
||||||
public function update()
|
public function update()
|
||||||
{
|
{
|
||||||
$this->outputJSON(
|
$response = $this->model->update($this->request->post->get());
|
||||||
$this->model->update(
|
$this->outputJSON($response['body'], $response['statusCode']);
|
||||||
$this->request->post->get()
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -91,6 +91,61 @@ class Manga extends Controller {
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Form to add an manga
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function add_form()
|
||||||
|
{
|
||||||
|
$raw_status_list = MangaReadingStatus::getConstList();
|
||||||
|
|
||||||
|
$statuses = [];
|
||||||
|
|
||||||
|
foreach ($raw_status_list as $status_item)
|
||||||
|
{
|
||||||
|
$statuses[$status_item] = (string)$this->string($status_item)
|
||||||
|
->underscored()
|
||||||
|
->humanize()
|
||||||
|
->titleize();
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->set_session_redirect();
|
||||||
|
$this->outputHTML('manga/add', [
|
||||||
|
'title' => $this->config->get('whose_list') .
|
||||||
|
"'s Manga List · Add",
|
||||||
|
'action_url' => $this->urlGenerator->url('manga/add'),
|
||||||
|
'status_list' => $statuses
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add an manga to the list
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function add()
|
||||||
|
{
|
||||||
|
$data = $this->request->post->get();
|
||||||
|
if ( ! array_key_exists('id', $data))
|
||||||
|
{
|
||||||
|
$this->redirect("manga/add", 303);
|
||||||
|
}
|
||||||
|
|
||||||
|
$result = $this->model->add($data);
|
||||||
|
|
||||||
|
if ($result['statusCode'] >= 200 && $result['statusCode'] < 300)
|
||||||
|
{
|
||||||
|
$this->set_flash_message('Added new manga to list', 'success');
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
$this->set_flash_message('Failed to add new manga to list' . $result['body'] , 'error');
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->session_redirect();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Show the manga edit form
|
* Show the manga edit form
|
||||||
*
|
*
|
||||||
@ -113,6 +168,18 @@ class Manga extends Controller {
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Search for a manga to add to the list
|
||||||
|
*
|
||||||
|
* @param string $query
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function search()
|
||||||
|
{
|
||||||
|
$query = $this->request->query->get('query');
|
||||||
|
$this->outputJSON($this->model->search($query));
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update an anime item via a form submission
|
* Update an anime item via a form submission
|
||||||
*
|
*
|
||||||
@ -141,7 +208,7 @@ class Manga extends Controller {
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$this->set_flash_message('Failed to update anime.', 'error');
|
$this->set_flash_message('Failed to update manga.', 'error');
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->session_redirect();
|
$this->session_redirect();
|
||||||
@ -154,7 +221,8 @@ class Manga extends Controller {
|
|||||||
*/
|
*/
|
||||||
public function update()
|
public function update()
|
||||||
{
|
{
|
||||||
$this->outputJSON($this->model->update($this->request->post->get()));
|
$result = $this->model->update($this->request->post->get());
|
||||||
|
$this->outputJSON($result['body'], $result['statusCode']);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// End of MangaController.php
|
// End of MangaController.php
|
@ -50,6 +50,49 @@ class Manga extends API {
|
|||||||
*/
|
*/
|
||||||
protected $base_url = "https://hummingbird.me/";
|
protected $base_url = "https://hummingbird.me/";
|
||||||
|
|
||||||
|
protected function _auth_json_call($type, $url, $json)
|
||||||
|
{
|
||||||
|
$token = $this->container->get('auth')
|
||||||
|
->get_auth_token();
|
||||||
|
|
||||||
|
// Set the token cookie, with the authentication token
|
||||||
|
// from the auth class.
|
||||||
|
$cookieJar = $this->cookieJar;
|
||||||
|
$cookie_data = new SetCookie([
|
||||||
|
'Name' => 'token',
|
||||||
|
'Value' => $token,
|
||||||
|
'Domain' => 'hummingbird.me'
|
||||||
|
]);
|
||||||
|
$cookieJar->setCookie($cookie_data);
|
||||||
|
|
||||||
|
$result = $this->client->request(strtoupper($type), $url, [
|
||||||
|
'cookies' => $cookieJar,
|
||||||
|
'json' => $json
|
||||||
|
]);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'statusCode' => $result->getStatusCode(),
|
||||||
|
'body' => $result->getBody()
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add a manga to the list
|
||||||
|
*
|
||||||
|
* @param array $data
|
||||||
|
*/
|
||||||
|
public function add($data)
|
||||||
|
{
|
||||||
|
$object = [
|
||||||
|
'manga_library_entry' => [
|
||||||
|
'status' => $data['status'],
|
||||||
|
'manga_id' => $data['id']
|
||||||
|
]
|
||||||
|
];
|
||||||
|
|
||||||
|
return $this->_auth_json_call('post', 'manga_library_entries', $object);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update the selected manga
|
* Update the selected manga
|
||||||
*
|
*
|
||||||
@ -60,6 +103,23 @@ class Manga extends API {
|
|||||||
{
|
{
|
||||||
$id = $data['id'];
|
$id = $data['id'];
|
||||||
|
|
||||||
|
return $this->_auth_json_call(
|
||||||
|
'put',
|
||||||
|
"manga_library_entries/{$id}",
|
||||||
|
['manga_library_entry' => $data]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete a manga entry
|
||||||
|
*
|
||||||
|
* @param array $data
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public function delete($data)
|
||||||
|
{
|
||||||
|
$id = $data['id'];
|
||||||
|
|
||||||
$token = $this->container->get('auth')
|
$token = $this->container->get('auth')
|
||||||
->get_auth_token();
|
->get_auth_token();
|
||||||
|
|
||||||
@ -73,17 +133,47 @@ class Manga extends API {
|
|||||||
]);
|
]);
|
||||||
$cookieJar->setCookie($cookie_data);
|
$cookieJar->setCookie($cookie_data);
|
||||||
|
|
||||||
$result = $this->put("manga_library_entries/{$id}", [
|
$result = $this->delete("manga_library_entries/{$id}", [
|
||||||
'cookies' => $cookieJar,
|
'cookies' => $cookieJar,
|
||||||
'json' => ['manga_library_entry' => $data]
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'statusCode' => $result->getStatusCode(),
|
'statusCode' => $result->getStatusCode(),
|
||||||
'body' => Json::decode($result->getBody(), TRUE)
|
'body' => $result->getBody()
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Search for manga by name
|
||||||
|
*
|
||||||
|
* @param string $name
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public function search($name)
|
||||||
|
{
|
||||||
|
$logger = $this->container->getLogger('default');
|
||||||
|
|
||||||
|
$config = [
|
||||||
|
'query' => [
|
||||||
|
'scope' => 'manga',
|
||||||
|
'depth' => 'full',
|
||||||
|
'query' => $name
|
||||||
|
]
|
||||||
|
];
|
||||||
|
|
||||||
|
$response = $this->get('search.json', $config);
|
||||||
|
|
||||||
|
if ($response->getStatusCode() != 200)
|
||||||
|
{
|
||||||
|
$logger->warning("Non 200 response for search api call");
|
||||||
|
$logger->warning($response->getBody());
|
||||||
|
|
||||||
|
throw new RuntimeException($response->getEffectiveUrl());
|
||||||
|
}
|
||||||
|
|
||||||
|
return Json::decode($response->getBody(), TRUE);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the full set of anime lists
|
* Get the full set of anime lists
|
||||||
*
|
*
|
||||||
|
Loading…
Reference in New Issue
Block a user