first commit

This commit is contained in:
Le Libre Au Quotidien 2020-10-10 12:12:44 +02:00
commit 13481238cb
172 changed files with 86811 additions and 0 deletions

15
.editorconfig Normal file
View File

@ -0,0 +1,15 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2

46
.env.example Normal file
View File

@ -0,0 +1,46 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

5
.gitattributes vendored Normal file
View File

@ -0,0 +1,5 @@
* text=auto
*.css linguist-vendored
*.scss linguist-vendored
*.js linguist-vendored
CHANGELOG.md export-ignore

12
.gitignore vendored Normal file
View File

@ -0,0 +1,12 @@
/node_modules
/public/hot
/public/storage
/storage/*.key
/vendor
.env
.env.backup
.phpunit.result.cache
Homestead.json
Homestead.yaml
npm-debug.log
yarn-error.log

13
.styleci.yml Normal file
View File

@ -0,0 +1,13 @@
php:
preset: laravel
disabled:
- no_unused_imports
finder:
not-name:
- index.php
- server.php
js:
finder:
not-name:
- webpack.mix.js
css: true

61
README.md Normal file
View File

@ -0,0 +1,61 @@
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400"></a></p>
<p align="center">
<a href="https://travis-ci.org/laravel/framework"><img src="https://travis-ci.org/laravel/framework.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/d/total.svg" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/v/stable.svg" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/license.svg" alt="License"></a>
</p>
## About Laravel
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
- [Simple, fast routing engine](https://laravel.com/docs/routing).
- [Powerful dependency injection container](https://laravel.com/docs/container).
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
- [Robust background job processing](https://laravel.com/docs/queues).
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
Laravel is accessible, powerful, and provides tools required for large, robust applications.
## Learning Laravel
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework.
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains over 1500 video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
## Laravel Sponsors
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the Laravel [Patreon page](https://patreon.com/taylorotwell).
### Premium Partners
- **[Vehikl](https://vehikl.com/)**
- **[Tighten Co.](https://tighten.co)**
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
- **[64 Robots](https://64robots.com)**
- **[Cubet Techno Labs](https://cubettech.com)**
- **[Cyber-Duck](https://cyber-duck.co.uk)**
- **[Many](https://www.many.co.uk)**
- **[Webdock, Fast VPS Hosting](https://www.webdock.io/en)**
- **[DevSquad](https://devsquad.com)**
- **[OP.GG](https://op.gg)**
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Code of Conduct
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

41
app/Console/Kernel.php Normal file
View File

@ -0,0 +1,41 @@
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
//
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')->hourly();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}

View File

@ -0,0 +1,37 @@
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
//
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace App\Http\Controllers;
use App\Models\Content;
use App\Models\Category;
use Illuminate\Http\Request;
class ContentController extends Controller
{
public function index($path){
$category = Category::where('path', $path)->firstOrFail();
//dd($category);
return view('choicebox')->with('category', $category);
}
public function show($path){
$content = Content::where('path', $path)->first();
return view('softbox')->with('content', $content);
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

66
app/Http/Kernel.php Normal file
View File

@ -0,0 +1,66 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}

View File

@ -0,0 +1,21 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array
*/
protected $except = [
//
];
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
class PreventRequestsDuringMaintenance extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array
*/
protected $except = [
//
];
}

View File

@ -0,0 +1,32 @@
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null ...$guards
* @return mixed
*/
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
}
return $next($request);
}
}

View File

@ -0,0 +1,18 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array
*/
protected $except = [
'password',
'password_confirmation',
];
}

View File

@ -0,0 +1,20 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustHosts as Middleware;
class TrustHosts extends Middleware
{
/**
* Get the host patterns that should be trusted.
*
* @return array
*/
public function hosts()
{
return [
$this->allSubdomainsOfApplicationUrl(),
];
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace App\Http\Middleware;
use Fideloper\Proxy\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array|string|null
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers = Request::HEADER_X_FORWARDED_ALL;
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
];
}

21
app/Models/Category.php Normal file
View File

@ -0,0 +1,21 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
//protected $primaryKey = 'path';
use HasFactory;
public function contents(){
return $this->belongsToMany('App\Models\Content');
}
public function subcategories(){
return $this->hasMany('App\Models\Category');
}
}

17
app/Models/Content.php Normal file
View File

@ -0,0 +1,17 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Content extends Model
{
//protected $primaryKey = 'path';
use HasFactory;
public function categories(){
return $this->belongsToMany('App\Models\Category');
}
}

43
app/Models/User.php Normal file
View File

@ -0,0 +1,43 @@
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}

View File

@ -0,0 +1,32 @@
<?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
//
}
}

View File

@ -0,0 +1,63 @@
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* This is used by Laravel authentication to redirect users after login.
*
* @var string
*/
public const HOME = '/home';
/**
* The controller namespace for the application.
*
* When present, controller route declarations will automatically be prefixed with this namespace.
*
* @var string|null
*/
// protected $namespace = 'App\\Http\\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
});
}
/**
* Configure the rate limiters for the application.
*
* @return void
*/
protected function configureRateLimiting()
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60);
});
}
}

53
artisan Normal file
View File

@ -0,0 +1,53 @@
#!/usr/bin/env php
<?php
define('LARAVEL_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/
require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Artisan Application
|--------------------------------------------------------------------------
|
| When we run the console application, the current CLI command will be
| executed in this console and the response sent back to a terminal
| or another output device for the developers. Here goes nothing!
|
*/
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArgvInput,
new Symfony\Component\Console\Output\ConsoleOutput
);
/*
|--------------------------------------------------------------------------
| Shutdown The Application
|--------------------------------------------------------------------------
|
| Once Artisan has finished running, we will fire off the shutdown events
| so that any final work may be done by the application before we shut
| down the process. This is the last thing to happen to the request.
|
*/
$kernel->terminate($input, $status);
exit($status);

55
bootstrap/app.php Normal file
View File

@ -0,0 +1,55 @@
<?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
return $app;

2
bootstrap/cache/.gitignore vendored Executable file
View File

@ -0,0 +1,2 @@
*
!.gitignore

61
composer.json Normal file
View File

@ -0,0 +1,61 @@
{
"name": "laravel/laravel",
"type": "project",
"description": "The Laravel Framework.",
"keywords": [
"framework",
"laravel"
],
"license": "MIT",
"require": {
"php": "^7.3",
"fideloper/proxy": "^4.2",
"fruitcake/laravel-cors": "^2.0",
"guzzlehttp/guzzle": "^7.0.1",
"laravel/framework": "^8.0",
"laravel/tinker": "^2.0"
},
"require-dev": {
"facade/ignition": "^2.3.6",
"fzaninotto/faker": "^1.9.1",
"mockery/mockery": "^1.3.1",
"nunomaduro/collision": "^5.0",
"phpunit/phpunit": "^9.3"
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"minimum-stability": "dev",
"prefer-stable": true,
"scripts": {
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi"
]
}
}

7139
composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

232
config/app.php Normal file
View File

@ -0,0 +1,232 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
'asset_url' => env('ASSET_URL', null),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'en',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Faker Locale
|--------------------------------------------------------------------------
|
| This locale will be used by the Faker PHP library when generating fake
| data for your database seeds. For example, this will be used to get
| localized telephone numbers, street address information and more.
|
*/
'faker_locale' => 'en_US',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Notifications\NotificationServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Arr' => Illuminate\Support\Arr::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
'Bus' => Illuminate\Support\Facades\Bus::class,
'Cache' => Illuminate\Support\Facades\Cache::class,
'Config' => Illuminate\Support\Facades\Config::class,
'Cookie' => Illuminate\Support\Facades\Cookie::class,
'Crypt' => Illuminate\Support\Facades\Crypt::class,
'DB' => Illuminate\Support\Facades\DB::class,
'Eloquent' => Illuminate\Database\Eloquent\Model::class,
'Event' => Illuminate\Support\Facades\Event::class,
'File' => Illuminate\Support\Facades\File::class,
'Gate' => Illuminate\Support\Facades\Gate::class,
'Hash' => Illuminate\Support\Facades\Hash::class,
'Http' => Illuminate\Support\Facades\Http::class,
'Lang' => Illuminate\Support\Facades\Lang::class,
'Log' => Illuminate\Support\Facades\Log::class,
'Mail' => Illuminate\Support\Facades\Mail::class,
'Notification' => Illuminate\Support\Facades\Notification::class,
'Password' => Illuminate\Support\Facades\Password::class,
'Queue' => Illuminate\Support\Facades\Queue::class,
'Redirect' => Illuminate\Support\Facades\Redirect::class,
'Redis' => Illuminate\Support\Facades\Redis::class,
'Request' => Illuminate\Support\Facades\Request::class,
'Response' => Illuminate\Support\Facades\Response::class,
'Route' => Illuminate\Support\Facades\Route::class,
'Schema' => Illuminate\Support\Facades\Schema::class,
'Session' => Illuminate\Support\Facades\Session::class,
'Storage' => Illuminate\Support\Facades\Storage::class,
'Str' => Illuminate\Support\Str::class,
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
],
];

117
config/auth.php Normal file
View File

@ -0,0 +1,117 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];

59
config/broadcasting.php Normal file
View File

@ -0,0 +1,59 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Broadcaster
|--------------------------------------------------------------------------
|
| This option controls the default broadcaster that will be used by the
| framework when an event needs to be broadcast. You may set this to
| any of the connections defined in the "connections" array below.
|
| Supported: "pusher", "redis", "log", "null"
|
*/
'default' => env('BROADCAST_DRIVER', 'null'),
/*
|--------------------------------------------------------------------------
| Broadcast Connections
|--------------------------------------------------------------------------
|
| Here you may define all of the broadcast connections that will be used
| to broadcast events to other systems or over websockets. Samples of
| each available type of connection are provided inside this array.
|
*/
'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'useTLS' => true,
],
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
'log' => [
'driver' => 'log',
],
'null' => [
'driver' => 'null',
],
],
];

104
config/cache.php Normal file
View File

@ -0,0 +1,104 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache connection that gets used while
| using this caching library. This connection is used when another is
| not explicitly specified when executing a given caching function.
|
| Supported: "apc", "array", "database", "file",
| "memcached", "redis", "dynamodb"
|
*/
'default' => env('CACHE_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
*/
'stores' => [
'apc' => [
'driver' => 'apc',
],
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'table' => 'cache',
'connection' => null,
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => 'cache',
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing a RAM based store such as APC or Memcached, there might
| be other applications utilizing the same cache. So, we'll specify a
| value to get prefixed to all our keys so we can avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache'),
];

34
config/cors.php Normal file
View File

@ -0,0 +1,34 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];

147
config/database.php Normal file
View File

@ -0,0 +1,147 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => env('DB_CONNECTION', 'mysql'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DATABASE_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
'schema' => 'public',
'sslmode' => 'prefer',
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
],
],
];

85
config/filesystems.php Normal file
View File

@ -0,0 +1,85 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application. Just store away!
|
*/
'default' => env('FILESYSTEM_DRIVER', 'local'),
/*
|--------------------------------------------------------------------------
| Default Cloud Filesystem Disk
|--------------------------------------------------------------------------
|
| Many applications store files both locally and in the cloud. For this
| reason, you may specify a default "cloud" driver here. This driver
| will be bound as the Cloud disk implementation in the container.
|
*/
'cloud' => env('FILESYSTEM_CLOUD', 's3'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Here you may configure as many filesystem "disks" as you wish, and you
| may even configure multiple disks of the same driver. Defaults have
| been setup for each driver as an example of the required options.
|
| Supported Drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];

52
config/hashing.php Normal file
View File

@ -0,0 +1,52 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Hash Driver
|--------------------------------------------------------------------------
|
| This option controls the default hash driver that will be used to hash
| passwords for your application. By default, the bcrypt algorithm is
| used; however, you remain free to modify this option if you wish.
|
| Supported: "bcrypt", "argon", "argon2id"
|
*/
'driver' => 'bcrypt',
/*
|--------------------------------------------------------------------------
| Bcrypt Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Bcrypt algorithm. This will allow you
| to control the amount of time it takes to hash the given password.
|
*/
'bcrypt' => [
'rounds' => env('BCRYPT_ROUNDS', 10),
],
/*
|--------------------------------------------------------------------------
| Argon Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Argon algorithm. These will allow you
| to control the amount of time it takes to hash the given password.
|
*/
'argon' => [
'memory' => 1024,
'threads' => 2,
'time' => 2,
],
];

104
config/logging.php Normal file
View File

@ -0,0 +1,104 @@
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that gets used when writing
| messages to the logs. The name specified in this option should match
| one of the channels defined in the "channels" configuration array.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog",
| "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single'],
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
'days' => 14,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => 'Laravel Log',
'emoji' => ':boom:',
'level' => 'critical',
],
'papertrail' => [
'driver' => 'monolog',
'level' => 'debug',
'handler' => SyslogUdpHandler::class,
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
],
],
'stderr' => [
'driver' => 'monolog',
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'stream' => 'php://stderr',
],
],
'syslog' => [
'driver' => 'syslog',
'level' => 'debug',
],
'errorlog' => [
'driver' => 'errorlog',
'level' => 'debug',
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];

110
config/mail.php Normal file
View File

@ -0,0 +1,110 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send any email
| messages sent by your application. Alternative mailers may be setup
| and used as needed; however, this mailer will be used by default.
|
*/
'default' => env('MAIL_MAILER', 'smtp'),
/*
|--------------------------------------------------------------------------
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers to be used while
| sending an e-mail. You will specify which one you are using for your
| mailers below. You are free to add additional mailers as required.
|
| Supported: "smtp", "sendmail", "mailgun", "ses",
| "postmark", "log", "array"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'auth_mode' => null,
],
'ses' => [
'transport' => 'ses',
],
'mailgun' => [
'transport' => 'mailgun',
],
'postmark' => [
'transport' => 'postmark',
],
'sendmail' => [
'transport' => 'sendmail',
'path' => '/usr/sbin/sendmail -bs',
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
/*
|--------------------------------------------------------------------------
| Markdown Mail Settings
|--------------------------------------------------------------------------
|
| If you are using Markdown based email rendering, you may configure your
| theme and component paths here, allowing you to customize the design
| of the emails. Or, you may simply stick with the Laravel defaults!
|
*/
'markdown' => [
'theme' => 'default',
'paths' => [
resource_path('views/vendor/mail'),
],
],
];

89
config/queue.php Normal file
View File

@ -0,0 +1,89 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue API supports an assortment of back-ends via a single
| API, giving you convenient access to each back-end using the same
| syntax for every one. Here you may define a default connection.
|
*/
'default' => env('QUEUE_CONNECTION', 'sync'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection information for each server that
| is used by your application. A default configuration has been added
| for each back-end shipped with Laravel. You are free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => 'localhost',
'queue' => 'default',
'retry_after' => 90,
'block_for' => 0,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'your-queue-name'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => 90,
'block_for' => null,
],
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control which database and table are used to store the jobs that
| have failed. You may change them to any database / table you wish.
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'mysql'),
'table' => 'failed_jobs',
],
];

33
config/services.php Normal file
View File

@ -0,0 +1,33 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark, AWS and more. This file provides the de facto
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
],
'postmark' => [
'token' => env('POSTMARK_TOKEN'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
];

201
config/session.php Normal file
View File

@ -0,0 +1,201 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
| "memcached", "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false,
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it is stored. All encryption will be run
| automatically by Laravel and you can use the Session like normal.
|
*/
'encrypt' => false,
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION', null),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/
'table' => 'sessions',
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| While using one of the framework's cache driven session backends you may
| list a cache store that should be used for these sessions. This value
| must match with one of the application's configured cache "stores".
|
| Affects: "apc", "dynamodb", "memcached", "redis"
|
*/
'store' => env('SESSION_STORE', null),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/
'path' => '/',
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/
'domain' => env('SESSION_DOMAIN', null),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you if it can not be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. You are free to modify this option if needed.
|
*/
'http_only' => true,
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" since this is a secure default value.
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => 'lax',
];

36
config/view.php Normal file
View File

@ -0,0 +1,36 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| View Storage Paths
|--------------------------------------------------------------------------
|
| Most templating systems load templates from disk. Here you may specify
| an array of paths that should be checked for your views. Of course
| the usual Laravel view path has already been registered for you.
|
*/
'paths' => [
resource_path('views'),
],
/*
|--------------------------------------------------------------------------
| Compiled View Path
|--------------------------------------------------------------------------
|
| This option determines where all the compiled Blade templates will be
| stored for your application. Typically, this is within the storage
| directory. However, as usual, you are free to change this value.
|
*/
'compiled' => env(
'VIEW_COMPILED_PATH',
realpath(storage_path('framework/views'))
),
];

2
database/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*.sqlite
*.sqlite-journal

View File

@ -0,0 +1,33 @@
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class UserFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = User::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
}
}

View File

@ -0,0 +1,36 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}

View File

@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePasswordResetsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('password_resets', function (Blueprint $table) {
$table->string('email')->index();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('password_resets');
}
}

View File

@ -0,0 +1,36 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFailedJobsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->string('uuid')->unique();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('failed_jobs');
}
}

View File

@ -0,0 +1,36 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateContentsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('contents', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description');
$table->text('href');
$table->text('img');
$table->text('path');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('contents');
}
}

View File

@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->text('path');
$table->text('name');
$table->foreignId('category_id') ->nullable()->constrained();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
}

View File

@ -0,0 +1,41 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCategoryContentTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('category_content', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('category_id');
$table->foreign('category_id')
->references('id')
->on('categories')
->onDelete('cascade');
$table->unsignedBigInteger('content_id');
$table->foreign('content_id')
->references('id')
->on('contents')
->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('category_content');
}
}

View File

@ -0,0 +1,18 @@
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
// \App\Models\User::factory(10)->create();
}
}

10099
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

22
package.json Normal file
View File

@ -0,0 +1,22 @@
{
"private": true,
"scripts": {
"dev": "npm run development",
"development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"watch": "npm run development -- --watch",
"watch-poll": "npm run watch -- --watch-poll",
"hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --disable-host-check --config=node_modules/laravel-mix/setup/webpack.config.js",
"prod": "npm run production",
"production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
},
"devDependencies": {
"axios": "^0.19",
"cross-env": "^7.0",
"laravel-mix": "^5.0.1",
"lodash": "^4.17.19",
"resolve-url-loader": "^3.1.0",
"sass": "^1.26.12",
"sass-loader": "^8.0.2",
"vue-template-compiler": "^2.6.12"
}
}

31
phpunit.xml Normal file
View File

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
>
<testsuites>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
</testsuites>
<coverage processUncoveredFiles="true">
<include>
<directory suffix=".php">./app</directory>
</include>
</coverage>
<php>
<server name="APP_ENV" value="testing"/>
<server name="BCRYPT_ROUNDS" value="4"/>
<server name="CACHE_DRIVER" value="array"/>
<!-- <server name="DB_CONNECTION" value="sqlite"/> -->
<!-- <server name="DB_DATABASE" value=":memory:"/> -->
<server name="MAIL_MAILER" value="array"/>
<server name="QUEUE_CONNECTION" value="sync"/>
<server name="SESSION_DRIVER" value="array"/>
<server name="TELESCOPE_ENABLED" value="false"/>
</php>
</phpunit>

21
public/.htaccess Normal file
View File

@ -0,0 +1,21 @@
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

9322
public/css/app.css vendored Normal file

File diff suppressed because it is too large Load Diff

0
public/favicon.ico Normal file
View File

463
public/images/infojune.svg Executable file
View File

@ -0,0 +1,463 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
inkscape:version="1.0 (4035a4fb49, 2020-05-01)"
inkscape:export-ydpi="21.59"
inkscape:output_extension="org.inkscape.output.svg.inkscape"
version="1.0"
inkscape:export-xdpi="21.59"
sodipodi:version="0.32"
viewBox="0 0 667.81 667.46"
inkscape:export-filename="/srv/http/infojune/public/img/icons/mstile-150x150.png"
sodipodi:docname="juneland.svg"
id="svg3136">
<defs
id="defs12">
<linearGradient
id="gradient-3"
gradientUnits="userSpaceOnUse"
x1="250"
y1="0"
x2="250"
y2="500"
spreadMethod="pad">
<stop
offset="0"
style="stop-color: rgb(247, 191, 44);"
id="stop822" />
<stop
offset="1"
style="stop-color: rgb(205, 94, 41);"
id="stop824" />
</linearGradient>
<linearGradient
id="gradient-1"
gradientUnits="userSpaceOnUse"
x1="250"
y1="20"
x2="250"
y2="480"
gradientTransform="matrix(1.0031068618357177, 0, 0, 1.0031068774714225, -0.7766979417722695, -1.4913391080554845)">
<stop
style="stop-color: rgb(255, 253, 90);"
offset="0"
id="stop827" />
<stop
style="stop-color: rgb(227, 140, 43);"
offset="1"
id="stop829" />
</linearGradient>
<linearGradient
id="gradient-2"
gradientUnits="userSpaceOnUse"
x1="250"
y1="20"
x2="250"
y2="480">
<stop
style="stop-color: rgb(255, 253, 90);"
offset="0"
id="stop832" />
<stop
style="stop-color: rgb(227, 140, 43);"
offset="1"
id="stop834" />
</linearGradient>
<linearGradient
id="gradient-4"
gradientUnits="userSpaceOnUse"
x1="253.44439697265625"
y1="238.4842529296875"
x2="253.44439697265625"
y2="480">
<stop
style="stop-color: rgb(247, 192, 40);"
offset="0"
id="stop837" />
<stop
style="stop-color: rgb(227, 140, 43);"
offset="1"
id="stop839" />
</linearGradient>
<linearGradient
id="gradient-5"
gradientUnits="userSpaceOnUse"
x1="250"
y1="80"
x2="250"
y2="420">
<stop
style="stop-color: rgb(255, 255, 255);"
offset="0"
id="stop842" />
<stop
style="stop-color: rgb(204, 204, 204);"
offset="1"
id="stop844" />
</linearGradient>
<radialGradient
id="gradient-6"
gradientUnits="userSpaceOnUse"
cx="255.1620635986328"
cy="260.2457580566406"
r="170"
gradientTransform="matrix(1.1626436932369086, 0, 0, 1.162643413775678, -41.65732727667786, -42.562495305302434)">
<stop
style="stop-color: rgb(248, 237, 51);"
offset="0"
id="stop847" />
<stop
offset="0.6244"
style="stop-color: rgb(248, 237, 51);"
id="stop849" />
<stop
offset="0.7638"
style="stop-color: rgb(239, 213, 43);"
id="stop851" />
<stop
offset="0.8931"
style="stop-color: rgb(218, 157, 24);"
id="stop853" />
<stop
style="stop-color: rgb(191, 80, 0);"
offset="1"
id="stop855" />
</radialGradient>
<linearGradient
id="gradient-7"
gradientUnits="userSpaceOnUse"
x1="-277.8105010986328"
y1="561.8806762695312"
x2="-277.8105010986328"
y2="796.8161010742188"
gradientTransform="matrix(0.6693761492701567, -0.07372995093502983, 0.07372975608843645, 0.6693762466934533, 391.9234250134925, 247.7612281045386)">
<stop
style="stop-color: rgb(255, 190, 0);"
offset="0"
id="stop858" />
<stop
style="stop-color: rgb(214, 120, 32);"
offset="1"
id="stop860" />
</linearGradient>
<linearGradient
id="gradient-7-2"
gradientUnits="userSpaceOnUse"
x1="-277.8105010986328"
y1="561.8806762695312"
x2="-277.8105010986328"
y2="796.8161010742188"
gradientTransform="matrix(0.3598424288589108, 0.0014199120748252486, -0.0008651188746076439, 0.21927866751948855, -159.19165838772352, 375.4938512765719)">
<stop
style="stop-color: rgb(255, 190, 0);"
offset="0"
id="stop863" />
<stop
style="stop-color: rgb(214, 120, 32);"
offset="1"
id="stop865" />
</linearGradient>
<linearGradient
id="gradient-8"
gradientUnits="userSpaceOnUse"
x1="545"
y1="360"
x2="545"
y2="375">
<stop
style="stop-color: rgb(211, 205, 32);"
offset="0"
id="stop868" />
<stop
style="stop-color: rgb(122, 118, 18);"
offset="1"
id="stop870" />
</linearGradient>
<linearGradient
id="gradient-9"
gradientUnits="userSpaceOnUse"
x1="-277.8105010986328"
y1="561.8806762695312"
x2="-277.8105010986328"
y2="796.8161010742188">
<stop
style="stop-color: rgb(255, 236, 46);"
offset="0"
id="stop873" />
<stop
style="stop-color: rgb(254, 189, 1);"
offset="1"
id="stop875" />
</linearGradient>
<linearGradient
id="gradient-11"
gradientUnits="userSpaceOnUse"
x1="-277.8105010986328"
y1="561.8806762695312"
x2="-277.8105010986328"
y2="796.8161010742188"
gradientTransform="matrix(0.6034087242432288, 0, 0, 0.6034087242432288, -110.17721499783198, 316.01031406856083)">
<stop
style="stop-color: rgb(255, 190, 0);"
offset="0"
id="stop883" />
<stop
style="stop-color: rgb(214, 120, 32);"
offset="1"
id="stop885" />
</linearGradient>
<radialGradient
id="gradient-12"
gradientUnits="userSpaceOnUse"
cx="-314.4753112792969"
cy="611.8270263671875"
r="126.30323791503906"
gradientTransform="matrix(1.1160329276951277, 0, 0, 1.1160334249562183, 24.30159432705809, -88.79756113141326)">
<stop
style="stop-color: rgb(255, 237, 49);"
offset="0"
id="stop888" />
<stop
style="stop-color: rgb(255, 237, 49);"
stop-opacity="0"
offset="1"
id="stop890" />
</radialGradient>
<radialGradient
id="gradient-16"
gradientUnits="userSpaceOnUse"
cx="634"
cy="196"
r="93"
gradientTransform="matrix(3.5442367061491935, 3.2814600134408605e-7, -0.0000013125840053763442, 3.6047992501207577, -1109.6003798618112, -416.64352220104587)">
<stop
style="stop-color: rgb(255, 255, 255);"
offset="0"
id="stop908" />
<stop
style="stop-color: rgb(255, 255, 255);"
stop-opacity="0"
offset="1"
id="stop910" />
</radialGradient>
<radialGradient
id="gradient-17"
gradientUnits="userSpaceOnUse"
cx="634"
cy="196"
r="93"
gradientTransform="matrix(0.7126241704469086, 3.2814600134408605e-7, 0.0000013125840053763442, 0.7248008481917843, 685.6403546076949, 147.83616457703292)">
<stop
style="stop-color: rgb(255, 255, 255);"
offset="0"
id="stop913" />
<stop
style="stop-color: rgb(255, 255, 255);"
stop-opacity="0"
offset="1"
id="stop915" />
</radialGradient>
<linearGradient
id="gradient-19"
gradientUnits="userSpaceOnUse"
x1="-255.98308563232422"
y1="500.7257080078125"
x2="-255.98308563232422"
y2="551.216552734375"
gradientTransform="matrix(0.9721816590550286, -0.23422891971152335, 0.10362082679554471, 0.43008454599742274, -64.23853990222898, 254.188188506241)">
<stop
style="stop-color: rgb(255, 237, 49);"
offset="0"
id="stop923" />
<stop
style="stop-color: rgb(255, 237, 49);"
stop-opacity="0"
offset="1"
id="stop925" />
</linearGradient>
<radialGradient
id="gradient-20"
gradientUnits="userSpaceOnUse"
cx="-283.0146484375"
cy="510.7113952636719"
r="55.76831817626953"
gradientTransform="matrix(0.6625576282626338, -0.5531133047923916, 1.2298754256288325, 1.4732364008060554, -723.6123845453899, -398.2264071794646)">
<stop
style="stop-color: rgb(255, 237, 49);"
offset="0"
id="stop928" />
<stop
style="stop-color: rgb(255, 237, 49);"
stop-opacity="0"
offset="1"
id="stop930" />
</radialGradient>
<linearGradient
id="gradient-21"
gradientUnits="userSpaceOnUse"
x1="-272.5911560058594"
y1="544.911376953125"
x2="-272.5911560058594"
y2="807.1071166992188">
<stop
style="stop-color: rgb(246, 189, 44);"
offset="0"
id="stop933" />
<stop
style="stop-color: rgb(191, 144, 26);"
offset="1"
id="stop935" />
</linearGradient>
<linearGradient
id="gradient-22"
gradientUnits="userSpaceOnUse"
x1="-254.775146484375"
y1="499.4190673828125"
x2="-254.775146484375"
y2="577.36083984375">
<stop
style="stop-color: rgb(246, 189, 44);"
offset="0"
id="stop938" />
<stop
style="stop-color: rgb(191, 144, 26);"
offset="1"
id="stop940" />
</linearGradient>
</defs>
<sodipodi:namedview
inkscape:document-rotation="0"
inkscape:window-maximized="1"
inkscape:document-units="px"
inkscape:pageopacity="0"
inkscape:window-width="1313"
inkscape:cy="500.39108"
inkscape:cx="-416.46798"
inkscape:current-layer="layer1"
borderopacity="1.0"
showgrid="false"
inkscape:window-x="53"
inkscape:zoom="0.16632743"
inkscape:window-height="712"
pagecolor="#ffffff"
inkscape:window-y="28"
inkscape:pageshadow="2"
bordercolor="#666666"
id="base" />
<g
transform="translate(-52.853 -28.173)"
inkscape:groupmode="layer"
inkscape:label="Layer 1"
id="layer1">
<path
sodipodi:cx="336.42856"
sodipodi:cy="336.64789"
transform="translate(50.508 25.254)"
d="m667.86 336.65a331.43 331.43 0 1 1 -662.86 0 331.43 331.43 0 1 1 662.86 0z"
sodipodi:type="arc"
style="stroke-linejoin:round;stroke:none;stroke-linecap:round;stroke-width:4.6;fill:#5ab0ed;fill-opacity:1"
sodipodi:ry="331.42856"
sodipodi:rx="331.42856"
id="path3144" />
<path
d="m116.33 451.23c1.26 7.28 4.79 15.36 10.07 20.32 7.98 7.52 19.87 11.34 29.74 17.12 6.73 3.94 16.85 5.58 20.07 12.04 6.6 13.23 6.21 31.35 9.38 47.01 4.9 24.15 7.36 49.27 14.82 72.42 3.47 10.79 9.68 22.88 17.97 29.38 6.45 5.04 18.48 7.07 26.25 5.25 6.7-1.57 10.93-11.06 17.14-15.44 4.16-2.93 9.89-3.53 13.99-6.52 5.64-4.09 17.72-11.21 15.23-14.7-4.7-6.57-29.9-8.06-36.81-15.47-3.14-3.38 7.44-11.87 6.67-16.89-0.65-4.33-0.82-12.76-2.39-17.42-11.21-33.05 5.2-54.17 5.35-57.76 0.21-5.07-3.27-22.67 6.15-33.07 6.44-7.11 18.61-8.06 17.74-24.34-0.36-6.82-8.06-15.51-8.04-22.5 0.02-8.07 12.12-9.05 8.17-22.68-1.22-4.21-2.94-9.94-8.04-11.05-10.11-2.18-17.14 3.45-27.92 2.27-10.68-1.16-27.17-15.2-37.53-18.25-5.79-1.7-20.28-8.17-25.12-11.29-3.79-2.46-9.99 2.36-13.32 2.09-7.65-0.62-9.44 8.09-17.16 7.88-8.22-0.22-15.16 2.72-22.79 5.67-6.42 2.48-13.05 7.09-17.3 12.19-2.51 3.02-2.82 8.02-3 12.17-0.59 13.77-1.64 28.22 0.68 41.57z"
style="fill-rule:evenodd;fill:#8dea43;fill-opacity:1"
sodipodi:nodetypes="cssssssssssssssssssssssssssss"
id="path4183" />
<path
d="m601.45 437.91c6.59-7.23 19.09-21.5 15.65-25.15-4.6-4.91-31.01 7.25-39.78-0.52-17.67-15.67-19.71-54.43-39.52-69.81-24.5-19.01-61.89-28.03-93.42-33.36-15.01-2.54-33.59 2.51-46.2 9.75-8.26 4.74-15.65 14.67-21.56 23.1-7.78 11.08-23.77 16.06-28.75 27.2-1.52 3.4 8.73 14.67 8.73 18.48 0 4.4-2.91 9.74-3.59 14.38-1.03 6.99 0.92 16.2 4.1 21.55 3.33 5.6 13.24 7.18 19.51 11.3 5.71 3.75 10.8 11.54 16.42 12.32 4.3 0.59 8.92-8.03 13.35-8.22 3.78-0.15 7.46 7.47 11.29 7.19 5.41-0.4 11.25-9.74 16.43-9.24 5.42 0.53 12.86 7.06 15.4 12.32 2.25 4.66-3.04 12.31-1.03 17.45 3.47 8.89 15.67 15.71 17.45 24.64 1.64 8.18-5.92 17.68-7.18 26.69-0.8 5.71-0.4 11.97 1.02 17.46 0.98 3.75 5.31 6.45 6.16 10.26 2.23 9.87-0.6 21.58 3.08 30.8 3.85 9.6 12.3 22.61 19.51 25.67 4.09 1.73 9.03-9.12 14.37-11.3 3.9-1.58 9.8 2.09 13.35 0 6.37-3.73 12.35-10.76 16.43-17.45 4.47-7.34 5.83-16.56 9.23-24.64 3.1-7.32 6.07-14.88 10.27-21.56 3.33-5.29 10.29-8.71 12.32-14.37 2.76-7.69 2.71-17.3 2.05-25.66-0.36-4.65-7.57-9.9-5.13-13.35 9.19-12.98 28.07-22.8 40.04-35.93z"
style="fill-rule:evenodd;fill:#8dea43;fill-opacity:1"
sodipodi:nodetypes="cssssssssssssssssssssssssssssssss"
id="path5058" />
<path
d="m250.6 57.594c-116.43 51.426-197.75 167.95-197.75 303.35 0.003 3.75 0.066 7.49 0.19 11.22 8.928 8.17 17.996 14.26 26.781 16.65 20.399 5.56 47.049-23.78 68.809-38.25 16.22-10.78 31.28-23.94 45.13-37.47 4.66-4.54 5.48-12.89 10.41-16.78 6.4-5.06 21.2-4 23.59-10.06 2.89-7.33-4.95-20.12-7.75-30.09-2.63-9.37 7.86-15.53 5.34-19.72-7.29-12.15-11.26-15.96-7.59-22.22 1.77-3.01 11.63-9.85 14.66-12.25 5.15-4.1 11.39-11.41 16.03-16.5 10.02-11 15.53-15.63 25.62-21.63 7.34-4.36 13.2-5.24 19.28-5.75 8.93-0.75 17.58-4.72 17.88-12.15 0.01-0.29-0.09-0.54-0.22-0.75-0.07-0.11-0.18-0.23-0.28-0.31-2.11-1.75-10.28-0.61-12.47-3.6-6.53-8.89-7.07-24.77-14.25-32.4-3.89-4.14-13.7-0.15-18.97-2.88-3.92-2.03-7.11-6.995-8.59-11.375-2.79-8.204-2.62-17.612-4.19-26.375-0.63-3.515-1.16-7.087-1.66-10.656z"
style="fill-rule:evenodd;fill:#8dea43;fill-opacity:1"
id="path5063" />
<path
d="m446.53 33.125c-3.89 1.763-7.67 3.647-11.28 5.531-21.84 11.394-51.95 23.157-60.94 43.656-11.94 27.238-4.28 66.828-1.84 99.568 0.95 12.8 5.55 27.29 12.03 37.06 2.65 3.99 12.46 1.28 15.34 4.22 0.02 0.01 0.05 0.04 0.07 0.06 0.02 0.03 0.07 0.09 0.09 0.12 0.04 0.06 0.1 0.16 0.12 0.22 0.81 2.09-3.06 7.36-2 9.32 0.05 0.08 0.13 0.18 0.19 0.24 0.11 0.12 0.27 0.21 0.44 0.29 23.03 10.22 53.23 14.77 78.84 24.28 6.46 2.39 13.52 5.86 17.38 11.43 13.05 18.86 21.64 41.66 33.37 61.88 2.44 4.2 4.74 10.92 9.13 11.38 13.39 1.39 33.92 3.15 44.19-5.82 20.41-17.81 26.32-66.26 47.84-74.56 19.33-7.45 58.6 11.56 74.72 27.31 10.02 9.79-2.46 35.49 3.72 49.31 2.26 5.07 6.77 10.25 12 14.41-3.08-160.28-120.12-292.84-273.41-319.9z"
style="fill-rule:evenodd;fill:#8dea43;fill-opacity:1"
id="path5090" />
<g
transform="matrix(1.8396107,0,0,1.8396107,-71.566068,-77.570841)"
id="glibre">
<g
id="macron"
transform="matrix(0.84148449,0,0,0.84148449,466.0224,-317.18527)">
<path
inkscape:connector-curvature="0"
class="main"
d="m -226.04393,501.50464 25.82916,20.70367 c -10.93431,13.99836 -27.30534,24.05487 -47.39934,26.26813 -24.87689,2.74011 -49.32586,-7.99963 -64.13729,-28.17352 13.94854,-10.58228 11.24874,-8.25812 26.66534,-19.57721 7.81708,10.64737 20.7207,16.31555 33.85014,14.86938 10.71334,-1.18005 19.42147,-6.58447 25.19199,-14.09045 z"
style="fill:#000000"
transform="translate(8.7228955e-8,-21.390767)"
id="path945" />
</g>
<g
id="G"
transform="matrix(0.84148449,0,0,0.84148449,466.0224,-317.18527)">
<path
inkscape:connector-curvature="0"
class="G main"
d="m -238.61481,691.86505 h 93.82932 v 93.82935 l -24.37015,-24.37018 c -23.2079,23.79895 -55.72147,39.15155 -93.55331,39.15155 -46.83683,0 -90.11579,-24.98724 -113.53415,-65.54901 -50.4596,-87.39862 12.61487,-196.64667 113.53415,-196.64667 46.35873,0 89.23176,24.47955 112.81076,64.31165 l -54.66439,29.28448 c -12.69412,-19.6886 -34.56584,-31.6889 -58.14637,-31.6889 -53.26288,0 -86.55216,57.65875 -59.92066,103.78576 12.35962,21.40772 35.20123,34.5954 59.92066,34.5954 20.17045,0 37.47648,-8.26886 49.74858,-21.04901 z"
style="fill:#000000"
transform="translate(7.1302561,2.3767521)"
id="path948" />
</g>
</g>
</g>
<metadata
id="metadata9">
<rdf:RDF>
<cc:Work>
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<cc:license
rdf:resource="http://creativecommons.org/publicdomain/zero/1.0/" />
<dc:publisher>
<cc:Agent
rdf:about="http://openclipart.org/">
<dc:title>Openclipart</dc:title>
</cc:Agent>
</dc:publisher>
<dc:title />
<dc:date>2006-09-11T08:15:36</dc:date>
<dc:description>Since the flood, the continents have drifted further apart, and the ocean level has risen, covering some of the land and changing the continents' shapes at the edges. Some of the pieces have bumped together, forming high mountain chains.</dc:description>
<dc:source>https://openclipart.org/detail/128/earth-with-continents-separated-by-jonadab</dc:source>
<dc:creator>
<cc:Agent>
<dc:title>jonadab</dc:title>
</cc:Agent>
</dc:creator>
<dc:subject>
<rdf:Bag>
<rdf:li>continent</rdf:li>
<rdf:li>contour</rdf:li>
<rdf:li>earth</rdf:li>
<rdf:li>flood</rdf:li>
<rdf:li>geography</rdf:li>
<rdf:li>geology</rdf:li>
<rdf:li>globe</rdf:li>
<rdf:li>planet</rdf:li>
<rdf:li>sea</rdf:li>
<rdf:li>world</rdf:li>
</rdf:Bag>
</dc:subject>
</cc:Work>
<cc:License
rdf:about="http://creativecommons.org/publicdomain/zero/1.0/">
<cc:permits
rdf:resource="http://creativecommons.org/ns#Reproduction" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#Distribution" />
<cc:permits
rdf:resource="http://creativecommons.org/ns#DerivativeWorks" />
</cc:License>
</rdf:RDF>
</metadata>
</svg>

After

Width:  |  Height:  |  Size: 18 KiB

55
public/index.php Normal file
View File

@ -0,0 +1,55 @@
<?php
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request;
define('LARAVEL_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Check If Application Is Under Maintenance
|--------------------------------------------------------------------------
|
| If the application is maintenance / demo mode via the "down" command we
| will require this file so that any prerendered template can be shown
| instead of starting the framework, which could cause an exception.
|
*/
if (file_exists(__DIR__.'/../storage/framework/maintenance.php')) {
require __DIR__.'/../storage/framework/maintenance.php';
}
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| this application. We just need to utilize it! We'll simply require it
| into the script here so we don't need to manually load our classes.
|
*/
require __DIR__.'/../vendor/autoload.php';
/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request using
| the application's HTTP kernel. Then, we will send the response back
| to this client's browser, allowing them to enjoy our application.
|
*/
$app = require_once __DIR__.'/../bootstrap/app.php';
$kernel = $app->make(Kernel::class);
$response = tap($kernel->handle(
$request = Request::capture()
))->send();
$kernel->terminate($request, $response);

19393
public/js/app.js vendored Normal file

File diff suppressed because it is too large Load Diff

4
public/mix-manifest.json Normal file
View File

@ -0,0 +1,4 @@
{
"/js/app.js": "/js/app.js",
"/css/app.css": "/css/app.css"
}

2
public/robots.txt Normal file
View File

@ -0,0 +1,2 @@
User-agent: *
Disallow:

1
resources/js/app.js vendored Normal file
View File

@ -0,0 +1 @@
require('./bootstrap');

28
resources/js/bootstrap.js vendored Normal file
View File

@ -0,0 +1,28 @@
window._ = require('lodash');
/**
* We'll load the axios HTTP library which allows us to easily issue requests
* to our Laravel back-end. This library automatically handles sending the
* CSRF token as a header based on the value of the "XSRF" token cookie.
*/
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
/**
* Echo exposes an expressive API for subscribing to channels and listening
* for events that are broadcast by Laravel. Echo and event broadcasting
* allows your team to easily build robust real-time web applications.
*/
// import Echo from 'laravel-echo';
// window.Pusher = require('pusher-js');
// window.Echo = new Echo({
// broadcaster: 'pusher',
// key: process.env.MIX_PUSHER_APP_KEY,
// cluster: process.env.MIX_PUSHER_APP_CLUSTER,
// forceTLS: true
// });

View File

@ -0,0 +1,19 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used during authentication for various
| messages that we need to display to the user. You are free to modify
| these language lines according to your application's requirements.
|
*/
'failed' => 'These credentials do not match our records.',
'throttle' => 'Too many login attempts. Please try again in :seconds seconds.',
];

View File

@ -0,0 +1,19 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Pagination Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are used by the paginator library to build
| the simple pagination links. You are free to change them to anything
| you want to customize your views to better match your application.
|
*/
'previous' => '&laquo; Previous',
'next' => 'Next &raquo;',
];

View File

@ -0,0 +1,22 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Password Reset Language Lines
|--------------------------------------------------------------------------
|
| The following language lines are the default lines which match reasons
| that are given by the password broker for a password update attempt
| has failed, such as for an invalid token or invalid new password.
|
*/
'reset' => 'Your password has been reset!',
'sent' => 'We have emailed your password reset link!',
'throttled' => 'Please wait before retrying.',
'token' => 'This password reset token is invalid.',
'user' => "We can't find a user with that email address.",
];

View File

@ -0,0 +1,151 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| as the size rules. Feel free to tweak each of these messages here.
|
*/
'accepted' => 'The :attribute must be accepted.',
'active_url' => 'The :attribute is not a valid URL.',
'after' => 'The :attribute must be a date after :date.',
'after_or_equal' => 'The :attribute must be a date after or equal to :date.',
'alpha' => 'The :attribute may only contain letters.',
'alpha_dash' => 'The :attribute may only contain letters, numbers, dashes and underscores.',
'alpha_num' => 'The :attribute may only contain letters and numbers.',
'array' => 'The :attribute must be an array.',
'before' => 'The :attribute must be a date before :date.',
'before_or_equal' => 'The :attribute must be a date before or equal to :date.',
'between' => [
'numeric' => 'The :attribute must be between :min and :max.',
'file' => 'The :attribute must be between :min and :max kilobytes.',
'string' => 'The :attribute must be between :min and :max characters.',
'array' => 'The :attribute must have between :min and :max items.',
],
'boolean' => 'The :attribute field must be true or false.',
'confirmed' => 'The :attribute confirmation does not match.',
'date' => 'The :attribute is not a valid date.',
'date_equals' => 'The :attribute must be a date equal to :date.',
'date_format' => 'The :attribute does not match the format :format.',
'different' => 'The :attribute and :other must be different.',
'digits' => 'The :attribute must be :digits digits.',
'digits_between' => 'The :attribute must be between :min and :max digits.',
'dimensions' => 'The :attribute has invalid image dimensions.',
'distinct' => 'The :attribute field has a duplicate value.',
'email' => 'The :attribute must be a valid email address.',
'ends_with' => 'The :attribute must end with one of the following: :values.',
'exists' => 'The selected :attribute is invalid.',
'file' => 'The :attribute must be a file.',
'filled' => 'The :attribute field must have a value.',
'gt' => [
'numeric' => 'The :attribute must be greater than :value.',
'file' => 'The :attribute must be greater than :value kilobytes.',
'string' => 'The :attribute must be greater than :value characters.',
'array' => 'The :attribute must have more than :value items.',
],
'gte' => [
'numeric' => 'The :attribute must be greater than or equal :value.',
'file' => 'The :attribute must be greater than or equal :value kilobytes.',
'string' => 'The :attribute must be greater than or equal :value characters.',
'array' => 'The :attribute must have :value items or more.',
],
'image' => 'The :attribute must be an image.',
'in' => 'The selected :attribute is invalid.',
'in_array' => 'The :attribute field does not exist in :other.',
'integer' => 'The :attribute must be an integer.',
'ip' => 'The :attribute must be a valid IP address.',
'ipv4' => 'The :attribute must be a valid IPv4 address.',
'ipv6' => 'The :attribute must be a valid IPv6 address.',
'json' => 'The :attribute must be a valid JSON string.',
'lt' => [
'numeric' => 'The :attribute must be less than :value.',
'file' => 'The :attribute must be less than :value kilobytes.',
'string' => 'The :attribute must be less than :value characters.',
'array' => 'The :attribute must have less than :value items.',
],
'lte' => [
'numeric' => 'The :attribute must be less than or equal :value.',
'file' => 'The :attribute must be less than or equal :value kilobytes.',
'string' => 'The :attribute must be less than or equal :value characters.',
'array' => 'The :attribute must not have more than :value items.',
],
'max' => [
'numeric' => 'The :attribute may not be greater than :max.',
'file' => 'The :attribute may not be greater than :max kilobytes.',
'string' => 'The :attribute may not be greater than :max characters.',
'array' => 'The :attribute may not have more than :max items.',
],
'mimes' => 'The :attribute must be a file of type: :values.',
'mimetypes' => 'The :attribute must be a file of type: :values.',
'min' => [
'numeric' => 'The :attribute must be at least :min.',
'file' => 'The :attribute must be at least :min kilobytes.',
'string' => 'The :attribute must be at least :min characters.',
'array' => 'The :attribute must have at least :min items.',
],
'not_in' => 'The selected :attribute is invalid.',
'not_regex' => 'The :attribute format is invalid.',
'numeric' => 'The :attribute must be a number.',
'password' => 'The password is incorrect.',
'present' => 'The :attribute field must be present.',
'regex' => 'The :attribute format is invalid.',
'required' => 'The :attribute field is required.',
'required_if' => 'The :attribute field is required when :other is :value.',
'required_unless' => 'The :attribute field is required unless :other is in :values.',
'required_with' => 'The :attribute field is required when :values is present.',
'required_with_all' => 'The :attribute field is required when :values are present.',
'required_without' => 'The :attribute field is required when :values is not present.',
'required_without_all' => 'The :attribute field is required when none of :values are present.',
'same' => 'The :attribute and :other must match.',
'size' => [
'numeric' => 'The :attribute must be :size.',
'file' => 'The :attribute must be :size kilobytes.',
'string' => 'The :attribute must be :size characters.',
'array' => 'The :attribute must contain :size items.',
],
'starts_with' => 'The :attribute must start with one of the following: :values.',
'string' => 'The :attribute must be a string.',
'timezone' => 'The :attribute must be a valid zone.',
'unique' => 'The :attribute has already been taken.',
'uploaded' => 'The :attribute failed to upload.',
'url' => 'The :attribute format is invalid.',
'uuid' => 'The :attribute must be a valid UUID.',
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap our attribute placeholder
| with something more reader friendly such as "E-Mail Address" instead
| of "email". This simply helps us make our message more expressive.
|
*/
'attributes' => [],
];

100
resources/sass/app.scss vendored Normal file
View File

@ -0,0 +1,100 @@
/* DEFINE FONTFACE */
$button-color:#2196F3;
.buttons::after{
content:"Aller";
}
/* BUTTONS ICONS (before) */
.donate::before,a[href*="demo.cesium.app"]::before,a[href*="helloasso.com"]::before,a[href*="opencollective.com"]::before,a[href*="liberapay.com"]::before{
font-family: "Font Awesome 5 Free";
font-weight: 900;
content: "\f4b9";
padding-right:5px;
}
a[href*="chat"]::before,a[href*="forum"]::before{
font-family: "Font Awesome 5 Free";
font-weight: 900;
content: "\f086";
padding-right:5px;
}
a[href*="framasphere.org"]::before{
font-family: "Font Awesome 5 Brands";
font-weight: 900;
content: "\f791";
padding-right:5px;
}
a[href*="facebook.com"]::before{
font-family: "Font Awesome 5 Brands";
font-weight: 900;
content: "\f09a";
padding-right:5px;
}
a[href*="mastodon"]::before{
font-family: "Font Awesome 5 Brands";
font-weight: 900;
content: "\f4f6";
padding-right:5px;
}
a[href*="twitter.com"]::before{
font-family: "Font Awesome 5 Brands";
font-weight: 900;
content: "\f099";
padding-right:5px;
}
a[href*="youtube.com"]::before,a[href*="peertube"]::before,a[href*="tube.p2p.legal"]::before{
font-family: "Font Awesome 5 Free";
font-weight: 900;
content: "\f04b";
padding-right:5px;
}
a[href*="agenda"]::before,a[href*="calendar"]::before,a[href*="events"]::before{
font-family: "Font Awesome 5 Free";
font-weight: 900;
content: "\f073";
padding-right:5px;
}
/* BUTTONS TEXTS (after) */
a[href*="facebook.com"]::after{
content:"Facebook";
}
a[href*="agenda"]::after,a[href*="calendar"]::after,a[href*="events"]::after{
content:"Agenda";
}
a[href*="framasphere.org"]::after{
content:"diaspora";
}
a[href*="forum"]::after{
content:"Forum";
}
a[href*="chat"]::after{
content:"Chat";
}
a[href*="demo.cesium.app"]::after,a[href*="helloasso.com"]::after,a[href*="opencollective.com"]::after,a[href*="liberapay.com"]::after{
content:"Donner";
}
a[href*="mastodon"]::after{
content:"Mastodon";
}
a[href*="twitter.com"]::after{
content:"Twitter";
}
a[href*="peertube"]::after{
content:"Peertube";
}
a[href*="youtube.com"]::after{
content:"Youtube";
}
/* DEFINE DEFAULT USE FONT */
@media (prefers-color-scheme: dark) {
.day.dark-scheme { background: #333; color: white; }
.night.dark-scheme { background: black; color: #ddd; }
}
@import 'softbox';
@import 'choicebox';
// MATERIALIZE CSS
@import 'materialize/sass/materialize.scss';

20
resources/sass/choicebox.scss vendored Normal file
View File

@ -0,0 +1,20 @@
#choicebox{
display:flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
a{
margin:10px;
}
.cb-buttons{
display:grid;
grid-template-columns: repeat(3, 50%);
}
@media only screen and (max-width: 460px) {
/* For mobile phones: */
.cb-buttons{
display:grid;
grid-template-columns: repeat(1, 30%);
}
}

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014-2018 Materialize
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,91 @@
<p align="center">
<a href="http://materializecss.com/">
<img src="http://materializecss.com/res/materialize.svg" width="150">
</a>
</p>
<h3 align="center">MaterializeCSS</h3>
<p align="center">
Materialize, a CSS Framework based on material design.
<br>
<a href="http://materializecss.com/"><strong>-- Browse the docs --</strong></a>
<br>
<br>
<a href="https://travis-ci.org/Dogfalo/materialize">
<img src="https://travis-ci.org/Dogfalo/materialize.svg?branch=master" alt="Travis CI badge">
</a>
<a href="https://badge.fury.io/js/materialize-css">
<img src="https://badge.fury.io/js/materialize-css.svg" alt="npm version badge">
</a>
<a href="https://cdnjs.com/libraries/materialize">
<img src="https://img.shields.io/cdnjs/v/materialize.svg" alt="CDNJS version badge">
</a>
<a href="https://david-dm.org/Dogfalo/materialize">
<img src="https://david-dm.org/Dogfalo/materialize/status.svg" alt="dependencies Status badge">
</a>
<a href="https://david-dm.org/Dogfalo/materialize#info=devDependencies">
<img src="https://david-dm.org/Dogfalo/materialize/dev-status.svg" alt="devDependency Status badge">
</a>
<a href="https://gitter.im/Dogfalo/materialize">
<img src="https://badges.gitter.im/Join%20Chat.svg" alt="Gitter badge">
</a>
</p>
## Table of Contents
- [Quickstart](#quickstart)
- [Documentation](#documentation)
- [Supported Browsers](#supported-browsers)
- [Changelog](#changelog)
- [Testing](#testing)
- [Contributing](#contributing)
- [Copyright and license](#copyright-and-license)
## Quickstart:
Read the [getting started guide](http://materializecss.com/getting-started.html) for more information on how to use materialize.
- [Download the latest release](https://github.com/Dogfalo/materialize/releases/latest) of materialize directly from GitHub. ([Beta](https://github.com/Dogfalo/materialize/releases/))
- Clone the repo: `git clone https://github.com/Dogfalo/materialize.git` (Beta: `git clone -b v1-dev https://github.com/Dogfalo/materialize.git`)
- Include the files via [cdnjs](https://cdnjs.com/libraries/materialize). More [here](http://materializecss.com/getting-started.html). ([Beta](https://cdnjs.com/libraries/materialize/1.0.0-beta))
- Install with [npm](https://www.npmjs.com): `npm install materialize-css` (Beta: `npm install materialize-css@next`)
- Install with [Bower](https://bower.io): `bower install materialize` ([DEPRECATED](https://bower.io/blog/2017/how-to-migrate-away-from-bower/))
- Install with [Atmosphere](https://atmospherejs.com): `meteor add materialize:materialize` (Beta: `meteor add materialize:materialize@=1.0.0-beta`)
## Documentation
The documentation can be found at <http://materializecss.com>. To run the documentation locally on your machine, you need [Node.js](https://nodejs.org/en/) installed on your computer.
### Running documentation locally
Run these commands to set up the documentation:
```bash
git clone https://github.com/Dogfalo/materialize
cd materialize
npm install
```
Then run `grunt monitor` to compile the documentation. When it finishes, open a new browser window and navigate to `localhost:8000`. We use [BrowserSync](https://www.browsersync.io/) to display the documentation.
### Documentation for previous releases
Previous releases and their documentation are available for [download](https://github.com/Dogfalo/materialize/releases).
## Supported Browsers:
Materialize is compatible with:
- Chrome 35+
- Firefox 31+
- Safari 9+
- Opera
- Edge
- IE 11+
## Changelog
For changelogs, check out [the Releases section of materialize](https://github.com/Dogfalo/materialize/releases) or the [CHANGELOG.md](CHANGELOG.md).
## Testing
We use Jasmine as our testing framework and we're trying to write a robust test suite for our components. If you want to help, [here's a starting guide on how to write tests in Jasmine](CONTRIBUTING.md#jasmine-testing-guide).
## Contributing
Check out the [CONTRIBUTING document](CONTRIBUTING.md) in the root of the repository to learn how you can contribute. You can also browse the [help-wanted](https://github.com/Dogfalo/materialize/labels/help-wanted) tag in our issue tracker to find things to do.
## Copyright and license
Code Copyright 2018 Materialize. Code released under the MIT license.

View File

@ -0,0 +1,34 @@
/*
v2.2.0
2017 Julian Garnier
Released under the MIT license
*/
var $jscomp={scope:{}};$jscomp.defineProperty="function"==typeof Object.defineProperties?Object.defineProperty:function(e,r,p){if(p.get||p.set)throw new TypeError("ES3 does not support getters and setters.");e!=Array.prototype&&e!=Object.prototype&&(e[r]=p.value)};$jscomp.getGlobal=function(e){return"undefined"!=typeof window&&window===e?e:"undefined"!=typeof global&&null!=global?global:e};$jscomp.global=$jscomp.getGlobal(this);$jscomp.SYMBOL_PREFIX="jscomp_symbol_";
$jscomp.initSymbol=function(){$jscomp.initSymbol=function(){};$jscomp.global.Symbol||($jscomp.global.Symbol=$jscomp.Symbol)};$jscomp.symbolCounter_=0;$jscomp.Symbol=function(e){return $jscomp.SYMBOL_PREFIX+(e||"")+$jscomp.symbolCounter_++};
$jscomp.initSymbolIterator=function(){$jscomp.initSymbol();var e=$jscomp.global.Symbol.iterator;e||(e=$jscomp.global.Symbol.iterator=$jscomp.global.Symbol("iterator"));"function"!=typeof Array.prototype[e]&&$jscomp.defineProperty(Array.prototype,e,{configurable:!0,writable:!0,value:function(){return $jscomp.arrayIterator(this)}});$jscomp.initSymbolIterator=function(){}};$jscomp.arrayIterator=function(e){var r=0;return $jscomp.iteratorPrototype(function(){return r<e.length?{done:!1,value:e[r++]}:{done:!0}})};
$jscomp.iteratorPrototype=function(e){$jscomp.initSymbolIterator();e={next:e};e[$jscomp.global.Symbol.iterator]=function(){return this};return e};$jscomp.array=$jscomp.array||{};$jscomp.iteratorFromArray=function(e,r){$jscomp.initSymbolIterator();e instanceof String&&(e+="");var p=0,m={next:function(){if(p<e.length){var u=p++;return{value:r(u,e[u]),done:!1}}m.next=function(){return{done:!0,value:void 0}};return m.next()}};m[Symbol.iterator]=function(){return m};return m};
$jscomp.polyfill=function(e,r,p,m){if(r){p=$jscomp.global;e=e.split(".");for(m=0;m<e.length-1;m++){var u=e[m];u in p||(p[u]={});p=p[u]}e=e[e.length-1];m=p[e];r=r(m);r!=m&&null!=r&&$jscomp.defineProperty(p,e,{configurable:!0,writable:!0,value:r})}};$jscomp.polyfill("Array.prototype.keys",function(e){return e?e:function(){return $jscomp.iteratorFromArray(this,function(e){return e})}},"es6-impl","es3");var $jscomp$this=this;
(function(r){M.anime=r()})(function(){function e(a){if(!h.col(a))try{return document.querySelectorAll(a)}catch(c){}}function r(a,c){for(var d=a.length,b=2<=arguments.length?arguments[1]:void 0,f=[],n=0;n<d;n++)if(n in a){var k=a[n];c.call(b,k,n,a)&&f.push(k)}return f}function p(a){return a.reduce(function(a,d){return a.concat(h.arr(d)?p(d):d)},[])}function m(a){if(h.arr(a))return a;
h.str(a)&&(a=e(a)||a);return a instanceof NodeList||a instanceof HTMLCollection?[].slice.call(a):[a]}function u(a,c){return a.some(function(a){return a===c})}function C(a){var c={},d;for(d in a)c[d]=a[d];return c}function D(a,c){var d=C(a),b;for(b in a)d[b]=c.hasOwnProperty(b)?c[b]:a[b];return d}function z(a,c){var d=C(a),b;for(b in c)d[b]=h.und(a[b])?c[b]:a[b];return d}function T(a){a=a.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,function(a,c,d,k){return c+c+d+d+k+k});var c=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(a);
a=parseInt(c[1],16);var d=parseInt(c[2],16),c=parseInt(c[3],16);return"rgba("+a+","+d+","+c+",1)"}function U(a){function c(a,c,b){0>b&&(b+=1);1<b&&--b;return b<1/6?a+6*(c-a)*b:.5>b?c:b<2/3?a+(c-a)*(2/3-b)*6:a}var d=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(a)||/hsla\((\d+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)/g.exec(a);a=parseInt(d[1])/360;var b=parseInt(d[2])/100,f=parseInt(d[3])/100,d=d[4]||1;if(0==b)f=b=a=f;else{var n=.5>f?f*(1+b):f+b-f*b,k=2*f-n,f=c(k,n,a+1/3),b=c(k,n,a);a=c(k,n,a-1/3)}return"rgba("+
255*f+","+255*b+","+255*a+","+d+")"}function y(a){if(a=/([\+\-]?[0-9#\.]+)(%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn)?$/.exec(a))return a[2]}function V(a){if(-1<a.indexOf("translate")||"perspective"===a)return"px";if(-1<a.indexOf("rotate")||-1<a.indexOf("skew"))return"deg"}function I(a,c){return h.fnc(a)?a(c.target,c.id,c.total):a}function E(a,c){if(c in a.style)return getComputedStyle(a).getPropertyValue(c.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase())||"0"}function J(a,c){if(h.dom(a)&&
u(W,c))return"transform";if(h.dom(a)&&(a.getAttribute(c)||h.svg(a)&&a[c]))return"attribute";if(h.dom(a)&&"transform"!==c&&E(a,c))return"css";if(null!=a[c])return"object"}function X(a,c){var d=V(c),d=-1<c.indexOf("scale")?1:0+d;a=a.style.transform;if(!a)return d;for(var b=[],f=[],n=[],k=/(\w+)\((.+?)\)/g;b=k.exec(a);)f.push(b[1]),n.push(b[2]);a=r(n,function(a,b){return f[b]===c});return a.length?a[0]:d}function K(a,c){switch(J(a,c)){case "transform":return X(a,c);case "css":return E(a,c);case "attribute":return a.getAttribute(c)}return a[c]||
0}function L(a,c){var d=/^(\*=|\+=|-=)/.exec(a);if(!d)return a;var b=y(a)||0;c=parseFloat(c);a=parseFloat(a.replace(d[0],""));switch(d[0][0]){case "+":return c+a+b;case "-":return c-a+b;case "*":return c*a+b}}function F(a,c){return Math.sqrt(Math.pow(c.x-a.x,2)+Math.pow(c.y-a.y,2))}function M(a){a=a.points;for(var c=0,d,b=0;b<a.numberOfItems;b++){var f=a.getItem(b);0<b&&(c+=F(d,f));d=f}return c}function N(a){if(a.getTotalLength)return a.getTotalLength();switch(a.tagName.toLowerCase()){case "circle":return 2*
Math.PI*a.getAttribute("r");case "rect":return 2*a.getAttribute("width")+2*a.getAttribute("height");case "line":return F({x:a.getAttribute("x1"),y:a.getAttribute("y1")},{x:a.getAttribute("x2"),y:a.getAttribute("y2")});case "polyline":return M(a);case "polygon":var c=a.points;return M(a)+F(c.getItem(c.numberOfItems-1),c.getItem(0))}}function Y(a,c){function d(b){b=void 0===b?0:b;return a.el.getPointAtLength(1<=c+b?c+b:0)}var b=d(),f=d(-1),n=d(1);switch(a.property){case "x":return b.x;case "y":return b.y;
case "angle":return 180*Math.atan2(n.y-f.y,n.x-f.x)/Math.PI}}function O(a,c){var d=/-?\d*\.?\d+/g,b;b=h.pth(a)?a.totalLength:a;if(h.col(b))if(h.rgb(b)){var f=/rgb\((\d+,\s*[\d]+,\s*[\d]+)\)/g.exec(b);b=f?"rgba("+f[1]+",1)":b}else b=h.hex(b)?T(b):h.hsl(b)?U(b):void 0;else f=(f=y(b))?b.substr(0,b.length-f.length):b,b=c&&!/\s/g.test(b)?f+c:f;b+="";return{original:b,numbers:b.match(d)?b.match(d).map(Number):[0],strings:h.str(a)||c?b.split(d):[]}}function P(a){a=a?p(h.arr(a)?a.map(m):m(a)):[];return r(a,
function(a,d,b){return b.indexOf(a)===d})}function Z(a){var c=P(a);return c.map(function(a,b){return{target:a,id:b,total:c.length}})}function aa(a,c){var d=C(c);if(h.arr(a)){var b=a.length;2!==b||h.obj(a[0])?h.fnc(c.duration)||(d.duration=c.duration/b):a={value:a}}return m(a).map(function(a,b){b=b?0:c.delay;a=h.obj(a)&&!h.pth(a)?a:{value:a};h.und(a.delay)&&(a.delay=b);return a}).map(function(a){return z(a,d)})}function ba(a,c){var d={},b;for(b in a){var f=I(a[b],c);h.arr(f)&&(f=f.map(function(a){return I(a,
c)}),1===f.length&&(f=f[0]));d[b]=f}d.duration=parseFloat(d.duration);d.delay=parseFloat(d.delay);return d}function ca(a){return h.arr(a)?A.apply(this,a):Q[a]}function da(a,c){var d;return a.tweens.map(function(b){b=ba(b,c);var f=b.value,e=K(c.target,a.name),k=d?d.to.original:e,k=h.arr(f)?f[0]:k,w=L(h.arr(f)?f[1]:f,k),e=y(w)||y(k)||y(e);b.from=O(k,e);b.to=O(w,e);b.start=d?d.end:a.offset;b.end=b.start+b.delay+b.duration;b.easing=ca(b.easing);b.elasticity=(1E3-Math.min(Math.max(b.elasticity,1),999))/
1E3;b.isPath=h.pth(f);b.isColor=h.col(b.from.original);b.isColor&&(b.round=1);return d=b})}function ea(a,c){return r(p(a.map(function(a){return c.map(function(b){var c=J(a.target,b.name);if(c){var d=da(b,a);b={type:c,property:b.name,animatable:a,tweens:d,duration:d[d.length-1].end,delay:d[0].delay}}else b=void 0;return b})})),function(a){return!h.und(a)})}function R(a,c,d,b){var f="delay"===a;return c.length?(f?Math.min:Math.max).apply(Math,c.map(function(b){return b[a]})):f?b.delay:d.offset+b.delay+
b.duration}function fa(a){var c=D(ga,a),d=D(S,a),b=Z(a.targets),f=[],e=z(c,d),k;for(k in a)e.hasOwnProperty(k)||"targets"===k||f.push({name:k,offset:e.offset,tweens:aa(a[k],d)});a=ea(b,f);return z(c,{children:[],animatables:b,animations:a,duration:R("duration",a,c,d),delay:R("delay",a,c,d)})}function q(a){function c(){return window.Promise&&new Promise(function(a){return p=a})}function d(a){return g.reversed?g.duration-a:a}function b(a){for(var b=0,c={},d=g.animations,f=d.length;b<f;){var e=d[b],
k=e.animatable,h=e.tweens,n=h.length-1,l=h[n];n&&(l=r(h,function(b){return a<b.end})[0]||l);for(var h=Math.min(Math.max(a-l.start-l.delay,0),l.duration)/l.duration,w=isNaN(h)?1:l.easing(h,l.elasticity),h=l.to.strings,p=l.round,n=[],m=void 0,m=l.to.numbers.length,t=0;t<m;t++){var x=void 0,x=l.to.numbers[t],q=l.from.numbers[t],x=l.isPath?Y(l.value,w*x):q+w*(x-q);p&&(l.isColor&&2<t||(x=Math.round(x*p)/p));n.push(x)}if(l=h.length)for(m=h[0],w=0;w<l;w++)p=h[w+1],t=n[w],isNaN(t)||(m=p?m+(t+p):m+(t+" "));
else m=n[0];ha[e.type](k.target,e.property,m,c,k.id);e.currentValue=m;b++}if(b=Object.keys(c).length)for(d=0;d<b;d++)H||(H=E(document.body,"transform")?"transform":"-webkit-transform"),g.animatables[d].target.style[H]=c[d].join(" ");g.currentTime=a;g.progress=a/g.duration*100}function f(a){if(g[a])g[a](g)}function e(){g.remaining&&!0!==g.remaining&&g.remaining--}function k(a){var k=g.duration,n=g.offset,w=n+g.delay,r=g.currentTime,x=g.reversed,q=d(a);if(g.children.length){var u=g.children,v=u.length;
if(q>=g.currentTime)for(var G=0;G<v;G++)u[G].seek(q);else for(;v--;)u[v].seek(q)}if(q>=w||!k)g.began||(g.began=!0,f("begin")),f("run");if(q>n&&q<k)b(q);else if(q<=n&&0!==r&&(b(0),x&&e()),q>=k&&r!==k||!k)b(k),x||e();f("update");a>=k&&(g.remaining?(t=h,"alternate"===g.direction&&(g.reversed=!g.reversed)):(g.pause(),g.completed||(g.completed=!0,f("complete"),"Promise"in window&&(p(),m=c()))),l=0)}a=void 0===a?{}:a;var h,t,l=0,p=null,m=c(),g=fa(a);g.reset=function(){var a=g.direction,c=g.loop;g.currentTime=
0;g.progress=0;g.paused=!0;g.began=!1;g.completed=!1;g.reversed="reverse"===a;g.remaining="alternate"===a&&1===c?2:c;b(0);for(a=g.children.length;a--;)g.children[a].reset()};g.tick=function(a){h=a;t||(t=h);k((l+h-t)*q.speed)};g.seek=function(a){k(d(a))};g.pause=function(){var a=v.indexOf(g);-1<a&&v.splice(a,1);g.paused=!0};g.play=function(){g.paused&&(g.paused=!1,t=0,l=d(g.currentTime),v.push(g),B||ia())};g.reverse=function(){g.reversed=!g.reversed;t=0;l=d(g.currentTime)};g.restart=function(){g.pause();
g.reset();g.play()};g.finished=m;g.reset();g.autoplay&&g.play();return g}var ga={update:void 0,begin:void 0,run:void 0,complete:void 0,loop:1,direction:"normal",autoplay:!0,offset:0},S={duration:1E3,delay:0,easing:"easeOutElastic",elasticity:500,round:0},W="translateX translateY translateZ rotate rotateX rotateY rotateZ scale scaleX scaleY scaleZ skewX skewY perspective".split(" "),H,h={arr:function(a){return Array.isArray(a)},obj:function(a){return-1<Object.prototype.toString.call(a).indexOf("Object")},
pth:function(a){return h.obj(a)&&a.hasOwnProperty("totalLength")},svg:function(a){return a instanceof SVGElement},dom:function(a){return a.nodeType||h.svg(a)},str:function(a){return"string"===typeof a},fnc:function(a){return"function"===typeof a},und:function(a){return"undefined"===typeof a},hex:function(a){return/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(a)},rgb:function(a){return/^rgb/.test(a)},hsl:function(a){return/^hsl/.test(a)},col:function(a){return h.hex(a)||h.rgb(a)||h.hsl(a)}},A=function(){function a(a,
d,b){return(((1-3*b+3*d)*a+(3*b-6*d))*a+3*d)*a}return function(c,d,b,f){if(0<=c&&1>=c&&0<=b&&1>=b){var e=new Float32Array(11);if(c!==d||b!==f)for(var k=0;11>k;++k)e[k]=a(.1*k,c,b);return function(k){if(c===d&&b===f)return k;if(0===k)return 0;if(1===k)return 1;for(var h=0,l=1;10!==l&&e[l]<=k;++l)h+=.1;--l;var l=h+(k-e[l])/(e[l+1]-e[l])*.1,n=3*(1-3*b+3*c)*l*l+2*(3*b-6*c)*l+3*c;if(.001<=n){for(h=0;4>h;++h){n=3*(1-3*b+3*c)*l*l+2*(3*b-6*c)*l+3*c;if(0===n)break;var m=a(l,c,b)-k,l=l-m/n}k=l}else if(0===
n)k=l;else{var l=h,h=h+.1,g=0;do m=l+(h-l)/2,n=a(m,c,b)-k,0<n?h=m:l=m;while(1e-7<Math.abs(n)&&10>++g);k=m}return a(k,d,f)}}}}(),Q=function(){function a(a,b){return 0===a||1===a?a:-Math.pow(2,10*(a-1))*Math.sin(2*(a-1-b/(2*Math.PI)*Math.asin(1))*Math.PI/b)}var c="Quad Cubic Quart Quint Sine Expo Circ Back Elastic".split(" "),d={In:[[.55,.085,.68,.53],[.55,.055,.675,.19],[.895,.03,.685,.22],[.755,.05,.855,.06],[.47,0,.745,.715],[.95,.05,.795,.035],[.6,.04,.98,.335],[.6,-.28,.735,.045],a],Out:[[.25,
.46,.45,.94],[.215,.61,.355,1],[.165,.84,.44,1],[.23,1,.32,1],[.39,.575,.565,1],[.19,1,.22,1],[.075,.82,.165,1],[.175,.885,.32,1.275],function(b,c){return 1-a(1-b,c)}],InOut:[[.455,.03,.515,.955],[.645,.045,.355,1],[.77,0,.175,1],[.86,0,.07,1],[.445,.05,.55,.95],[1,0,0,1],[.785,.135,.15,.86],[.68,-.55,.265,1.55],function(b,c){return.5>b?a(2*b,c)/2:1-a(-2*b+2,c)/2}]},b={linear:A(.25,.25,.75,.75)},f={},e;for(e in d)f.type=e,d[f.type].forEach(function(a){return function(d,f){b["ease"+a.type+c[f]]=h.fnc(d)?
d:A.apply($jscomp$this,d)}}(f)),f={type:f.type};return b}(),ha={css:function(a,c,d){return a.style[c]=d},attribute:function(a,c,d){return a.setAttribute(c,d)},object:function(a,c,d){return a[c]=d},transform:function(a,c,d,b,f){b[f]||(b[f]=[]);b[f].push(c+"("+d+")")}},v=[],B=0,ia=function(){function a(){B=requestAnimationFrame(c)}function c(c){var b=v.length;if(b){for(var d=0;d<b;)v[d]&&v[d].tick(c),d++;a()}else cancelAnimationFrame(B),B=0}return a}();q.version="2.2.0";q.speed=1;q.running=v;q.remove=
function(a){a=P(a);for(var c=v.length;c--;)for(var d=v[c],b=d.animations,f=b.length;f--;)u(a,b[f].animatable.target)&&(b.splice(f,1),b.length||d.pause())};q.getValue=K;q.path=function(a,c){var d=h.str(a)?e(a)[0]:a,b=c||100;return function(a){return{el:d,property:a,totalLength:N(d)*(b/100)}}};q.setDashoffset=function(a){var c=N(a);a.setAttribute("stroke-dasharray",c);return c};q.bezier=A;q.easings=Q;q.timeline=function(a){var c=q(a);c.pause();c.duration=0;c.add=function(d){c.children.forEach(function(a){a.began=
!0;a.completed=!0});m(d).forEach(function(b){var d=z(b,D(S,a||{}));d.targets=d.targets||a.targets;b=c.duration;var e=d.offset;d.autoplay=!1;d.direction=c.direction;d.offset=h.und(e)?b:L(e,b);c.began=!0;c.completed=!0;c.seek(d.offset);d=q(d);d.began=!0;d.completed=!0;d.duration>b&&(c.duration=d.duration);c.children.push(d)});c.seek(0);c.reset();c.autoplay&&c.restart();return c};return c};q.random=function(a,c){return Math.floor(Math.random()*(c-a+1))+a};return q});

View File

@ -0,0 +1,450 @@
(function($) {
'use strict';
let _defaults = {
data: {}, // Autocomplete data set
limit: Infinity, // Limit of results the autocomplete shows
onAutocomplete: null, // Callback for when autocompleted
minLength: 1, // Min characters before autocomplete starts
sortFunction: function(a, b, inputString) {
// Sort function for sorting autocomplete results
return a.indexOf(inputString) - b.indexOf(inputString);
}
};
/**
* @class
*
*/
class Autocomplete extends Component {
/**
* Construct Autocomplete instance
* @constructor
* @param {Element} el
* @param {Object} options
*/
constructor(el, options) {
super(Autocomplete, el, options);
this.el.M_Autocomplete = this;
/**
* Options for the autocomplete
* @member Autocomplete#options
* @prop {Number} duration
* @prop {Number} dist
* @prop {number} shift
* @prop {number} padding
* @prop {Boolean} fullWidth
* @prop {Boolean} indicators
* @prop {Boolean} noWrap
* @prop {Function} onCycleTo
*/
this.options = $.extend({}, Autocomplete.defaults, options);
// Setup
this.isOpen = false;
this.count = 0;
this.activeIndex = -1;
this.oldVal;
this.$inputField = this.$el.closest('.input-field');
this.$active = $();
this._mousedown = false;
this._setupDropdown();
this._setupEventHandlers();
}
static get defaults() {
return _defaults;
}
static init(els, options) {
return super.init(this, els, options);
}
/**
* Get Instance
*/
static getInstance(el) {
let domElem = !!el.jquery ? el[0] : el;
return domElem.M_Autocomplete;
}
/**
* Teardown component
*/
destroy() {
this._removeEventHandlers();
this._removeDropdown();
this.el.M_Autocomplete = undefined;
}
/**
* Setup Event Handlers
*/
_setupEventHandlers() {
this._handleInputBlurBound = this._handleInputBlur.bind(this);
this._handleInputKeyupAndFocusBound = this._handleInputKeyupAndFocus.bind(this);
this._handleInputKeydownBound = this._handleInputKeydown.bind(this);
this._handleInputClickBound = this._handleInputClick.bind(this);
this._handleContainerMousedownAndTouchstartBound = this._handleContainerMousedownAndTouchstart.bind(
this
);
this._handleContainerMouseupAndTouchendBound = this._handleContainerMouseupAndTouchend.bind(
this
);
this.el.addEventListener('blur', this._handleInputBlurBound);
this.el.addEventListener('keyup', this._handleInputKeyupAndFocusBound);
this.el.addEventListener('focus', this._handleInputKeyupAndFocusBound);
this.el.addEventListener('keydown', this._handleInputKeydownBound);
this.el.addEventListener('click', this._handleInputClickBound);
this.container.addEventListener(
'mousedown',
this._handleContainerMousedownAndTouchstartBound
);
this.container.addEventListener('mouseup', this._handleContainerMouseupAndTouchendBound);
if (typeof window.ontouchstart !== 'undefined') {
this.container.addEventListener(
'touchstart',
this._handleContainerMousedownAndTouchstartBound
);
this.container.addEventListener('touchend', this._handleContainerMouseupAndTouchendBound);
}
}
/**
* Remove Event Handlers
*/
_removeEventHandlers() {
this.el.removeEventListener('blur', this._handleInputBlurBound);
this.el.removeEventListener('keyup', this._handleInputKeyupAndFocusBound);
this.el.removeEventListener('focus', this._handleInputKeyupAndFocusBound);
this.el.removeEventListener('keydown', this._handleInputKeydownBound);
this.el.removeEventListener('click', this._handleInputClickBound);
this.container.removeEventListener(
'mousedown',
this._handleContainerMousedownAndTouchstartBound
);
this.container.removeEventListener('mouseup', this._handleContainerMouseupAndTouchendBound);
if (typeof window.ontouchstart !== 'undefined') {
this.container.removeEventListener(
'touchstart',
this._handleContainerMousedownAndTouchstartBound
);
this.container.removeEventListener(
'touchend',
this._handleContainerMouseupAndTouchendBound
);
}
}
/**
* Setup dropdown
*/
_setupDropdown() {
this.container = document.createElement('ul');
this.container.id = `autocomplete-options-${M.guid()}`;
$(this.container).addClass('autocomplete-content dropdown-content');
this.$inputField.append(this.container);
this.el.setAttribute('data-target', this.container.id);
this.dropdown = M.Dropdown.init(this.el, {
autoFocus: false,
closeOnClick: false,
coverTrigger: false,
onItemClick: (itemEl) => {
this.selectOption($(itemEl));
}
});
// Sketchy removal of dropdown click handler
this.el.removeEventListener('click', this.dropdown._handleClickBound);
}
/**
* Remove dropdown
*/
_removeDropdown() {
this.container.parentNode.removeChild(this.container);
}
/**
* Handle Input Blur
*/
_handleInputBlur() {
if (!this._mousedown) {
this.close();
this._resetAutocomplete();
}
}
/**
* Handle Input Keyup and Focus
* @param {Event} e
*/
_handleInputKeyupAndFocus(e) {
if (e.type === 'keyup') {
Autocomplete._keydown = false;
}
this.count = 0;
let val = this.el.value.toLowerCase();
// Don't capture enter or arrow key usage.
if (e.keyCode === 13 || e.keyCode === 38 || e.keyCode === 40) {
return;
}
// Check if the input isn't empty
// Check if focus triggered by tab
if (this.oldVal !== val && (M.tabPressed || e.type !== 'focus')) {
this.open();
}
// Update oldVal
this.oldVal = val;
}
/**
* Handle Input Keydown
* @param {Event} e
*/
_handleInputKeydown(e) {
Autocomplete._keydown = true;
// Arrow keys and enter key usage
let keyCode = e.keyCode,
liElement,
numItems = $(this.container).children('li').length;
// select element on Enter
if (keyCode === M.keys.ENTER && this.activeIndex >= 0) {
liElement = $(this.container)
.children('li')
.eq(this.activeIndex);
if (liElement.length) {
this.selectOption(liElement);
e.preventDefault();
}
return;
}
// Capture up and down key
if (keyCode === M.keys.ARROW_UP || keyCode === M.keys.ARROW_DOWN) {
e.preventDefault();
if (keyCode === M.keys.ARROW_UP && this.activeIndex > 0) {
this.activeIndex--;
}
if (keyCode === M.keys.ARROW_DOWN && this.activeIndex < numItems - 1) {
this.activeIndex++;
}
this.$active.removeClass('active');
if (this.activeIndex >= 0) {
this.$active = $(this.container)
.children('li')
.eq(this.activeIndex);
this.$active.addClass('active');
}
}
}
/**
* Handle Input Click
* @param {Event} e
*/
_handleInputClick(e) {
this.open();
}
/**
* Handle Container Mousedown and Touchstart
* @param {Event} e
*/
_handleContainerMousedownAndTouchstart(e) {
this._mousedown = true;
}
/**
* Handle Container Mouseup and Touchend
* @param {Event} e
*/
_handleContainerMouseupAndTouchend(e) {
this._mousedown = false;
}
/**
* Highlight partial match
*/
_highlight(string, $el) {
let img = $el.find('img');
let matchStart = $el
.text()
.toLowerCase()
.indexOf('' + string.toLowerCase() + ''),
matchEnd = matchStart + string.length - 1,
beforeMatch = $el.text().slice(0, matchStart),
matchText = $el.text().slice(matchStart, matchEnd + 1),
afterMatch = $el.text().slice(matchEnd + 1);
$el.html(
`<span>${beforeMatch}<span class='highlight'>${matchText}</span>${afterMatch}</span>`
);
if (img.length) {
$el.prepend(img);
}
}
/**
* Reset current element position
*/
_resetCurrentElement() {
this.activeIndex = -1;
this.$active.removeClass('active');
}
/**
* Reset autocomplete elements
*/
_resetAutocomplete() {
$(this.container).empty();
this._resetCurrentElement();
this.oldVal = null;
this.isOpen = false;
this._mousedown = false;
}
/**
* Select autocomplete option
* @param {Element} el Autocomplete option list item element
*/
selectOption(el) {
let text = el.text().trim();
this.el.value = text;
this.$el.trigger('change');
this._resetAutocomplete();
this.close();
// Handle onAutocomplete callback.
if (typeof this.options.onAutocomplete === 'function') {
this.options.onAutocomplete.call(this, text);
}
}
/**
* Render dropdown content
* @param {Object} data data set
* @param {String} val current input value
*/
_renderDropdown(data, val) {
this._resetAutocomplete();
let matchingData = [];
// Gather all matching data
for (let key in data) {
if (data.hasOwnProperty(key) && key.toLowerCase().indexOf(val) !== -1) {
// Break if past limit
if (this.count >= this.options.limit) {
break;
}
let entry = {
data: data[key],
key: key
};
matchingData.push(entry);
this.count++;
}
}
// Sort
if (this.options.sortFunction) {
let sortFunctionBound = (a, b) => {
return this.options.sortFunction(
a.key.toLowerCase(),
b.key.toLowerCase(),
val.toLowerCase()
);
};
matchingData.sort(sortFunctionBound);
}
// Render
for (let i = 0; i < matchingData.length; i++) {
let entry = matchingData[i];
let $autocompleteOption = $('<li></li>');
if (!!entry.data) {
$autocompleteOption.append(
`<img src="${entry.data}" class="right circle"><span>${entry.key}</span>`
);
} else {
$autocompleteOption.append('<span>' + entry.key + '</span>');
}
$(this.container).append($autocompleteOption);
this._highlight(val, $autocompleteOption);
}
}
/**
* Open Autocomplete Dropdown
*/
open() {
let val = this.el.value.toLowerCase();
this._resetAutocomplete();
if (val.length >= this.options.minLength) {
this.isOpen = true;
this._renderDropdown(this.options.data, val);
}
// Open dropdown
if (!this.dropdown.isOpen) {
this.dropdown.open();
} else {
// Recalculate dropdown when its already open
this.dropdown.recalculateDimensions();
}
}
/**
* Close Autocomplete Dropdown
*/
close() {
this.dropdown.close();
}
/**
* Update Data
* @param {Object} data
*/
updateData(data) {
let val = this.el.value.toLowerCase();
this.options.data = data;
if (this.isOpen) {
this._renderDropdown(data, val);
}
}
}
/**
* @static
* @memberof Autocomplete
*/
Autocomplete._keydown = false;
M.Autocomplete = Autocomplete;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Autocomplete, 'autocomplete', 'M_Autocomplete');
}
})(cash);

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

354
resources/sass/materialize/js/buttons.js vendored Normal file
View File

@ -0,0 +1,354 @@
(function($, anim) {
'use strict';
let _defaults = {
direction: 'top',
hoverEnabled: true,
toolbarEnabled: false
};
$.fn.reverse = [].reverse;
/**
* @class
*
*/
class FloatingActionButton extends Component {
/**
* Construct FloatingActionButton instance
* @constructor
* @param {Element} el
* @param {Object} options
*/
constructor(el, options) {
super(FloatingActionButton, el, options);
this.el.M_FloatingActionButton = this;
/**
* Options for the fab
* @member FloatingActionButton#options
* @prop {Boolean} [direction] - Direction fab menu opens
* @prop {Boolean} [hoverEnabled=true] - Enable hover vs click
* @prop {Boolean} [toolbarEnabled=false] - Enable toolbar transition
*/
this.options = $.extend({}, FloatingActionButton.defaults, options);
this.isOpen = false;
this.$anchor = this.$el.children('a').first();
this.$menu = this.$el.children('ul').first();
this.$floatingBtns = this.$el.find('ul .btn-floating');
this.$floatingBtnsReverse = this.$el.find('ul .btn-floating').reverse();
this.offsetY = 0;
this.offsetX = 0;
this.$el.addClass(`direction-${this.options.direction}`);
if (this.options.direction === 'top') {
this.offsetY = 40;
} else if (this.options.direction === 'right') {
this.offsetX = -40;
} else if (this.options.direction === 'bottom') {
this.offsetY = -40;
} else {
this.offsetX = 40;
}
this._setupEventHandlers();
}
static get defaults() {
return _defaults;
}
static init(els, options) {
return super.init(this, els, options);
}
/**
* Get Instance
*/
static getInstance(el) {
let domElem = !!el.jquery ? el[0] : el;
return domElem.M_FloatingActionButton;
}
/**
* Teardown component
*/
destroy() {
this._removeEventHandlers();
this.el.M_FloatingActionButton = undefined;
}
/**
* Setup Event Handlers
*/
_setupEventHandlers() {
this._handleFABClickBound = this._handleFABClick.bind(this);
this._handleOpenBound = this.open.bind(this);
this._handleCloseBound = this.close.bind(this);
if (this.options.hoverEnabled && !this.options.toolbarEnabled) {
this.el.addEventListener('mouseenter', this._handleOpenBound);
this.el.addEventListener('mouseleave', this._handleCloseBound);
} else {
this.el.addEventListener('click', this._handleFABClickBound);
}
}
/**
* Remove Event Handlers
*/
_removeEventHandlers() {
if (this.options.hoverEnabled && !this.options.toolbarEnabled) {
this.el.removeEventListener('mouseenter', this._handleOpenBound);
this.el.removeEventListener('mouseleave', this._handleCloseBound);
} else {
this.el.removeEventListener('click', this._handleFABClickBound);
}
}
/**
* Handle FAB Click
*/
_handleFABClick() {
if (this.isOpen) {
this.close();
} else {
this.open();
}
}
/**
* Handle Document Click
* @param {Event} e
*/
_handleDocumentClick(e) {
if (!$(e.target).closest(this.$menu).length) {
this.close();
}
}
/**
* Open FAB
*/
open() {
if (this.isOpen) {
return;
}
if (this.options.toolbarEnabled) {
this._animateInToolbar();
} else {
this._animateInFAB();
}
this.isOpen = true;
}
/**
* Close FAB
*/
close() {
if (!this.isOpen) {
return;
}
if (this.options.toolbarEnabled) {
window.removeEventListener('scroll', this._handleCloseBound, true);
document.body.removeEventListener('click', this._handleDocumentClickBound, true);
this._animateOutToolbar();
} else {
this._animateOutFAB();
}
this.isOpen = false;
}
/**
* Classic FAB Menu open
*/
_animateInFAB() {
this.$el.addClass('active');
let time = 0;
this.$floatingBtnsReverse.each((el) => {
anim({
targets: el,
opacity: 1,
scale: [0.4, 1],
translateY: [this.offsetY, 0],
translateX: [this.offsetX, 0],
duration: 275,
delay: time,
easing: 'easeInOutQuad'
});
time += 40;
});
}
/**
* Classic FAB Menu close
*/
_animateOutFAB() {
this.$floatingBtnsReverse.each((el) => {
anim.remove(el);
anim({
targets: el,
opacity: 0,
scale: 0.4,
translateY: this.offsetY,
translateX: this.offsetX,
duration: 175,
easing: 'easeOutQuad',
complete: () => {
this.$el.removeClass('active');
}
});
});
}
/**
* Toolbar transition Menu open
*/
_animateInToolbar() {
let scaleFactor;
let windowWidth = window.innerWidth;
let windowHeight = window.innerHeight;
let btnRect = this.el.getBoundingClientRect();
let backdrop = $('<div class="fab-backdrop"></div>');
let fabColor = this.$anchor.css('background-color');
this.$anchor.append(backdrop);
this.offsetX = btnRect.left - windowWidth / 2 + btnRect.width / 2;
this.offsetY = windowHeight - btnRect.bottom;
scaleFactor = windowWidth / backdrop[0].clientWidth;
this.btnBottom = btnRect.bottom;
this.btnLeft = btnRect.left;
this.btnWidth = btnRect.width;
// Set initial state
this.$el.addClass('active');
this.$el.css({
'text-align': 'center',
width: '100%',
bottom: 0,
left: 0,
transform: 'translateX(' + this.offsetX + 'px)',
transition: 'none'
});
this.$anchor.css({
transform: 'translateY(' + -this.offsetY + 'px)',
transition: 'none'
});
backdrop.css({
'background-color': fabColor
});
setTimeout(() => {
this.$el.css({
transform: '',
transition:
'transform .2s cubic-bezier(0.550, 0.085, 0.680, 0.530), background-color 0s linear .2s'
});
this.$anchor.css({
overflow: 'visible',
transform: '',
transition: 'transform .2s'
});
setTimeout(() => {
this.$el.css({
overflow: 'hidden',
'background-color': fabColor
});
backdrop.css({
transform: 'scale(' + scaleFactor + ')',
transition: 'transform .2s cubic-bezier(0.550, 0.055, 0.675, 0.190)'
});
this.$menu
.children('li')
.children('a')
.css({
opacity: 1
});
// Scroll to close.
this._handleDocumentClickBound = this._handleDocumentClick.bind(this);
window.addEventListener('scroll', this._handleCloseBound, true);
document.body.addEventListener('click', this._handleDocumentClickBound, true);
}, 100);
}, 0);
}
/**
* Toolbar transition Menu close
*/
_animateOutToolbar() {
let windowWidth = window.innerWidth;
let windowHeight = window.innerHeight;
let backdrop = this.$el.find('.fab-backdrop');
let fabColor = this.$anchor.css('background-color');
this.offsetX = this.btnLeft - windowWidth / 2 + this.btnWidth / 2;
this.offsetY = windowHeight - this.btnBottom;
// Hide backdrop
this.$el.removeClass('active');
this.$el.css({
'background-color': 'transparent',
transition: 'none'
});
this.$anchor.css({
transition: 'none'
});
backdrop.css({
transform: 'scale(0)',
'background-color': fabColor
});
this.$menu
.children('li')
.children('a')
.css({
opacity: ''
});
setTimeout(() => {
backdrop.remove();
// Set initial state.
this.$el.css({
'text-align': '',
width: '',
bottom: '',
left: '',
overflow: '',
'background-color': '',
transform: 'translate3d(' + -this.offsetX + 'px,0,0)'
});
this.$anchor.css({
overflow: '',
transform: 'translate3d(0,' + this.offsetY + 'px,0)'
});
setTimeout(() => {
this.$el.css({
transform: 'translate3d(0,0,0)',
transition: 'transform .2s'
});
this.$anchor.css({
transform: 'translate3d(0,0,0)',
transition: 'transform .2s cubic-bezier(0.550, 0.055, 0.675, 0.190)'
});
}, 20);
}, 200);
}
}
M.FloatingActionButton = FloatingActionButton;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(
FloatingActionButton,
'floatingActionButton',
'M_FloatingActionButton'
);
}
})(cash, M.anime);

40
resources/sass/materialize/js/cards.js vendored Normal file
View File

@ -0,0 +1,40 @@
(function($, anim) {
$(document).on('click', '.card', function(e) {
if ($(this).children('.card-reveal').length) {
var $card = $(e.target).closest('.card');
if ($card.data('initialOverflow') === undefined) {
$card.data(
'initialOverflow',
$card.css('overflow') === undefined ? '' : $card.css('overflow')
);
}
let $cardReveal = $(this).find('.card-reveal');
if (
$(e.target).is($('.card-reveal .card-title')) ||
$(e.target).is($('.card-reveal .card-title i'))
) {
// Make Reveal animate down and display none
anim({
targets: $cardReveal[0],
translateY: 0,
duration: 225,
easing: 'easeInOutQuad',
complete: function(anim) {
let el = anim.animatables[0].target;
$(el).css({ display: 'none' });
$card.css('overflow', $card.data('initialOverflow'));
}
});
} else if ($(e.target).is($('.card .activator')) || $(e.target).is($('.card .activator i'))) {
$card.css('overflow', 'hidden');
$cardReveal.css({ display: 'block' });
anim({
targets: $cardReveal[0],
translateY: '-100%',
duration: 300,
easing: 'easeInOutQuad'
});
}
}
});
})(cash, M.anime);

View File

@ -0,0 +1,717 @@
(function($) {
'use strict';
let _defaults = {
duration: 200, // ms
dist: -100, // zoom scale TODO: make this more intuitive as an option
shift: 0, // spacing for center image
padding: 0, // Padding between non center items
numVisible: 5, // Number of visible items in carousel
fullWidth: false, // Change to full width styles
indicators: false, // Toggle indicators
noWrap: false, // Don't wrap around and cycle through items.
onCycleTo: null // Callback for when a new slide is cycled to.
};
/**
* @class
*
*/
class Carousel extends Component {
/**
* Construct Carousel instance
* @constructor
* @param {Element} el
* @param {Object} options
*/
constructor(el, options) {
super(Carousel, el, options);
this.el.M_Carousel = this;
/**
* Options for the carousel
* @member Carousel#options
* @prop {Number} duration
* @prop {Number} dist
* @prop {Number} shift
* @prop {Number} padding
* @prop {Number} numVisible
* @prop {Boolean} fullWidth
* @prop {Boolean} indicators
* @prop {Boolean} noWrap
* @prop {Function} onCycleTo
*/
this.options = $.extend({}, Carousel.defaults, options);
// Setup
this.hasMultipleSlides = this.$el.find('.carousel-item').length > 1;
this.showIndicators = this.options.indicators && this.hasMultipleSlides;
this.noWrap = this.options.noWrap || !this.hasMultipleSlides;
this.pressed = false;
this.dragged = false;
this.offset = this.target = 0;
this.images = [];
this.itemWidth = this.$el
.find('.carousel-item')
.first()
.innerWidth();
this.itemHeight = this.$el
.find('.carousel-item')
.first()
.innerHeight();
this.dim = this.itemWidth * 2 + this.options.padding || 1; // Make sure dim is non zero for divisions.
this._autoScrollBound = this._autoScroll.bind(this);
this._trackBound = this._track.bind(this);
// Full Width carousel setup
if (this.options.fullWidth) {
this.options.dist = 0;
this._setCarouselHeight();
// Offset fixed items when indicators.
if (this.showIndicators) {
this.$el.find('.carousel-fixed-item').addClass('with-indicators');
}
}
// Iterate through slides
this.$indicators = $('<ul class="indicators"></ul>');
this.$el.find('.carousel-item').each((el, i) => {
this.images.push(el);
if (this.showIndicators) {
let $indicator = $('<li class="indicator-item"></li>');
// Add active to first by default.
if (i === 0) {
$indicator[0].classList.add('active');
}
this.$indicators.append($indicator);
}
});
if (this.showIndicators) {
this.$el.append(this.$indicators);
}
this.count = this.images.length;
// Cap numVisible at count
this.options.numVisible = Math.min(this.count, this.options.numVisible);
// Setup cross browser string
this.xform = 'transform';
['webkit', 'Moz', 'O', 'ms'].every((prefix) => {
var e = prefix + 'Transform';
if (typeof document.body.style[e] !== 'undefined') {
this.xform = e;
return false;
}
return true;
});
this._setupEventHandlers();
this._scroll(this.offset);
}
static get defaults() {
return _defaults;
}
static init(els, options) {
return super.init(this, els, options);
}
/**
* Get Instance
*/
static getInstance(el) {
let domElem = !!el.jquery ? el[0] : el;
return domElem.M_Carousel;
}
/**
* Teardown component
*/
destroy() {
this._removeEventHandlers();
this.el.M_Carousel = undefined;
}
/**
* Setup Event Handlers
*/
_setupEventHandlers() {
this._handleCarouselTapBound = this._handleCarouselTap.bind(this);
this._handleCarouselDragBound = this._handleCarouselDrag.bind(this);
this._handleCarouselReleaseBound = this._handleCarouselRelease.bind(this);
this._handleCarouselClickBound = this._handleCarouselClick.bind(this);
if (typeof window.ontouchstart !== 'undefined') {
this.el.addEventListener('touchstart', this._handleCarouselTapBound);
this.el.addEventListener('touchmove', this._handleCarouselDragBound);
this.el.addEventListener('touchend', this._handleCarouselReleaseBound);
}
this.el.addEventListener('mousedown', this._handleCarouselTapBound);
this.el.addEventListener('mousemove', this._handleCarouselDragBound);
this.el.addEventListener('mouseup', this._handleCarouselReleaseBound);
this.el.addEventListener('mouseleave', this._handleCarouselReleaseBound);
this.el.addEventListener('click', this._handleCarouselClickBound);
if (this.showIndicators && this.$indicators) {
this._handleIndicatorClickBound = this._handleIndicatorClick.bind(this);
this.$indicators.find('.indicator-item').each((el, i) => {
el.addEventListener('click', this._handleIndicatorClickBound);
});
}
// Resize
let throttledResize = M.throttle(this._handleResize, 200);
this._handleThrottledResizeBound = throttledResize.bind(this);
window.addEventListener('resize', this._handleThrottledResizeBound);
}
/**
* Remove Event Handlers
*/
_removeEventHandlers() {
if (typeof window.ontouchstart !== 'undefined') {
this.el.removeEventListener('touchstart', this._handleCarouselTapBound);
this.el.removeEventListener('touchmove', this._handleCarouselDragBound);
this.el.removeEventListener('touchend', this._handleCarouselReleaseBound);
}
this.el.removeEventListener('mousedown', this._handleCarouselTapBound);
this.el.removeEventListener('mousemove', this._handleCarouselDragBound);
this.el.removeEventListener('mouseup', this._handleCarouselReleaseBound);
this.el.removeEventListener('mouseleave', this._handleCarouselReleaseBound);
this.el.removeEventListener('click', this._handleCarouselClickBound);
if (this.showIndicators && this.$indicators) {
this.$indicators.find('.indicator-item').each((el, i) => {
el.removeEventListener('click', this._handleIndicatorClickBound);
});
}
window.removeEventListener('resize', this._handleThrottledResizeBound);
}
/**
* Handle Carousel Tap
* @param {Event} e
*/
_handleCarouselTap(e) {
// Fixes firefox draggable image bug
if (e.type === 'mousedown' && $(e.target).is('img')) {
e.preventDefault();
}
this.pressed = true;
this.dragged = false;
this.verticalDragged = false;
this.reference = this._xpos(e);
this.referenceY = this._ypos(e);
this.velocity = this.amplitude = 0;
this.frame = this.offset;
this.timestamp = Date.now();
clearInterval(this.ticker);
this.ticker = setInterval(this._trackBound, 100);
}
/**
* Handle Carousel Drag
* @param {Event} e
*/
_handleCarouselDrag(e) {
let x, y, delta, deltaY;
if (this.pressed) {
x = this._xpos(e);
y = this._ypos(e);
delta = this.reference - x;
deltaY = Math.abs(this.referenceY - y);
if (deltaY < 30 && !this.verticalDragged) {
// If vertical scrolling don't allow dragging.
if (delta > 2 || delta < -2) {
this.dragged = true;
this.reference = x;
this._scroll(this.offset + delta);
}
} else if (this.dragged) {
// If dragging don't allow vertical scroll.
e.preventDefault();
e.stopPropagation();
return false;
} else {
// Vertical scrolling.
this.verticalDragged = true;
}
}
if (this.dragged) {
// If dragging don't allow vertical scroll.
e.preventDefault();
e.stopPropagation();
return false;
}
}
/**
* Handle Carousel Release
* @param {Event} e
*/
_handleCarouselRelease(e) {
if (this.pressed) {
this.pressed = false;
} else {
return;
}
clearInterval(this.ticker);
this.target = this.offset;
if (this.velocity > 10 || this.velocity < -10) {
this.amplitude = 0.9 * this.velocity;
this.target = this.offset + this.amplitude;
}
this.target = Math.round(this.target / this.dim) * this.dim;
// No wrap of items.
if (this.noWrap) {
if (this.target >= this.dim * (this.count - 1)) {
this.target = this.dim * (this.count - 1);
} else if (this.target < 0) {
this.target = 0;
}
}
this.amplitude = this.target - this.offset;
this.timestamp = Date.now();
requestAnimationFrame(this._autoScrollBound);
if (this.dragged) {
e.preventDefault();
e.stopPropagation();
}
return false;
}
/**
* Handle Carousel CLick
* @param {Event} e
*/
_handleCarouselClick(e) {
// Disable clicks if carousel was dragged.
if (this.dragged) {
e.preventDefault();
e.stopPropagation();
return false;
} else if (!this.options.fullWidth) {
let clickedIndex = $(e.target)
.closest('.carousel-item')
.index();
let diff = this._wrap(this.center) - clickedIndex;
// Disable clicks if carousel was shifted by click
if (diff !== 0) {
e.preventDefault();
e.stopPropagation();
}
this._cycleTo(clickedIndex);
}
}
/**
* Handle Indicator CLick
* @param {Event} e
*/
_handleIndicatorClick(e) {
e.stopPropagation();
let indicator = $(e.target).closest('.indicator-item');
if (indicator.length) {
this._cycleTo(indicator.index());
}
}
/**
* Handle Throttle Resize
* @param {Event} e
*/
_handleResize(e) {
if (this.options.fullWidth) {
this.itemWidth = this.$el
.find('.carousel-item')
.first()
.innerWidth();
this.imageHeight = this.$el.find('.carousel-item.active').height();
this.dim = this.itemWidth * 2 + this.options.padding;
this.offset = this.center * 2 * this.itemWidth;
this.target = this.offset;
this._setCarouselHeight(true);
} else {
this._scroll();
}
}
/**
* Set carousel height based on first slide
* @param {Booleam} imageOnly - true for image slides
*/
_setCarouselHeight(imageOnly) {
let firstSlide = this.$el.find('.carousel-item.active').length
? this.$el.find('.carousel-item.active').first()
: this.$el.find('.carousel-item').first();
let firstImage = firstSlide.find('img').first();
if (firstImage.length) {
if (firstImage[0].complete) {
// If image won't trigger the load event
let imageHeight = firstImage.height();
if (imageHeight > 0) {
this.$el.css('height', imageHeight + 'px');
} else {
// If image still has no height, use the natural dimensions to calculate
let naturalWidth = firstImage[0].naturalWidth;
let naturalHeight = firstImage[0].naturalHeight;
let adjustedHeight = this.$el.width() / naturalWidth * naturalHeight;
this.$el.css('height', adjustedHeight + 'px');
}
} else {
// Get height when image is loaded normally
firstImage.one('load', (el, i) => {
this.$el.css('height', el.offsetHeight + 'px');
});
}
} else if (!imageOnly) {
let slideHeight = firstSlide.height();
this.$el.css('height', slideHeight + 'px');
}
}
/**
* Get x position from event
* @param {Event} e
*/
_xpos(e) {
// touch event
if (e.targetTouches && e.targetTouches.length >= 1) {
return e.targetTouches[0].clientX;
}
// mouse event
return e.clientX;
}
/**
* Get y position from event
* @param {Event} e
*/
_ypos(e) {
// touch event
if (e.targetTouches && e.targetTouches.length >= 1) {
return e.targetTouches[0].clientY;
}
// mouse event
return e.clientY;
}
/**
* Wrap index
* @param {Number} x
*/
_wrap(x) {
return x >= this.count ? x % this.count : x < 0 ? this._wrap(this.count + x % this.count) : x;
}
/**
* Tracks scrolling information
*/
_track() {
let now, elapsed, delta, v;
now = Date.now();
elapsed = now - this.timestamp;
this.timestamp = now;
delta = this.offset - this.frame;
this.frame = this.offset;
v = 1000 * delta / (1 + elapsed);
this.velocity = 0.8 * v + 0.2 * this.velocity;
}
/**
* Auto scrolls to nearest carousel item.
*/
_autoScroll() {
let elapsed, delta;
if (this.amplitude) {
elapsed = Date.now() - this.timestamp;
delta = this.amplitude * Math.exp(-elapsed / this.options.duration);
if (delta > 2 || delta < -2) {
this._scroll(this.target - delta);
requestAnimationFrame(this._autoScrollBound);
} else {
this._scroll(this.target);
}
}
}
/**
* Scroll to target
* @param {Number} x
*/
_scroll(x) {
// Track scrolling state
if (!this.$el.hasClass('scrolling')) {
this.el.classList.add('scrolling');
}
if (this.scrollingTimeout != null) {
window.clearTimeout(this.scrollingTimeout);
}
this.scrollingTimeout = window.setTimeout(() => {
this.$el.removeClass('scrolling');
}, this.options.duration);
// Start actual scroll
let i,
half,
delta,
dir,
tween,
el,
alignment,
zTranslation,
tweenedOpacity,
centerTweenedOpacity;
let lastCenter = this.center;
let numVisibleOffset = 1 / this.options.numVisible;
this.offset = typeof x === 'number' ? x : this.offset;
this.center = Math.floor((this.offset + this.dim / 2) / this.dim);
delta = this.offset - this.center * this.dim;
dir = delta < 0 ? 1 : -1;
tween = -dir * delta * 2 / this.dim;
half = this.count >> 1;
if (this.options.fullWidth) {
alignment = 'translateX(0)';
centerTweenedOpacity = 1;
} else {
alignment = 'translateX(' + (this.el.clientWidth - this.itemWidth) / 2 + 'px) ';
alignment += 'translateY(' + (this.el.clientHeight - this.itemHeight) / 2 + 'px)';
centerTweenedOpacity = 1 - numVisibleOffset * tween;
}
// Set indicator active
if (this.showIndicators) {
let diff = this.center % this.count;
let activeIndicator = this.$indicators.find('.indicator-item.active');
if (activeIndicator.index() !== diff) {
activeIndicator.removeClass('active');
this.$indicators
.find('.indicator-item')
.eq(diff)[0]
.classList.add('active');
}
}
// center
// Don't show wrapped items.
if (!this.noWrap || (this.center >= 0 && this.center < this.count)) {
el = this.images[this._wrap(this.center)];
// Add active class to center item.
if (!$(el).hasClass('active')) {
this.$el.find('.carousel-item').removeClass('active');
el.classList.add('active');
}
let transformString = `${alignment} translateX(${-delta / 2}px) translateX(${dir *
this.options.shift *
tween *
i}px) translateZ(${this.options.dist * tween}px)`;
this._updateItemStyle(el, centerTweenedOpacity, 0, transformString);
}
for (i = 1; i <= half; ++i) {
// right side
if (this.options.fullWidth) {
zTranslation = this.options.dist;
tweenedOpacity = i === half && delta < 0 ? 1 - tween : 1;
} else {
zTranslation = this.options.dist * (i * 2 + tween * dir);
tweenedOpacity = 1 - numVisibleOffset * (i * 2 + tween * dir);
}
// Don't show wrapped items.
if (!this.noWrap || this.center + i < this.count) {
el = this.images[this._wrap(this.center + i)];
let transformString = `${alignment} translateX(${this.options.shift +
(this.dim * i - delta) / 2}px) translateZ(${zTranslation}px)`;
this._updateItemStyle(el, tweenedOpacity, -i, transformString);
}
// left side
if (this.options.fullWidth) {
zTranslation = this.options.dist;
tweenedOpacity = i === half && delta > 0 ? 1 - tween : 1;
} else {
zTranslation = this.options.dist * (i * 2 - tween * dir);
tweenedOpacity = 1 - numVisibleOffset * (i * 2 - tween * dir);
}
// Don't show wrapped items.
if (!this.noWrap || this.center - i >= 0) {
el = this.images[this._wrap(this.center - i)];
let transformString = `${alignment} translateX(${-this.options.shift +
(-this.dim * i - delta) / 2}px) translateZ(${zTranslation}px)`;
this._updateItemStyle(el, tweenedOpacity, -i, transformString);
}
}
// center
// Don't show wrapped items.
if (!this.noWrap || (this.center >= 0 && this.center < this.count)) {
el = this.images[this._wrap(this.center)];
let transformString = `${alignment} translateX(${-delta / 2}px) translateX(${dir *
this.options.shift *
tween}px) translateZ(${this.options.dist * tween}px)`;
this._updateItemStyle(el, centerTweenedOpacity, 0, transformString);
}
// onCycleTo callback
let $currItem = this.$el.find('.carousel-item').eq(this._wrap(this.center));
if (lastCenter !== this.center && typeof this.options.onCycleTo === 'function') {
this.options.onCycleTo.call(this, $currItem[0], this.dragged);
}
// One time callback
if (typeof this.oneTimeCallback === 'function') {
this.oneTimeCallback.call(this, $currItem[0], this.dragged);
this.oneTimeCallback = null;
}
}
/**
* Cycle to target
* @param {Element} el
* @param {Number} opacity
* @param {Number} zIndex
* @param {String} transform
*/
_updateItemStyle(el, opacity, zIndex, transform) {
el.style[this.xform] = transform;
el.style.zIndex = zIndex;
el.style.opacity = opacity;
el.style.visibility = 'visible';
}
/**
* Cycle to target
* @param {Number} n
* @param {Function} callback
*/
_cycleTo(n, callback) {
let diff = this.center % this.count - n;
// Account for wraparound.
if (!this.noWrap) {
if (diff < 0) {
if (Math.abs(diff + this.count) < Math.abs(diff)) {
diff += this.count;
}
} else if (diff > 0) {
if (Math.abs(diff - this.count) < diff) {
diff -= this.count;
}
}
}
this.target = this.dim * Math.round(this.offset / this.dim);
// Next
if (diff < 0) {
this.target += this.dim * Math.abs(diff);
// Prev
} else if (diff > 0) {
this.target -= this.dim * diff;
}
// Set one time callback
if (typeof callback === 'function') {
this.oneTimeCallback = callback;
}
// Scroll
if (this.offset !== this.target) {
this.amplitude = this.target - this.offset;
this.timestamp = Date.now();
requestAnimationFrame(this._autoScrollBound);
}
}
/**
* Cycle to next item
* @param {Number} [n]
*/
next(n) {
if (n === undefined || isNaN(n)) {
n = 1;
}
let index = this.center + n;
if (index >= this.count || index < 0) {
if (this.noWrap) {
return;
}
index = this._wrap(index);
}
this._cycleTo(index);
}
/**
* Cycle to previous item
* @param {Number} [n]
*/
prev(n) {
if (n === undefined || isNaN(n)) {
n = 1;
}
let index = this.center - n;
if (index >= this.count || index < 0) {
if (this.noWrap) {
return;
}
index = this._wrap(index);
}
this._cycleTo(index);
}
/**
* Cycle to nth item
* @param {Number} [n]
* @param {Function} callback
*/
set(n, callback) {
if (n === undefined || isNaN(n)) {
n = 0;
}
if (n > this.count || n < 0) {
if (this.noWrap) {
return;
}
n = this._wrap(n);
}
this._cycleTo(n, callback);
}
}
M.Carousel = Carousel;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Carousel, 'carousel', 'M_Carousel');
}
})(cash);

960
resources/sass/materialize/js/cash.js vendored Normal file
View File

@ -0,0 +1,960 @@
/*! cash-dom 1.3.5, https://github.com/kenwheeler/cash @license MIT */
(function (factory) {
window.cash = factory();
})(function () {
var doc = document, win = window, ArrayProto = Array.prototype, slice = ArrayProto.slice, filter = ArrayProto.filter, push = ArrayProto.push;
var noop = function () {}, isFunction = function (item) {
// @see https://crbug.com/568448
return typeof item === typeof noop && item.call;
}, isString = function (item) {
return typeof item === typeof "";
};
var idMatch = /^#[\w-]*$/, classMatch = /^\.[\w-]*$/, htmlMatch = /<.+>/, singlet = /^\w+$/;
function find(selector, context) {
context = context || doc;
var elems = (classMatch.test(selector) ? context.getElementsByClassName(selector.slice(1)) : singlet.test(selector) ? context.getElementsByTagName(selector) : context.querySelectorAll(selector));
return elems;
}
var frag;
function parseHTML(str) {
if (!frag) {
frag = doc.implementation.createHTMLDocument(null);
var base = frag.createElement("base");
base.href = doc.location.href;
frag.head.appendChild(base);
}
frag.body.innerHTML = str;
return frag.body.childNodes;
}
function onReady(fn) {
if (doc.readyState !== "loading") {
fn();
} else {
doc.addEventListener("DOMContentLoaded", fn);
}
}
function Init(selector, context) {
if (!selector) {
return this;
}
// If already a cash collection, don't do any further processing
if (selector.cash && selector !== win) {
return selector;
}
var elems = selector, i = 0, length;
if (isString(selector)) {
elems = (idMatch.test(selector) ?
// If an ID use the faster getElementById check
doc.getElementById(selector.slice(1)) : htmlMatch.test(selector) ?
// If HTML, parse it into real elements
parseHTML(selector) :
// else use `find`
find(selector, context));
// If function, use as shortcut for DOM ready
} else if (isFunction(selector)) {
onReady(selector);return this;
}
if (!elems) {
return this;
}
// If a single DOM element is passed in or received via ID, return the single element
if (elems.nodeType || elems === win) {
this[0] = elems;
this.length = 1;
} else {
// Treat like an array and loop through each item.
length = this.length = elems.length;
for (; i < length; i++) {
this[i] = elems[i];
}
}
return this;
}
function cash(selector, context) {
return new Init(selector, context);
}
var fn = cash.fn = cash.prototype = Init.prototype = { // jshint ignore:line
cash: true,
length: 0,
push: push,
splice: ArrayProto.splice,
map: ArrayProto.map,
init: Init
};
Object.defineProperty(fn, "constructor", { value: cash });
cash.parseHTML = parseHTML;
cash.noop = noop;
cash.isFunction = isFunction;
cash.isString = isString;
cash.extend = fn.extend = function (target) {
target = target || {};
var args = slice.call(arguments), length = args.length, i = 1;
if (args.length === 1) {
target = this;
i = 0;
}
for (; i < length; i++) {
if (!args[i]) {
continue;
}
for (var key in args[i]) {
if (args[i].hasOwnProperty(key)) {
target[key] = args[i][key];
}
}
}
return target;
};
function each(collection, callback) {
var l = collection.length, i = 0;
for (; i < l; i++) {
if (callback.call(collection[i], collection[i], i, collection) === false) {
break;
}
}
}
function matches(el, selector) {
var m = el && (el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector || el.oMatchesSelector);
return !!m && m.call(el, selector);
}
function getCompareFunction(selector) {
return (
/* Use browser's `matches` function if string */
isString(selector) ? matches :
/* Match a cash element */
selector.cash ? function (el) {
return selector.is(el);
} :
/* Direct comparison */
function (el, selector) {
return el === selector;
});
}
function unique(collection) {
return cash(slice.call(collection).filter(function (item, index, self) {
return self.indexOf(item) === index;
}));
}
cash.extend({
merge: function (first, second) {
var len = +second.length, i = first.length, j = 0;
for (; j < len; i++, j++) {
first[i] = second[j];
}
first.length = i;
return first;
},
each: each,
matches: matches,
unique: unique,
isArray: Array.isArray,
isNumeric: function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
});
var uid = cash.uid = "_cash" + Date.now();
function getDataCache(node) {
return (node[uid] = node[uid] || {});
}
function setData(node, key, value) {
return (getDataCache(node)[key] = value);
}
function getData(node, key) {
var c = getDataCache(node);
if (c[key] === undefined) {
c[key] = node.dataset ? node.dataset[key] : cash(node).attr("data-" + key);
}
return c[key];
}
function removeData(node, key) {
var c = getDataCache(node);
if (c) {
delete c[key];
} else if (node.dataset) {
delete node.dataset[key];
} else {
cash(node).removeAttr("data-" + name);
}
}
fn.extend({
data: function (name, value) {
if (isString(name)) {
return (value === undefined ? getData(this[0], name) : this.each(function (v) {
return setData(v, name, value);
}));
}
for (var key in name) {
this.data(key, name[key]);
}
return this;
},
removeData: function (key) {
return this.each(function (v) {
return removeData(v, key);
});
}
});
var notWhiteMatch = /\S+/g;
function getClasses(c) {
return isString(c) && c.match(notWhiteMatch);
}
function hasClass(v, c) {
return (v.classList ? v.classList.contains(c) : new RegExp("(^| )" + c + "( |$)", "gi").test(v.className));
}
function addClass(v, c, spacedName) {
if (v.classList) {
v.classList.add(c);
} else if (spacedName.indexOf(" " + c + " ")) {
v.className += " " + c;
}
}
function removeClass(v, c) {
if (v.classList) {
v.classList.remove(c);
} else {
v.className = v.className.replace(c, "");
}
}
fn.extend({
addClass: function (c) {
var classes = getClasses(c);
return (classes ? this.each(function (v) {
var spacedName = " " + v.className + " ";
each(classes, function (c) {
addClass(v, c, spacedName);
});
}) : this);
},
attr: function (name, value) {
if (!name) {
return undefined;
}
if (isString(name)) {
if (value === undefined) {
return this[0] ? this[0].getAttribute ? this[0].getAttribute(name) : this[0][name] : undefined;
}
return this.each(function (v) {
if (v.setAttribute) {
v.setAttribute(name, value);
} else {
v[name] = value;
}
});
}
for (var key in name) {
this.attr(key, name[key]);
}
return this;
},
hasClass: function (c) {
var check = false, classes = getClasses(c);
if (classes && classes.length) {
this.each(function (v) {
check = hasClass(v, classes[0]);
return !check;
});
}
return check;
},
prop: function (name, value) {
if (isString(name)) {
return (value === undefined ? this[0][name] : this.each(function (v) {
v[name] = value;
}));
}
for (var key in name) {
this.prop(key, name[key]);
}
return this;
},
removeAttr: function (name) {
return this.each(function (v) {
if (v.removeAttribute) {
v.removeAttribute(name);
} else {
delete v[name];
}
});
},
removeClass: function (c) {
if (!arguments.length) {
return this.attr("class", "");
}
var classes = getClasses(c);
return (classes ? this.each(function (v) {
each(classes, function (c) {
removeClass(v, c);
});
}) : this);
},
removeProp: function (name) {
return this.each(function (v) {
delete v[name];
});
},
toggleClass: function (c, state) {
if (state !== undefined) {
return this[state ? "addClass" : "removeClass"](c);
}
var classes = getClasses(c);
return (classes ? this.each(function (v) {
var spacedName = " " + v.className + " ";
each(classes, function (c) {
if (hasClass(v, c)) {
removeClass(v, c);
} else {
addClass(v, c, spacedName);
}
});
}) : this);
} });
fn.extend({
add: function (selector, context) {
return unique(cash.merge(this, cash(selector, context)));
},
each: function (callback) {
each(this, callback);
return this;
},
eq: function (index) {
return cash(this.get(index));
},
filter: function (selector) {
if (!selector) {
return this;
}
var comparator = (isFunction(selector) ? selector : getCompareFunction(selector));
return cash(filter.call(this, function (e) {
return comparator(e, selector);
}));
},
first: function () {
return this.eq(0);
},
get: function (index) {
if (index === undefined) {
return slice.call(this);
}
return (index < 0 ? this[index + this.length] : this[index]);
},
index: function (elem) {
var child = elem ? cash(elem)[0] : this[0], collection = elem ? this : cash(child).parent().children();
return slice.call(collection).indexOf(child);
},
last: function () {
return this.eq(-1);
}
});
var camelCase = (function () {
var camelRegex = /(?:^\w|[A-Z]|\b\w)/g, whiteSpace = /[\s-_]+/g;
return function (str) {
return str.replace(camelRegex, function (letter, index) {
return letter[index === 0 ? "toLowerCase" : "toUpperCase"]();
}).replace(whiteSpace, "");
};
}());
var getPrefixedProp = (function () {
var cache = {}, doc = document, div = doc.createElement("div"), style = div.style;
return function (prop) {
prop = camelCase(prop);
if (cache[prop]) {
return cache[prop];
}
var ucProp = prop.charAt(0).toUpperCase() + prop.slice(1), prefixes = ["webkit", "moz", "ms", "o"], props = (prop + " " + (prefixes).join(ucProp + " ") + ucProp).split(" ");
each(props, function (p) {
if (p in style) {
cache[p] = prop = cache[prop] = p;
return false;
}
});
return cache[prop];
};
}());
cash.prefixedProp = getPrefixedProp;
cash.camelCase = camelCase;
fn.extend({
css: function (prop, value) {
if (isString(prop)) {
prop = getPrefixedProp(prop);
return (arguments.length > 1 ? this.each(function (v) {
return v.style[prop] = value;
}) : win.getComputedStyle(this[0])[prop]);
}
for (var key in prop) {
this.css(key, prop[key]);
}
return this;
}
});
function compute(el, prop) {
return parseInt(win.getComputedStyle(el[0], null)[prop], 10) || 0;
}
each(["Width", "Height"], function (v) {
var lower = v.toLowerCase();
fn[lower] = function () {
return this[0].getBoundingClientRect()[lower];
};
fn["inner" + v] = function () {
return this[0]["client" + v];
};
fn["outer" + v] = function (margins) {
return this[0]["offset" + v] + (margins ? compute(this, "margin" + (v === "Width" ? "Left" : "Top")) + compute(this, "margin" + (v === "Width" ? "Right" : "Bottom")) : 0);
};
});
function registerEvent(node, eventName, callback) {
var eventCache = getData(node, "_cashEvents") || setData(node, "_cashEvents", {});
eventCache[eventName] = eventCache[eventName] || [];
eventCache[eventName].push(callback);
node.addEventListener(eventName, callback);
}
function removeEvent(node, eventName, callback) {
var events = getData(node, "_cashEvents"), eventCache = (events && events[eventName]), index;
if (!eventCache) {
return;
}
if (callback) {
node.removeEventListener(eventName, callback);
index = eventCache.indexOf(callback);
if (index >= 0) {
eventCache.splice(index, 1);
}
} else {
each(eventCache, function (event) {
node.removeEventListener(eventName, event);
});
eventCache = [];
}
}
fn.extend({
off: function (eventName, callback) {
return this.each(function (v) {
return removeEvent(v, eventName, callback);
});
},
on: function (eventName, delegate, callback, runOnce) {
// jshint ignore:line
var originalCallback;
if (!isString(eventName)) {
for (var key in eventName) {
this.on(key, delegate, eventName[key]);
}
return this;
}
if (isFunction(delegate)) {
callback = delegate;
delegate = null;
}
if (eventName === "ready") {
onReady(callback);
return this;
}
if (delegate) {
originalCallback = callback;
callback = function (e) {
var t = e.target;
while (!matches(t, delegate)) {
if (t === this || t === null) {
return (t = false);
}
t = t.parentNode;
}
if (t) {
originalCallback.call(t, e);
}
};
}
return this.each(function (v) {
var finalCallback = callback;
if (runOnce) {
finalCallback = function () {
callback.apply(this, arguments);
removeEvent(v, eventName, finalCallback);
};
}
registerEvent(v, eventName, finalCallback);
});
},
one: function (eventName, delegate, callback) {
return this.on(eventName, delegate, callback, true);
},
ready: onReady,
/**
* Modified
* Triggers browser event
* @param String eventName
* @param Object data - Add properties to event object
*/
trigger: function (eventName, data) {
if (document.createEvent) {
let evt = document.createEvent('HTMLEvents');
evt.initEvent(eventName, true, false);
evt = this.extend(evt, data);
return this.each(function (v) {
return v.dispatchEvent(evt);
});
}
}
});
function encode(name, value) {
return "&" + encodeURIComponent(name) + "=" + encodeURIComponent(value).replace(/%20/g, "+");
}
function getSelectMultiple_(el) {
var values = [];
each(el.options, function (o) {
if (o.selected) {
values.push(o.value);
}
});
return values.length ? values : null;
}
function getSelectSingle_(el) {
var selectedIndex = el.selectedIndex;
return selectedIndex >= 0 ? el.options[selectedIndex].value : null;
}
function getValue(el) {
var type = el.type;
if (!type) {
return null;
}
switch (type.toLowerCase()) {
case "select-one":
return getSelectSingle_(el);
case "select-multiple":
return getSelectMultiple_(el);
case "radio":
return (el.checked) ? el.value : null;
case "checkbox":
return (el.checked) ? el.value : null;
default:
return el.value ? el.value : null;
}
}
fn.extend({
serialize: function () {
var query = "";
each(this[0].elements || this, function (el) {
if (el.disabled || el.tagName === "FIELDSET") {
return;
}
var name = el.name;
switch (el.type.toLowerCase()) {
case "file":
case "reset":
case "submit":
case "button":
break;
case "select-multiple":
var values = getValue(el);
if (values !== null) {
each(values, function (value) {
query += encode(name, value);
});
}
break;
default:
var value = getValue(el);
if (value !== null) {
query += encode(name, value);
}
}
});
return query.substr(1);
},
val: function (value) {
if (value === undefined) {
return getValue(this[0]);
}
return this.each(function (v) {
return v.value = value;
});
}
});
function insertElement(el, child, prepend) {
if (prepend) {
var first = el.childNodes[0];
el.insertBefore(child, first);
} else {
el.appendChild(child);
}
}
function insertContent(parent, child, prepend) {
var str = isString(child);
if (!str && child.length) {
each(child, function (v) {
return insertContent(parent, v, prepend);
});
return;
}
each(parent, str ? function (v) {
return v.insertAdjacentHTML(prepend ? "afterbegin" : "beforeend", child);
} : function (v, i) {
return insertElement(v, (i === 0 ? child : child.cloneNode(true)), prepend);
});
}
fn.extend({
after: function (selector) {
cash(selector).insertAfter(this);
return this;
},
append: function (content) {
insertContent(this, content);
return this;
},
appendTo: function (parent) {
insertContent(cash(parent), this);
return this;
},
before: function (selector) {
cash(selector).insertBefore(this);
return this;
},
clone: function () {
return cash(this.map(function (v) {
return v.cloneNode(true);
}));
},
empty: function () {
this.html("");
return this;
},
html: function (content) {
if (content === undefined) {
return this[0].innerHTML;
}
var source = (content.nodeType ? content[0].outerHTML : content);
return this.each(function (v) {
return v.innerHTML = source;
});
},
insertAfter: function (selector) {
var _this = this;
cash(selector).each(function (el, i) {
var parent = el.parentNode, sibling = el.nextSibling;
_this.each(function (v) {
parent.insertBefore((i === 0 ? v : v.cloneNode(true)), sibling);
});
});
return this;
},
insertBefore: function (selector) {
var _this2 = this;
cash(selector).each(function (el, i) {
var parent = el.parentNode;
_this2.each(function (v) {
parent.insertBefore((i === 0 ? v : v.cloneNode(true)), el);
});
});
return this;
},
prepend: function (content) {
insertContent(this, content, true);
return this;
},
prependTo: function (parent) {
insertContent(cash(parent), this, true);
return this;
},
remove: function () {
return this.each(function (v) {
if (!!v.parentNode) {
return v.parentNode.removeChild(v);
}
});
},
text: function (content) {
if (content === undefined) {
return this[0].textContent;
}
return this.each(function (v) {
return v.textContent = content;
});
}
});
var docEl = doc.documentElement;
fn.extend({
position: function () {
var el = this[0];
return {
left: el.offsetLeft,
top: el.offsetTop
};
},
offset: function () {
var rect = this[0].getBoundingClientRect();
return {
top: rect.top + win.pageYOffset - docEl.clientTop,
left: rect.left + win.pageXOffset - docEl.clientLeft
};
},
offsetParent: function () {
return cash(this[0].offsetParent);
}
});
fn.extend({
children: function (selector) {
var elems = [];
this.each(function (el) {
push.apply(elems, el.children);
});
elems = unique(elems);
return (!selector ? elems : elems.filter(function (v) {
return matches(v, selector);
}));
},
closest: function (selector) {
if (!selector || this.length < 1) {
return cash();
}
if (this.is(selector)) {
return this.filter(selector);
}
return this.parent().closest(selector);
},
is: function (selector) {
if (!selector) {
return false;
}
var match = false, comparator = getCompareFunction(selector);
this.each(function (el) {
match = comparator(el, selector);
return !match;
});
return match;
},
find: function (selector) {
if (!selector || selector.nodeType) {
return cash(selector && this.has(selector).length ? selector : null);
}
var elems = [];
this.each(function (el) {
push.apply(elems, find(selector, el));
});
return unique(elems);
},
has: function (selector) {
var comparator = (isString(selector) ? function (el) {
return find(selector, el).length !== 0;
} : function (el) {
return el.contains(selector);
});
return this.filter(comparator);
},
next: function () {
return cash(this[0].nextElementSibling);
},
not: function (selector) {
if (!selector) {
return this;
}
var comparator = getCompareFunction(selector);
return this.filter(function (el) {
return !comparator(el, selector);
});
},
parent: function () {
var result = [];
this.each(function (item) {
if (item && item.parentNode) {
result.push(item.parentNode);
}
});
return unique(result);
},
parents: function (selector) {
var last, result = [];
this.each(function (item) {
last = item;
while (last && last.parentNode && last !== doc.body.parentNode) {
last = last.parentNode;
if (!selector || (selector && matches(last, selector))) {
result.push(last);
}
}
});
return unique(result);
},
prev: function () {
return cash(this[0].previousElementSibling);
},
siblings: function (selector) {
var collection = this.parent().children(selector), el = this[0];
return collection.filter(function (i) {
return i !== el;
});
}
});
return cash;
});

View File

@ -0,0 +1,136 @@
(function($) {
'use strict';
let _defaults = {};
/**
* @class
*
*/
class CharacterCounter extends Component {
/**
* Construct CharacterCounter instance
* @constructor
* @param {Element} el
* @param {Object} options
*/
constructor(el, options) {
super(CharacterCounter, el, options);
this.el.M_CharacterCounter = this;
/**
* Options for the character counter
*/
this.options = $.extend({}, CharacterCounter.defaults, options);
this.isInvalid = false;
this.isValidLength = false;
this._setupCounter();
this._setupEventHandlers();
}
static get defaults() {
return _defaults;
}
static init(els, options) {
return super.init(this, els, options);
}
/**
* Get Instance
*/
static getInstance(el) {
let domElem = !!el.jquery ? el[0] : el;
return domElem.M_CharacterCounter;
}
/**
* Teardown component
*/
destroy() {
this._removeEventHandlers();
this.el.CharacterCounter = undefined;
this._removeCounter();
}
/**
* Setup Event Handlers
*/
_setupEventHandlers() {
this._handleUpdateCounterBound = this.updateCounter.bind(this);
this.el.addEventListener('focus', this._handleUpdateCounterBound, true);
this.el.addEventListener('input', this._handleUpdateCounterBound, true);
}
/**
* Remove Event Handlers
*/
_removeEventHandlers() {
this.el.removeEventListener('focus', this._handleUpdateCounterBound, true);
this.el.removeEventListener('input', this._handleUpdateCounterBound, true);
}
/**
* Setup counter element
*/
_setupCounter() {
this.counterEl = document.createElement('span');
$(this.counterEl)
.addClass('character-counter')
.css({
float: 'right',
'font-size': '12px',
height: 1
});
this.$el.parent().append(this.counterEl);
}
/**
* Remove counter element
*/
_removeCounter() {
$(this.counterEl).remove();
}
/**
* Update counter
*/
updateCounter() {
let maxLength = +this.$el.attr('data-length'),
actualLength = this.el.value.length;
this.isValidLength = actualLength <= maxLength;
let counterString = actualLength;
if (maxLength) {
counterString += '/' + maxLength;
this._validateInput();
}
$(this.counterEl).html(counterString);
}
/**
* Add validation classes
*/
_validateInput() {
if (this.isValidLength && this.isInvalid) {
this.isInvalid = false;
this.$el.removeClass('invalid');
} else if (!this.isValidLength && !this.isInvalid) {
this.isInvalid = true;
this.$el.removeClass('valid');
this.$el.addClass('invalid');
}
}
}
M.CharacterCounter = CharacterCounter;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(CharacterCounter, 'characterCounter', 'M_CharacterCounter');
}
})(cash);

481
resources/sass/materialize/js/chips.js vendored Normal file
View File

@ -0,0 +1,481 @@
(function($) {
'use strict';
let _defaults = {
data: [],
placeholder: '',
secondaryPlaceholder: '',
autocompleteOptions: {},
limit: Infinity,
onChipAdd: null,
onChipSelect: null,
onChipDelete: null
};
/**
* @typedef {Object} chip
* @property {String} tag chip tag string
* @property {String} [image] chip avatar image string
*/
/**
* @class
*
*/
class Chips extends Component {
/**
* Construct Chips instance and set up overlay
* @constructor
* @param {Element} el
* @param {Object} options
*/
constructor(el, options) {
super(Chips, el, options);
this.el.M_Chips = this;
/**
* Options for the modal
* @member Chips#options
* @prop {Array} data
* @prop {String} placeholder
* @prop {String} secondaryPlaceholder
* @prop {Object} autocompleteOptions
*/
this.options = $.extend({}, Chips.defaults, options);
this.$el.addClass('chips input-field');
this.chipsData = [];
this.$chips = $();
this._setupInput();
this.hasAutocomplete = Object.keys(this.options.autocompleteOptions).length > 0;
// Set input id
if (!this.$input.attr('id')) {
this.$input.attr('id', M.guid());
}
// Render initial chips
if (this.options.data.length) {
this.chipsData = this.options.data;
this._renderChips(this.chipsData);
}
// Setup autocomplete if needed
if (this.hasAutocomplete) {
this._setupAutocomplete();
}
this._setPlaceholder();
this._setupLabel();
this._setupEventHandlers();
}
static get defaults() {
return _defaults;
}
static init(els, options) {
return super.init(this, els, options);
}
/**
* Get Instance
*/
static getInstance(el) {
let domElem = !!el.jquery ? el[0] : el;
return domElem.M_Chips;
}
/**
* Get Chips Data
*/
getData() {
return this.chipsData;
}
/**
* Teardown component
*/
destroy() {
this._removeEventHandlers();
this.$chips.remove();
this.el.M_Chips = undefined;
}
/**
* Setup Event Handlers
*/
_setupEventHandlers() {
this._handleChipClickBound = this._handleChipClick.bind(this);
this._handleInputKeydownBound = this._handleInputKeydown.bind(this);
this._handleInputFocusBound = this._handleInputFocus.bind(this);
this._handleInputBlurBound = this._handleInputBlur.bind(this);
this.el.addEventListener('click', this._handleChipClickBound);
document.addEventListener('keydown', Chips._handleChipsKeydown);
document.addEventListener('keyup', Chips._handleChipsKeyup);
this.el.addEventListener('blur', Chips._handleChipsBlur, true);
this.$input[0].addEventListener('focus', this._handleInputFocusBound);
this.$input[0].addEventListener('blur', this._handleInputBlurBound);
this.$input[0].addEventListener('keydown', this._handleInputKeydownBound);
}
/**
* Remove Event Handlers
*/
_removeEventHandlers() {
this.el.removeEventListener('click', this._handleChipClickBound);
document.removeEventListener('keydown', Chips._handleChipsKeydown);
document.removeEventListener('keyup', Chips._handleChipsKeyup);
this.el.removeEventListener('blur', Chips._handleChipsBlur, true);
this.$input[0].removeEventListener('focus', this._handleInputFocusBound);
this.$input[0].removeEventListener('blur', this._handleInputBlurBound);
this.$input[0].removeEventListener('keydown', this._handleInputKeydownBound);
}
/**
* Handle Chip Click
* @param {Event} e
*/
_handleChipClick(e) {
let $chip = $(e.target).closest('.chip');
let clickedClose = $(e.target).is('.close');
if ($chip.length) {
let index = $chip.index();
if (clickedClose) {
// delete chip
this.deleteChip(index);
this.$input[0].focus();
} else {
// select chip
this.selectChip(index);
}
// Default handle click to focus on input
} else {
this.$input[0].focus();
}
}
/**
* Handle Chips Keydown
* @param {Event} e
*/
static _handleChipsKeydown(e) {
Chips._keydown = true;
let $chips = $(e.target).closest('.chips');
let chipsKeydown = e.target && $chips.length;
// Don't handle keydown inputs on input and textarea
if ($(e.target).is('input, textarea') || !chipsKeydown) {
return;
}
let currChips = $chips[0].M_Chips;
// backspace and delete
if (e.keyCode === 8 || e.keyCode === 46) {
e.preventDefault();
let selectIndex = currChips.chipsData.length;
if (currChips._selectedChip) {
let index = currChips._selectedChip.index();
currChips.deleteChip(index);
currChips._selectedChip = null;
// Make sure selectIndex doesn't go negative
selectIndex = Math.max(index - 1, 0);
}
if (currChips.chipsData.length) {
currChips.selectChip(selectIndex);
}
// left arrow key
} else if (e.keyCode === 37) {
if (currChips._selectedChip) {
let selectIndex = currChips._selectedChip.index() - 1;
if (selectIndex < 0) {
return;
}
currChips.selectChip(selectIndex);
}
// right arrow key
} else if (e.keyCode === 39) {
if (currChips._selectedChip) {
let selectIndex = currChips._selectedChip.index() + 1;
if (selectIndex >= currChips.chipsData.length) {
currChips.$input[0].focus();
} else {
currChips.selectChip(selectIndex);
}
}
}
}
/**
* Handle Chips Keyup
* @param {Event} e
*/
static _handleChipsKeyup(e) {
Chips._keydown = false;
}
/**
* Handle Chips Blur
* @param {Event} e
*/
static _handleChipsBlur(e) {
if (!Chips._keydown) {
let $chips = $(e.target).closest('.chips');
let currChips = $chips[0].M_Chips;
currChips._selectedChip = null;
}
}
/**
* Handle Input Focus
*/
_handleInputFocus() {
this.$el.addClass('focus');
}
/**
* Handle Input Blur
*/
_handleInputBlur() {
this.$el.removeClass('focus');
}
/**
* Handle Input Keydown
* @param {Event} e
*/
_handleInputKeydown(e) {
Chips._keydown = true;
// enter
if (e.keyCode === 13) {
// Override enter if autocompleting.
if (this.hasAutocomplete && this.autocomplete && this.autocomplete.isOpen) {
return;
}
e.preventDefault();
this.addChip({
tag: this.$input[0].value
});
this.$input[0].value = '';
// delete or left
} else if (
(e.keyCode === 8 || e.keyCode === 37) &&
this.$input[0].value === '' &&
this.chipsData.length
) {
e.preventDefault();
this.selectChip(this.chipsData.length - 1);
}
}
/**
* Render Chip
* @param {chip} chip
* @return {Element}
*/
_renderChip(chip) {
if (!chip.tag) {
return;
}
let renderedChip = document.createElement('div');
let closeIcon = document.createElement('i');
renderedChip.classList.add('chip');
renderedChip.textContent = chip.tag;
renderedChip.setAttribute('tabindex', 0);
$(closeIcon).addClass('material-icons close');
closeIcon.textContent = 'close';
// attach image if needed
if (chip.image) {
let img = document.createElement('img');
img.setAttribute('src', chip.image);
renderedChip.insertBefore(img, renderedChip.firstChild);
}
renderedChip.appendChild(closeIcon);
return renderedChip;
}
/**
* Render Chips
*/
_renderChips() {
this.$chips.remove();
for (let i = 0; i < this.chipsData.length; i++) {
let chipEl = this._renderChip(this.chipsData[i]);
this.$el.append(chipEl);
this.$chips.add(chipEl);
}
// move input to end
this.$el.append(this.$input[0]);
}
/**
* Setup Autocomplete
*/
_setupAutocomplete() {
this.options.autocompleteOptions.onAutocomplete = (val) => {
this.addChip({
tag: val
});
this.$input[0].value = '';
this.$input[0].focus();
};
this.autocomplete = M.Autocomplete.init(this.$input[0], this.options.autocompleteOptions);
}
/**
* Setup Input
*/
_setupInput() {
this.$input = this.$el.find('input');
if (!this.$input.length) {
this.$input = $('<input></input>');
this.$el.append(this.$input);
}
this.$input.addClass('input');
}
/**
* Setup Label
*/
_setupLabel() {
this.$label = this.$el.find('label');
if (this.$label.length) {
this.$label.setAttribute('for', this.$input.attr('id'));
}
}
/**
* Set placeholder
*/
_setPlaceholder() {
if (this.chipsData !== undefined && !this.chipsData.length && this.options.placeholder) {
$(this.$input).prop('placeholder', this.options.placeholder);
} else if (
(this.chipsData === undefined || !!this.chipsData.length) &&
this.options.secondaryPlaceholder
) {
$(this.$input).prop('placeholder', this.options.secondaryPlaceholder);
}
}
/**
* Check if chip is valid
* @param {chip} chip
*/
_isValid(chip) {
if (chip.hasOwnProperty('tag') && chip.tag !== '') {
let exists = false;
for (let i = 0; i < this.chipsData.length; i++) {
if (this.chipsData[i].tag === chip.tag) {
exists = true;
break;
}
}
return !exists;
}
return false;
}
/**
* Add chip
* @param {chip} chip
*/
addChip(chip) {
if (!this._isValid(chip) || this.chipsData.length >= this.options.limit) {
return;
}
let renderedChip = this._renderChip(chip);
this.$chips.add(renderedChip);
this.chipsData.push(chip);
$(this.$input).before(renderedChip);
this._setPlaceholder();
// fire chipAdd callback
if (typeof this.options.onChipAdd === 'function') {
this.options.onChipAdd.call(this, this.$el, renderedChip);
}
}
/**
* Delete chip
* @param {Number} chip
*/
deleteChip(chipIndex) {
let $chip = this.$chips.eq(chipIndex);
this.$chips.eq(chipIndex).remove();
this.$chips = this.$chips.filter(function(el) {
return $(el).index() >= 0;
});
this.chipsData.splice(chipIndex, 1);
this._setPlaceholder();
// fire chipDelete callback
if (typeof this.options.onChipDelete === 'function') {
this.options.onChipDelete.call(this, this.$el, $chip[0]);
}
}
/**
* Select chip
* @param {Number} chip
*/
selectChip(chipIndex) {
let $chip = this.$chips.eq(chipIndex);
this._selectedChip = $chip;
$chip[0].focus();
// fire chipSelect callback
if (typeof this.options.onChipSelect === 'function') {
this.options.onChipSelect.call(this, this.$el, $chip[0]);
}
}
}
/**
* @static
* @memberof Chips
*/
Chips._keydown = false;
M.Chips = Chips;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Chips, 'chips', 'M_Chips');
}
$(document).ready(function() {
// Handle removal of static chips.
$(document.body).on('click', '.chip .close', function() {
let $chips = $(this).closest('.chips');
if ($chips.length && $chips[0].M_Chips) {
return;
}
$(this)
.closest('.chip')
.remove();
});
});
})(cash);

View File

@ -0,0 +1,275 @@
(function($, anim) {
'use strict';
let _defaults = {
accordion: true,
onOpenStart: undefined,
onOpenEnd: undefined,
onCloseStart: undefined,
onCloseEnd: undefined,
inDuration: 300,
outDuration: 300
};
/**
* @class
*
*/
class Collapsible extends Component {
/**
* Construct Collapsible instance
* @constructor
* @param {Element} el
* @param {Object} options
*/
constructor(el, options) {
super(Collapsible, el, options);
this.el.M_Collapsible = this;
/**
* Options for the collapsible
* @member Collapsible#options
* @prop {Boolean} [accordion=false] - Type of the collapsible
* @prop {Function} onOpenStart - Callback function called before collapsible is opened
* @prop {Function} onOpenEnd - Callback function called after collapsible is opened
* @prop {Function} onCloseStart - Callback function called before collapsible is closed
* @prop {Function} onCloseEnd - Callback function called after collapsible is closed
* @prop {Number} inDuration - Transition in duration in milliseconds.
* @prop {Number} outDuration - Transition duration in milliseconds.
*/
this.options = $.extend({}, Collapsible.defaults, options);
// Setup tab indices
this.$headers = this.$el.children('li').children('.collapsible-header');
this.$headers.attr('tabindex', 0);
this._setupEventHandlers();
// Open first active
let $activeBodies = this.$el.children('li.active').children('.collapsible-body');
if (this.options.accordion) {
// Handle Accordion
$activeBodies.first().css('display', 'block');
} else {
// Handle Expandables
$activeBodies.css('display', 'block');
}
}
static get defaults() {
return _defaults;
}
static init(els, options) {
return super.init(this, els, options);
}
/**
* Get Instance
*/
static getInstance(el) {
let domElem = !!el.jquery ? el[0] : el;
return domElem.M_Collapsible;
}
/**
* Teardown component
*/
destroy() {
this._removeEventHandlers();
this.el.M_Collapsible = undefined;
}
/**
* Setup Event Handlers
*/
_setupEventHandlers() {
this._handleCollapsibleClickBound = this._handleCollapsibleClick.bind(this);
this._handleCollapsibleKeydownBound = this._handleCollapsibleKeydown.bind(this);
this.el.addEventListener('click', this._handleCollapsibleClickBound);
this.$headers.each((header) => {
header.addEventListener('keydown', this._handleCollapsibleKeydownBound);
});
}
/**
* Remove Event Handlers
*/
_removeEventHandlers() {
this.el.removeEventListener('click', this._handleCollapsibleClickBound);
this.$headers.each((header) => {
header.removeEventListener('keydown', this._handleCollapsibleKeydownBound);
});
}
/**
* Handle Collapsible Click
* @param {Event} e
*/
_handleCollapsibleClick(e) {
let $header = $(e.target).closest('.collapsible-header');
if (e.target && $header.length) {
let $collapsible = $header.closest('.collapsible');
if ($collapsible[0] === this.el) {
let $collapsibleLi = $header.closest('li');
let $collapsibleLis = $collapsible.children('li');
let isActive = $collapsibleLi[0].classList.contains('active');
let index = $collapsibleLis.index($collapsibleLi);
if (isActive) {
this.close(index);
} else {
this.open(index);
}
}
}
}
/**
* Handle Collapsible Keydown
* @param {Event} e
*/
_handleCollapsibleKeydown(e) {
if (e.keyCode === 13) {
this._handleCollapsibleClickBound(e);
}
}
/**
* Animate in collapsible slide
* @param {Number} index - 0th index of slide
*/
_animateIn(index) {
let $collapsibleLi = this.$el.children('li').eq(index);
if ($collapsibleLi.length) {
let $body = $collapsibleLi.children('.collapsible-body');
anim.remove($body[0]);
$body.css({
display: 'block',
overflow: 'hidden',
height: 0,
paddingTop: '',
paddingBottom: ''
});
let pTop = $body.css('padding-top');
let pBottom = $body.css('padding-bottom');
let finalHeight = $body[0].scrollHeight;
$body.css({
paddingTop: 0,
paddingBottom: 0
});
anim({
targets: $body[0],
height: finalHeight,
paddingTop: pTop,
paddingBottom: pBottom,
duration: this.options.inDuration,
easing: 'easeInOutCubic',
complete: (anim) => {
$body.css({
overflow: '',
paddingTop: '',
paddingBottom: '',
height: ''
});
// onOpenEnd callback
if (typeof this.options.onOpenEnd === 'function') {
this.options.onOpenEnd.call(this, $collapsibleLi[0]);
}
}
});
}
}
/**
* Animate out collapsible slide
* @param {Number} index - 0th index of slide to open
*/
_animateOut(index) {
let $collapsibleLi = this.$el.children('li').eq(index);
if ($collapsibleLi.length) {
let $body = $collapsibleLi.children('.collapsible-body');
anim.remove($body[0]);
$body.css('overflow', 'hidden');
anim({
targets: $body[0],
height: 0,
paddingTop: 0,
paddingBottom: 0,
duration: this.options.outDuration,
easing: 'easeInOutCubic',
complete: () => {
$body.css({
height: '',
overflow: '',
padding: '',
display: ''
});
// onCloseEnd callback
if (typeof this.options.onCloseEnd === 'function') {
this.options.onCloseEnd.call(this, $collapsibleLi[0]);
}
}
});
}
}
/**
* Open Collapsible
* @param {Number} index - 0th index of slide
*/
open(index) {
let $collapsibleLi = this.$el.children('li').eq(index);
if ($collapsibleLi.length && !$collapsibleLi[0].classList.contains('active')) {
// onOpenStart callback
if (typeof this.options.onOpenStart === 'function') {
this.options.onOpenStart.call(this, $collapsibleLi[0]);
}
// Handle accordion behavior
if (this.options.accordion) {
let $collapsibleLis = this.$el.children('li');
let $activeLis = this.$el.children('li.active');
$activeLis.each((el) => {
let index = $collapsibleLis.index($(el));
this.close(index);
});
}
// Animate in
$collapsibleLi[0].classList.add('active');
this._animateIn(index);
}
}
/**
* Close Collapsible
* @param {Number} index - 0th index of slide
*/
close(index) {
let $collapsibleLi = this.$el.children('li').eq(index);
if ($collapsibleLi.length && $collapsibleLi[0].classList.contains('active')) {
// onCloseStart callback
if (typeof this.options.onCloseStart === 'function') {
this.options.onCloseStart.call(this, $collapsibleLi[0]);
}
// Animate out
$collapsibleLi[0].classList.remove('active');
this._animateOut(index);
}
}
}
M.Collapsible = Collapsible;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Collapsible, 'collapsible', 'M_Collapsible');
}
})(cash, M.anime);

View File

@ -0,0 +1,44 @@
class Component {
/**
* Generic constructor for all components
* @constructor
* @param {Element} el
* @param {Object} options
*/
constructor(classDef, el, options) {
// Display error if el is valid HTML Element
if (!(el instanceof Element)) {
console.error(Error(el + ' is not an HTML Element'));
}
// If exists, destroy and reinitialize in child
let ins = classDef.getInstance(el);
if (!!ins) {
ins.destroy();
}
this.el = el;
this.$el = cash(el);
}
/**
* Initializes components
* @param {class} classDef
* @param {Element | NodeList | jQuery} els
* @param {Object} options
*/
static init(classDef, els, options) {
let instances = null;
if (els instanceof Element) {
instances = new classDef(els, options);
} else if (!!els && (els.jquery || els.cash || els instanceof NodeList)) {
let instancesArr = [];
for (let i = 0; i < els.length; i++) {
instancesArr.push(new classDef(els[i], options));
}
instances = instancesArr;
}
return instances;
}
}

View File

@ -0,0 +1,975 @@
(function($) {
'use strict';
let _defaults = {
// Close when date is selected
autoClose: false,
// the default output format for the input field value
format: 'mmm dd, yyyy',
// Used to create date object from current input string
parse: null,
// The initial date to view when first opened
defaultDate: null,
// Make the `defaultDate` the initial selected value
setDefaultDate: false,
disableWeekends: false,
disableDayFn: null,
// First day of week (0: Sunday, 1: Monday etc)
firstDay: 0,
// The earliest date that can be selected
minDate: null,
// Thelatest date that can be selected
maxDate: null,
// Number of years either side, or array of upper/lower range
yearRange: 10,
// used internally (don't config outside)
minYear: 0,
maxYear: 9999,
minMonth: undefined,
maxMonth: undefined,
startRange: null,
endRange: null,
isRTL: false,
// Render the month after year in the calendar title
showMonthAfterYear: false,
// Render days of the calendar grid that fall in the next or previous month
showDaysInNextAndPreviousMonths: false,
// Specify a DOM element to render the calendar in
container: null,
// Show clear button
showClearBtn: false,
// internationalization
i18n: {
cancel: 'Cancel',
clear: 'Clear',
done: 'Ok',
previousMonth: '',
nextMonth: '',
months: [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
],
monthsShort: [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
],
weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
weekdaysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
weekdaysAbbrev: ['S', 'M', 'T', 'W', 'T', 'F', 'S']
},
// events array
events: [],
// callback function
onSelect: null,
onOpen: null,
onClose: null,
onDraw: null
};
/**
* @class
*
*/
class Datepicker extends Component {
/**
* Construct Datepicker instance and set up overlay
* @constructor
* @param {Element} el
* @param {Object} options
*/
constructor(el, options) {
super(Datepicker, el, options);
this.el.M_Datepicker = this;
this.options = $.extend({}, Datepicker.defaults, options);
// make sure i18n defaults are not lost when only few i18n option properties are passed
if (!!options && options.hasOwnProperty('i18n') && typeof options.i18n === 'object') {
this.options.i18n = $.extend({}, Datepicker.defaults.i18n, options.i18n);
}
// Remove time component from minDate and maxDate options
if (this.options.minDate) this.options.minDate.setHours(0, 0, 0, 0);
if (this.options.maxDate) this.options.maxDate.setHours(0, 0, 0, 0);
this.id = M.guid();
this._setupVariables();
this._insertHTMLIntoDOM();
this._setupModal();
this._setupEventHandlers();
if (!this.options.defaultDate) {
this.options.defaultDate = new Date(Date.parse(this.el.value));
}
let defDate = this.options.defaultDate;
if (Datepicker._isDate(defDate)) {
if (this.options.setDefaultDate) {
this.setDate(defDate, true);
this.setInputValue();
} else {
this.gotoDate(defDate);
}
} else {
this.gotoDate(new Date());
}
/**
* Describes open/close state of datepicker
* @type {Boolean}
*/
this.isOpen = false;
}
static get defaults() {
return _defaults;
}
static init(els, options) {
return super.init(this, els, options);
}
static _isDate(obj) {
return /Date/.test(Object.prototype.toString.call(obj)) && !isNaN(obj.getTime());
}
static _isWeekend(date) {
let day = date.getDay();
return day === 0 || day === 6;
}
static _setToStartOfDay(date) {
if (Datepicker._isDate(date)) date.setHours(0, 0, 0, 0);
}
static _getDaysInMonth(year, month) {
return [31, Datepicker._isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][
month
];
}
static _isLeapYear(year) {
// solution by Matti Virkkunen: http://stackoverflow.com/a/4881951
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
static _compareDates(a, b) {
// weak date comparison (use setToStartOfDay(date) to ensure correct result)
return a.getTime() === b.getTime();
}
static _setToStartOfDay(date) {
if (Datepicker._isDate(date)) date.setHours(0, 0, 0, 0);
}
/**
* Get Instance
*/
static getInstance(el) {
let domElem = !!el.jquery ? el[0] : el;
return domElem.M_Datepicker;
}
/**
* Teardown component
*/
destroy() {
this._removeEventHandlers();
this.modal.destroy();
$(this.modalEl).remove();
this.destroySelects();
this.el.M_Datepicker = undefined;
}
destroySelects() {
let oldYearSelect = this.calendarEl.querySelector('.orig-select-year');
if (oldYearSelect) {
M.FormSelect.getInstance(oldYearSelect).destroy();
}
let oldMonthSelect = this.calendarEl.querySelector('.orig-select-month');
if (oldMonthSelect) {
M.FormSelect.getInstance(oldMonthSelect).destroy();
}
}
_insertHTMLIntoDOM() {
if (this.options.showClearBtn) {
$(this.clearBtn).css({ visibility: '' });
this.clearBtn.innerHTML = this.options.i18n.clear;
}
this.doneBtn.innerHTML = this.options.i18n.done;
this.cancelBtn.innerHTML = this.options.i18n.cancel;
if (this.options.container) {
this.$modalEl.appendTo(this.options.container);
} else {
this.$modalEl.insertBefore(this.el);
}
}
_setupModal() {
this.modalEl.id = 'modal-' + this.id;
this.modal = M.Modal.init(this.modalEl, {
onCloseEnd: () => {
this.isOpen = false;
}
});
}
toString(format) {
format = format || this.options.format;
if (!Datepicker._isDate(this.date)) {
return '';
}
let formatArray = format.split(/(d{1,4}|m{1,4}|y{4}|yy|!.)/g);
let formattedDate = formatArray
.map((label) => {
if (this.formats[label]) {
return this.formats[label]();
}
return label;
})
.join('');
return formattedDate;
}
setDate(date, preventOnSelect) {
if (!date) {
this.date = null;
this._renderDateDisplay();
return this.draw();
}
if (typeof date === 'string') {
date = new Date(Date.parse(date));
}
if (!Datepicker._isDate(date)) {
return;
}
let min = this.options.minDate,
max = this.options.maxDate;
if (Datepicker._isDate(min) && date < min) {
date = min;
} else if (Datepicker._isDate(max) && date > max) {
date = max;
}
this.date = new Date(date.getTime());
this._renderDateDisplay();
Datepicker._setToStartOfDay(this.date);
this.gotoDate(this.date);
if (!preventOnSelect && typeof this.options.onSelect === 'function') {
this.options.onSelect.call(this, this.date);
}
}
setInputValue() {
this.el.value = this.toString();
this.$el.trigger('change', { firedBy: this });
}
_renderDateDisplay() {
let displayDate = Datepicker._isDate(this.date) ? this.date : new Date();
let i18n = this.options.i18n;
let day = i18n.weekdaysShort[displayDate.getDay()];
let month = i18n.monthsShort[displayDate.getMonth()];
let date = displayDate.getDate();
this.yearTextEl.innerHTML = displayDate.getFullYear();
this.dateTextEl.innerHTML = `${day}, ${month} ${date}`;
}
/**
* change view to a specific date
*/
gotoDate(date) {
let newCalendar = true;
if (!Datepicker._isDate(date)) {
return;
}
if (this.calendars) {
let firstVisibleDate = new Date(this.calendars[0].year, this.calendars[0].month, 1),
lastVisibleDate = new Date(
this.calendars[this.calendars.length - 1].year,
this.calendars[this.calendars.length - 1].month,
1
),
visibleDate = date.getTime();
// get the end of the month
lastVisibleDate.setMonth(lastVisibleDate.getMonth() + 1);
lastVisibleDate.setDate(lastVisibleDate.getDate() - 1);
newCalendar =
visibleDate < firstVisibleDate.getTime() || lastVisibleDate.getTime() < visibleDate;
}
if (newCalendar) {
this.calendars = [
{
month: date.getMonth(),
year: date.getFullYear()
}
];
}
this.adjustCalendars();
}
adjustCalendars() {
this.calendars[0] = this.adjustCalendar(this.calendars[0]);
this.draw();
}
adjustCalendar(calendar) {
if (calendar.month < 0) {
calendar.year -= Math.ceil(Math.abs(calendar.month) / 12);
calendar.month += 12;
}
if (calendar.month > 11) {
calendar.year += Math.floor(Math.abs(calendar.month) / 12);
calendar.month -= 12;
}
return calendar;
}
nextMonth() {
this.calendars[0].month++;
this.adjustCalendars();
}
prevMonth() {
this.calendars[0].month--;
this.adjustCalendars();
}
render(year, month, randId) {
let opts = this.options,
now = new Date(),
days = Datepicker._getDaysInMonth(year, month),
before = new Date(year, month, 1).getDay(),
data = [],
row = [];
Datepicker._setToStartOfDay(now);
if (opts.firstDay > 0) {
before -= opts.firstDay;
if (before < 0) {
before += 7;
}
}
let previousMonth = month === 0 ? 11 : month - 1,
nextMonth = month === 11 ? 0 : month + 1,
yearOfPreviousMonth = month === 0 ? year - 1 : year,
yearOfNextMonth = month === 11 ? year + 1 : year,
daysInPreviousMonth = Datepicker._getDaysInMonth(yearOfPreviousMonth, previousMonth);
let cells = days + before,
after = cells;
while (after > 7) {
after -= 7;
}
cells += 7 - after;
let isWeekSelected = false;
for (let i = 0, r = 0; i < cells; i++) {
let day = new Date(year, month, 1 + (i - before)),
isSelected = Datepicker._isDate(this.date)
? Datepicker._compareDates(day, this.date)
: false,
isToday = Datepicker._compareDates(day, now),
hasEvent = opts.events.indexOf(day.toDateString()) !== -1 ? true : false,
isEmpty = i < before || i >= days + before,
dayNumber = 1 + (i - before),
monthNumber = month,
yearNumber = year,
isStartRange = opts.startRange && Datepicker._compareDates(opts.startRange, day),
isEndRange = opts.endRange && Datepicker._compareDates(opts.endRange, day),
isInRange =
opts.startRange && opts.endRange && opts.startRange < day && day < opts.endRange,
isDisabled =
(opts.minDate && day < opts.minDate) ||
(opts.maxDate && day > opts.maxDate) ||
(opts.disableWeekends && Datepicker._isWeekend(day)) ||
(opts.disableDayFn && opts.disableDayFn(day));
if (isEmpty) {
if (i < before) {
dayNumber = daysInPreviousMonth + dayNumber;
monthNumber = previousMonth;
yearNumber = yearOfPreviousMonth;
} else {
dayNumber = dayNumber - days;
monthNumber = nextMonth;
yearNumber = yearOfNextMonth;
}
}
let dayConfig = {
day: dayNumber,
month: monthNumber,
year: yearNumber,
hasEvent: hasEvent,
isSelected: isSelected,
isToday: isToday,
isDisabled: isDisabled,
isEmpty: isEmpty,
isStartRange: isStartRange,
isEndRange: isEndRange,
isInRange: isInRange,
showDaysInNextAndPreviousMonths: opts.showDaysInNextAndPreviousMonths
};
row.push(this.renderDay(dayConfig));
if (++r === 7) {
data.push(this.renderRow(row, opts.isRTL, isWeekSelected));
row = [];
r = 0;
isWeekSelected = false;
}
}
return this.renderTable(opts, data, randId);
}
renderDay(opts) {
let arr = [];
let ariaSelected = 'false';
if (opts.isEmpty) {
if (opts.showDaysInNextAndPreviousMonths) {
arr.push('is-outside-current-month');
arr.push('is-selection-disabled');
} else {
return '<td class="is-empty"></td>';
}
}
if (opts.isDisabled) {
arr.push('is-disabled');
}
if (opts.isToday) {
arr.push('is-today');
}
if (opts.isSelected) {
arr.push('is-selected');
ariaSelected = 'true';
}
if (opts.hasEvent) {
arr.push('has-event');
}
if (opts.isInRange) {
arr.push('is-inrange');
}
if (opts.isStartRange) {
arr.push('is-startrange');
}
if (opts.isEndRange) {
arr.push('is-endrange');
}
return (
`<td data-day="${opts.day}" class="${arr.join(' ')}" aria-selected="${ariaSelected}">` +
`<button class="datepicker-day-button" type="button" data-year="${opts.year}" data-month="${
opts.month
}" data-day="${opts.day}">${opts.day}</button>` +
'</td>'
);
}
renderRow(days, isRTL, isRowSelected) {
return (
'<tr class="datepicker-row' +
(isRowSelected ? ' is-selected' : '') +
'">' +
(isRTL ? days.reverse() : days).join('') +
'</tr>'
);
}
renderTable(opts, data, randId) {
return (
'<div class="datepicker-table-wrapper"><table cellpadding="0" cellspacing="0" class="datepicker-table" role="grid" aria-labelledby="' +
randId +
'">' +
this.renderHead(opts) +
this.renderBody(data) +
'</table></div>'
);
}
renderHead(opts) {
let i,
arr = [];
for (i = 0; i < 7; i++) {
arr.push(
`<th scope="col"><abbr title="${this.renderDayName(opts, i)}">${this.renderDayName(
opts,
i,
true
)}</abbr></th>`
);
}
return '<thead><tr>' + (opts.isRTL ? arr.reverse() : arr).join('') + '</tr></thead>';
}
renderBody(rows) {
return '<tbody>' + rows.join('') + '</tbody>';
}
renderTitle(instance, c, year, month, refYear, randId) {
let i,
j,
arr,
opts = this.options,
isMinYear = year === opts.minYear,
isMaxYear = year === opts.maxYear,
html =
'<div id="' +
randId +
'" class="datepicker-controls" role="heading" aria-live="assertive">',
monthHtml,
yearHtml,
prev = true,
next = true;
for (arr = [], i = 0; i < 12; i++) {
arr.push(
'<option value="' +
(year === refYear ? i - c : 12 + i - c) +
'"' +
(i === month ? ' selected="selected"' : '') +
((isMinYear && i < opts.minMonth) || (isMaxYear && i > opts.maxMonth)
? 'disabled="disabled"'
: '') +
'>' +
opts.i18n.months[i] +
'</option>'
);
}
monthHtml =
'<select class="datepicker-select orig-select-month" tabindex="-1">' +
arr.join('') +
'</select>';
if ($.isArray(opts.yearRange)) {
i = opts.yearRange[0];
j = opts.yearRange[1] + 1;
} else {
i = year - opts.yearRange;
j = 1 + year + opts.yearRange;
}
for (arr = []; i < j && i <= opts.maxYear; i++) {
if (i >= opts.minYear) {
arr.push(`<option value="${i}" ${i === year ? 'selected="selected"' : ''}>${i}</option>`);
}
}
yearHtml = `<select class="datepicker-select orig-select-year" tabindex="-1">${arr.join(
''
)}</select>`;
let leftArrow =
'<svg fill="#000000" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M15.41 16.09l-4.58-4.59 4.58-4.59L14 5.5l-6 6 6 6z"/><path d="M0-.5h24v24H0z" fill="none"/></svg>';
html += `<button class="month-prev${
prev ? '' : ' is-disabled'
}" type="button">${leftArrow}</button>`;
html += '<div class="selects-container">';
if (opts.showMonthAfterYear) {
html += yearHtml + monthHtml;
} else {
html += monthHtml + yearHtml;
}
html += '</div>';
if (isMinYear && (month === 0 || opts.minMonth >= month)) {
prev = false;
}
if (isMaxYear && (month === 11 || opts.maxMonth <= month)) {
next = false;
}
let rightArrow =
'<svg fill="#000000" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"/><path d="M0-.25h24v24H0z" fill="none"/></svg>';
html += `<button class="month-next${
next ? '' : ' is-disabled'
}" type="button">${rightArrow}</button>`;
return (html += '</div>');
}
/**
* refresh the HTML
*/
draw(force) {
if (!this.isOpen && !force) {
return;
}
let opts = this.options,
minYear = opts.minYear,
maxYear = opts.maxYear,
minMonth = opts.minMonth,
maxMonth = opts.maxMonth,
html = '',
randId;
if (this._y <= minYear) {
this._y = minYear;
if (!isNaN(minMonth) && this._m < minMonth) {
this._m = minMonth;
}
}
if (this._y >= maxYear) {
this._y = maxYear;
if (!isNaN(maxMonth) && this._m > maxMonth) {
this._m = maxMonth;
}
}
randId =
'datepicker-title-' +
Math.random()
.toString(36)
.replace(/[^a-z]+/g, '')
.substr(0, 2);
for (let c = 0; c < 1; c++) {
this._renderDateDisplay();
html +=
this.renderTitle(
this,
c,
this.calendars[c].year,
this.calendars[c].month,
this.calendars[0].year,
randId
) + this.render(this.calendars[c].year, this.calendars[c].month, randId);
}
this.destroySelects();
this.calendarEl.innerHTML = html;
// Init Materialize Select
let yearSelect = this.calendarEl.querySelector('.orig-select-year');
let monthSelect = this.calendarEl.querySelector('.orig-select-month');
M.FormSelect.init(yearSelect, {
classes: 'select-year',
dropdownOptions: { container: document.body, constrainWidth: false }
});
M.FormSelect.init(monthSelect, {
classes: 'select-month',
dropdownOptions: { container: document.body, constrainWidth: false }
});
// Add change handlers for select
yearSelect.addEventListener('change', this._handleYearChange.bind(this));
monthSelect.addEventListener('change', this._handleMonthChange.bind(this));
if (typeof this.options.onDraw === 'function') {
this.options.onDraw(this);
}
}
/**
* Setup Event Handlers
*/
_setupEventHandlers() {
this._handleInputKeydownBound = this._handleInputKeydown.bind(this);
this._handleInputClickBound = this._handleInputClick.bind(this);
this._handleInputChangeBound = this._handleInputChange.bind(this);
this._handleCalendarClickBound = this._handleCalendarClick.bind(this);
this._finishSelectionBound = this._finishSelection.bind(this);
this._handleMonthChange = this._handleMonthChange.bind(this);
this._closeBound = this.close.bind(this);
this.el.addEventListener('click', this._handleInputClickBound);
this.el.addEventListener('keydown', this._handleInputKeydownBound);
this.el.addEventListener('change', this._handleInputChangeBound);
this.calendarEl.addEventListener('click', this._handleCalendarClickBound);
this.doneBtn.addEventListener('click', this._finishSelectionBound);
this.cancelBtn.addEventListener('click', this._closeBound);
if (this.options.showClearBtn) {
this._handleClearClickBound = this._handleClearClick.bind(this);
this.clearBtn.addEventListener('click', this._handleClearClickBound);
}
}
_setupVariables() {
this.$modalEl = $(Datepicker._template);
this.modalEl = this.$modalEl[0];
this.calendarEl = this.modalEl.querySelector('.datepicker-calendar');
this.yearTextEl = this.modalEl.querySelector('.year-text');
this.dateTextEl = this.modalEl.querySelector('.date-text');
if (this.options.showClearBtn) {
this.clearBtn = this.modalEl.querySelector('.datepicker-clear');
}
this.doneBtn = this.modalEl.querySelector('.datepicker-done');
this.cancelBtn = this.modalEl.querySelector('.datepicker-cancel');
this.formats = {
d: () => {
return this.date.getDate();
},
dd: () => {
let d = this.date.getDate();
return (d < 10 ? '0' : '') + d;
},
ddd: () => {
return this.options.i18n.weekdaysShort[this.date.getDay()];
},
dddd: () => {
return this.options.i18n.weekdays[this.date.getDay()];
},
m: () => {
return this.date.getMonth() + 1;
},
mm: () => {
let m = this.date.getMonth() + 1;
return (m < 10 ? '0' : '') + m;
},
mmm: () => {
return this.options.i18n.monthsShort[this.date.getMonth()];
},
mmmm: () => {
return this.options.i18n.months[this.date.getMonth()];
},
yy: () => {
return ('' + this.date.getFullYear()).slice(2);
},
yyyy: () => {
return this.date.getFullYear();
}
};
}
/**
* Remove Event Handlers
*/
_removeEventHandlers() {
this.el.removeEventListener('click', this._handleInputClickBound);
this.el.removeEventListener('keydown', this._handleInputKeydownBound);
this.el.removeEventListener('change', this._handleInputChangeBound);
this.calendarEl.removeEventListener('click', this._handleCalendarClickBound);
}
_handleInputClick() {
this.open();
}
_handleInputKeydown(e) {
if (e.which === M.keys.ENTER) {
e.preventDefault();
this.open();
}
}
_handleCalendarClick(e) {
if (!this.isOpen) {
return;
}
let $target = $(e.target);
if (!$target.hasClass('is-disabled')) {
if (
$target.hasClass('datepicker-day-button') &&
!$target.hasClass('is-empty') &&
!$target.parent().hasClass('is-disabled')
) {
this.setDate(
new Date(
e.target.getAttribute('data-year'),
e.target.getAttribute('data-month'),
e.target.getAttribute('data-day')
)
);
if (this.options.autoClose) {
this._finishSelection();
}
} else if ($target.closest('.month-prev').length) {
this.prevMonth();
} else if ($target.closest('.month-next').length) {
this.nextMonth();
}
}
}
_handleClearClick() {
this.date = null;
this.setInputValue();
this.close();
}
_handleMonthChange(e) {
this.gotoMonth(e.target.value);
}
_handleYearChange(e) {
this.gotoYear(e.target.value);
}
/**
* change view to a specific month (zero-index, e.g. 0: January)
*/
gotoMonth(month) {
if (!isNaN(month)) {
this.calendars[0].month = parseInt(month, 10);
this.adjustCalendars();
}
}
/**
* change view to a specific full year (e.g. "2012")
*/
gotoYear(year) {
if (!isNaN(year)) {
this.calendars[0].year = parseInt(year, 10);
this.adjustCalendars();
}
}
_handleInputChange(e) {
let date;
// Prevent change event from being fired when triggered by the plugin
if (e.firedBy === this) {
return;
}
if (this.options.parse) {
date = this.options.parse(this.el.value, this.options.format);
} else {
date = new Date(Date.parse(this.el.value));
}
if (Datepicker._isDate(date)) {
this.setDate(date);
}
}
renderDayName(opts, day, abbr) {
day += opts.firstDay;
while (day >= 7) {
day -= 7;
}
return abbr ? opts.i18n.weekdaysAbbrev[day] : opts.i18n.weekdays[day];
}
/**
* Set input value to the selected date and close Datepicker
*/
_finishSelection() {
this.setInputValue();
this.close();
}
/**
* Open Datepicker
*/
open() {
if (this.isOpen) {
return;
}
this.isOpen = true;
if (typeof this.options.onOpen === 'function') {
this.options.onOpen.call(this);
}
this.draw();
this.modal.open();
return this;
}
/**
* Close Datepicker
*/
close() {
if (!this.isOpen) {
return;
}
this.isOpen = false;
if (typeof this.options.onClose === 'function') {
this.options.onClose.call(this);
}
this.modal.close();
return this;
}
}
Datepicker._template = [
'<div class= "modal datepicker-modal">',
'<div class="modal-content datepicker-container">',
'<div class="datepicker-date-display">',
'<span class="year-text"></span>',
'<span class="date-text"></span>',
'</div>',
'<div class="datepicker-calendar-container">',
'<div class="datepicker-calendar"></div>',
'<div class="datepicker-footer">',
'<button class="btn-flat datepicker-clear waves-effect" style="visibility: hidden;" type="button"></button>',
'<div class="confirmation-btns">',
'<button class="btn-flat datepicker-cancel waves-effect" type="button"></button>',
'<button class="btn-flat datepicker-done waves-effect" type="button"></button>',
'</div>',
'</div>',
'</div>',
'</div>',
'</div>'
].join('');
M.Datepicker = Datepicker;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Datepicker, 'datepicker', 'M_Datepicker');
}
})(cash);

View File

@ -0,0 +1,617 @@
(function($, anim) {
'use strict';
let _defaults = {
alignment: 'left',
autoFocus: true,
constrainWidth: true,
container: null,
coverTrigger: true,
closeOnClick: true,
hover: false,
inDuration: 150,
outDuration: 250,
onOpenStart: null,
onOpenEnd: null,
onCloseStart: null,
onCloseEnd: null,
onItemClick: null
};
/**
* @class
*/
class Dropdown extends Component {
constructor(el, options) {
super(Dropdown, el, options);
this.el.M_Dropdown = this;
Dropdown._dropdowns.push(this);
this.id = M.getIdFromTrigger(el);
this.dropdownEl = document.getElementById(this.id);
this.$dropdownEl = $(this.dropdownEl);
/**
* Options for the dropdown
* @member Dropdown#options
* @prop {String} [alignment='left'] - Edge which the dropdown is aligned to
* @prop {Boolean} [autoFocus=true] - Automatically focus dropdown el for keyboard
* @prop {Boolean} [constrainWidth=true] - Constrain width to width of the button
* @prop {Element} container - Container element to attach dropdown to (optional)
* @prop {Boolean} [coverTrigger=true] - Place dropdown over trigger
* @prop {Boolean} [closeOnClick=true] - Close on click of dropdown item
* @prop {Boolean} [hover=false] - Open dropdown on hover
* @prop {Number} [inDuration=150] - Duration of open animation in ms
* @prop {Number} [outDuration=250] - Duration of close animation in ms
* @prop {Function} onOpenStart - Function called when dropdown starts opening
* @prop {Function} onOpenEnd - Function called when dropdown finishes opening
* @prop {Function} onCloseStart - Function called when dropdown starts closing
* @prop {Function} onCloseEnd - Function called when dropdown finishes closing
*/
this.options = $.extend({}, Dropdown.defaults, options);
/**
* Describes open/close state of dropdown
* @type {Boolean}
*/
this.isOpen = false;
/**
* Describes if dropdown content is scrollable
* @type {Boolean}
*/
this.isScrollable = false;
/**
* Describes if touch moving on dropdown content
* @type {Boolean}
*/
this.isTouchMoving = false;
this.focusedIndex = -1;
this.filterQuery = [];
// Move dropdown-content after dropdown-trigger
if (!!this.options.container) {
$(this.options.container).append(this.dropdownEl);
} else {
this.$el.after(this.dropdownEl);
}
this._makeDropdownFocusable();
this._resetFilterQueryBound = this._resetFilterQuery.bind(this);
this._handleDocumentClickBound = this._handleDocumentClick.bind(this);
this._handleDocumentTouchmoveBound = this._handleDocumentTouchmove.bind(this);
this._handleDropdownClickBound = this._handleDropdownClick.bind(this);
this._handleDropdownKeydownBound = this._handleDropdownKeydown.bind(this);
this._handleTriggerKeydownBound = this._handleTriggerKeydown.bind(this);
this._setupEventHandlers();
}
static get defaults() {
return _defaults;
}
static init(els, options) {
return super.init(this, els, options);
}
/**
* Get Instance
*/
static getInstance(el) {
let domElem = !!el.jquery ? el[0] : el;
return domElem.M_Dropdown;
}
/**
* Teardown component
*/
destroy() {
this._resetDropdownStyles();
this._removeEventHandlers();
Dropdown._dropdowns.splice(Dropdown._dropdowns.indexOf(this), 1);
this.el.M_Dropdown = undefined;
}
/**
* Setup Event Handlers
*/
_setupEventHandlers() {
// Trigger keydown handler
this.el.addEventListener('keydown', this._handleTriggerKeydownBound);
// Item click handler
this.dropdownEl.addEventListener('click', this._handleDropdownClickBound);
// Hover event handlers
if (this.options.hover) {
this._handleMouseEnterBound = this._handleMouseEnter.bind(this);
this.el.addEventListener('mouseenter', this._handleMouseEnterBound);
this._handleMouseLeaveBound = this._handleMouseLeave.bind(this);
this.el.addEventListener('mouseleave', this._handleMouseLeaveBound);
this.dropdownEl.addEventListener('mouseleave', this._handleMouseLeaveBound);
// Click event handlers
} else {
this._handleClickBound = this._handleClick.bind(this);
this.el.addEventListener('click', this._handleClickBound);
}
}
/**
* Remove Event Handlers
*/
_removeEventHandlers() {
this.el.removeEventListener('keydown', this._handleTriggerKeydownBound);
this.dropdownEl.removeEventListener('click', this._handleDropdownClickBound);
if (this.options.hover) {
this.el.removeEventListener('mouseenter', this._handleMouseEnterBound);
this.el.removeEventListener('mouseleave', this._handleMouseLeaveBound);
this.dropdownEl.removeEventListener('mouseleave', this._handleMouseLeaveBound);
} else {
this.el.removeEventListener('click', this._handleClickBound);
}
}
_setupTemporaryEventHandlers() {
// Use capture phase event handler to prevent click
document.body.addEventListener('click', this._handleDocumentClickBound, true);
document.body.addEventListener('touchend', this._handleDocumentClickBound);
document.body.addEventListener('touchmove', this._handleDocumentTouchmoveBound);
this.dropdownEl.addEventListener('keydown', this._handleDropdownKeydownBound);
}
_removeTemporaryEventHandlers() {
// Use capture phase event handler to prevent click
document.body.removeEventListener('click', this._handleDocumentClickBound, true);
document.body.removeEventListener('touchend', this._handleDocumentClickBound);
document.body.removeEventListener('touchmove', this._handleDocumentTouchmoveBound);
this.dropdownEl.removeEventListener('keydown', this._handleDropdownKeydownBound);
}
_handleClick(e) {
e.preventDefault();
this.open();
}
_handleMouseEnter() {
this.open();
}
_handleMouseLeave(e) {
let toEl = e.toElement || e.relatedTarget;
let leaveToDropdownContent = !!$(toEl).closest('.dropdown-content').length;
let leaveToActiveDropdownTrigger = false;
let $closestTrigger = $(toEl).closest('.dropdown-trigger');
if (
$closestTrigger.length &&
!!$closestTrigger[0].M_Dropdown &&
$closestTrigger[0].M_Dropdown.isOpen
) {
leaveToActiveDropdownTrigger = true;
}
// Close hover dropdown if mouse did not leave to either active dropdown-trigger or dropdown-content
if (!leaveToActiveDropdownTrigger && !leaveToDropdownContent) {
this.close();
}
}
_handleDocumentClick(e) {
let $target = $(e.target);
if (
this.options.closeOnClick &&
$target.closest('.dropdown-content').length &&
!this.isTouchMoving
) {
// isTouchMoving to check if scrolling on mobile.
setTimeout(() => {
this.close();
}, 0);
} else if (
$target.closest('.dropdown-trigger').length ||
!$target.closest('.dropdown-content').length
) {
setTimeout(() => {
this.close();
}, 0);
}
this.isTouchMoving = false;
}
_handleTriggerKeydown(e) {
// ARROW DOWN OR ENTER WHEN SELECT IS CLOSED - open Dropdown
if ((e.which === M.keys.ARROW_DOWN || e.which === M.keys.ENTER) && !this.isOpen) {
e.preventDefault();
this.open();
}
}
/**
* Handle Document Touchmove
* @param {Event} e
*/
_handleDocumentTouchmove(e) {
let $target = $(e.target);
if ($target.closest('.dropdown-content').length) {
this.isTouchMoving = true;
}
}
/**
* Handle Dropdown Click
* @param {Event} e
*/
_handleDropdownClick(e) {
// onItemClick callback
if (typeof this.options.onItemClick === 'function') {
let itemEl = $(e.target).closest('li')[0];
this.options.onItemClick.call(this, itemEl);
}
}
/**
* Handle Dropdown Keydown
* @param {Event} e
*/
_handleDropdownKeydown(e) {
if (e.which === M.keys.TAB) {
e.preventDefault();
this.close();
// Navigate down dropdown list
} else if ((e.which === M.keys.ARROW_DOWN || e.which === M.keys.ARROW_UP) && this.isOpen) {
e.preventDefault();
let direction = e.which === M.keys.ARROW_DOWN ? 1 : -1;
let newFocusedIndex = this.focusedIndex;
let foundNewIndex = false;
do {
newFocusedIndex = newFocusedIndex + direction;
if (
!!this.dropdownEl.children[newFocusedIndex] &&
this.dropdownEl.children[newFocusedIndex].tabIndex !== -1
) {
foundNewIndex = true;
break;
}
} while (newFocusedIndex < this.dropdownEl.children.length && newFocusedIndex >= 0);
if (foundNewIndex) {
this.focusedIndex = newFocusedIndex;
this._focusFocusedItem();
}
// ENTER selects choice on focused item
} else if (e.which === M.keys.ENTER && this.isOpen) {
// Search for <a> and <button>
let focusedElement = this.dropdownEl.children[this.focusedIndex];
let $activatableElement = $(focusedElement)
.find('a, button')
.first();
// Click a or button tag if exists, otherwise click li tag
if (!!$activatableElement.length) {
$activatableElement[0].click();
} else if (!!focusedElement) {
focusedElement.click();
}
// Close dropdown on ESC
} else if (e.which === M.keys.ESC && this.isOpen) {
e.preventDefault();
this.close();
}
// CASE WHEN USER TYPE LETTERS
let letter = String.fromCharCode(e.which).toLowerCase(),
nonLetters = [9, 13, 27, 38, 40];
if (letter && nonLetters.indexOf(e.which) === -1) {
this.filterQuery.push(letter);
let string = this.filterQuery.join(''),
newOptionEl = $(this.dropdownEl)
.find('li')
.filter((el) => {
return (
$(el)
.text()
.toLowerCase()
.indexOf(string) === 0
);
})[0];
if (newOptionEl) {
this.focusedIndex = $(newOptionEl).index();
this._focusFocusedItem();
}
}
this.filterTimeout = setTimeout(this._resetFilterQueryBound, 1000);
}
/**
* Setup dropdown
*/
_resetFilterQuery() {
this.filterQuery = [];
}
_resetDropdownStyles() {
this.$dropdownEl.css({
display: '',
width: '',
height: '',
left: '',
top: '',
'transform-origin': '',
transform: '',
opacity: ''
});
}
_makeDropdownFocusable() {
// Needed for arrow key navigation
this.dropdownEl.tabIndex = 0;
// Only set tabindex if it hasn't been set by user
$(this.dropdownEl)
.children()
.each(function(el) {
if (!el.getAttribute('tabindex')) {
el.setAttribute('tabindex', 0);
}
});
}
_focusFocusedItem() {
if (
this.focusedIndex >= 0 &&
this.focusedIndex < this.dropdownEl.children.length &&
this.options.autoFocus
) {
this.dropdownEl.children[this.focusedIndex].focus();
}
}
_getDropdownPosition() {
let offsetParentBRect = this.el.offsetParent.getBoundingClientRect();
let triggerBRect = this.el.getBoundingClientRect();
let dropdownBRect = this.dropdownEl.getBoundingClientRect();
let idealHeight = dropdownBRect.height;
let idealWidth = dropdownBRect.width;
let idealXPos = triggerBRect.left - dropdownBRect.left;
let idealYPos = triggerBRect.top - dropdownBRect.top;
let dropdownBounds = {
left: idealXPos,
top: idealYPos,
height: idealHeight,
width: idealWidth
};
// Countainer here will be closest ancestor with overflow: hidden
let closestOverflowParent = !!this.dropdownEl.offsetParent
? this.dropdownEl.offsetParent
: this.dropdownEl.parentNode;
let alignments = M.checkPossibleAlignments(
this.el,
closestOverflowParent,
dropdownBounds,
this.options.coverTrigger ? 0 : triggerBRect.height
);
let verticalAlignment = 'top';
let horizontalAlignment = this.options.alignment;
idealYPos += this.options.coverTrigger ? 0 : triggerBRect.height;
// Reset isScrollable
this.isScrollable = false;
if (!alignments.top) {
if (alignments.bottom) {
verticalAlignment = 'bottom';
} else {
this.isScrollable = true;
// Determine which side has most space and cutoff at correct height
if (alignments.spaceOnTop > alignments.spaceOnBottom) {
verticalAlignment = 'bottom';
idealHeight += alignments.spaceOnTop;
idealYPos -= alignments.spaceOnTop;
} else {
idealHeight += alignments.spaceOnBottom;
}
}
}
// If preferred horizontal alignment is possible
if (!alignments[horizontalAlignment]) {
let oppositeAlignment = horizontalAlignment === 'left' ? 'right' : 'left';
if (alignments[oppositeAlignment]) {
horizontalAlignment = oppositeAlignment;
} else {
// Determine which side has most space and cutoff at correct height
if (alignments.spaceOnLeft > alignments.spaceOnRight) {
horizontalAlignment = 'right';
idealWidth += alignments.spaceOnLeft;
idealXPos -= alignments.spaceOnLeft;
} else {
horizontalAlignment = 'left';
idealWidth += alignments.spaceOnRight;
}
}
}
if (verticalAlignment === 'bottom') {
idealYPos =
idealYPos - dropdownBRect.height + (this.options.coverTrigger ? triggerBRect.height : 0);
}
if (horizontalAlignment === 'right') {
idealXPos = idealXPos - dropdownBRect.width + triggerBRect.width;
}
return {
x: idealXPos,
y: idealYPos,
verticalAlignment: verticalAlignment,
horizontalAlignment: horizontalAlignment,
height: idealHeight,
width: idealWidth
};
}
/**
* Animate in dropdown
*/
_animateIn() {
anim.remove(this.dropdownEl);
anim({
targets: this.dropdownEl,
opacity: {
value: [0, 1],
easing: 'easeOutQuad'
},
scaleX: [0.3, 1],
scaleY: [0.3, 1],
duration: this.options.inDuration,
easing: 'easeOutQuint',
complete: (anim) => {
if (this.options.autoFocus) {
this.dropdownEl.focus();
}
// onOpenEnd callback
if (typeof this.options.onOpenEnd === 'function') {
this.options.onOpenEnd.call(this, this.el);
}
}
});
}
/**
* Animate out dropdown
*/
_animateOut() {
anim.remove(this.dropdownEl);
anim({
targets: this.dropdownEl,
opacity: {
value: 0,
easing: 'easeOutQuint'
},
scaleX: 0.3,
scaleY: 0.3,
duration: this.options.outDuration,
easing: 'easeOutQuint',
complete: (anim) => {
this._resetDropdownStyles();
// onCloseEnd callback
if (typeof this.options.onCloseEnd === 'function') {
this.options.onCloseEnd.call(this, this.el);
}
}
});
}
/**
* Place dropdown
*/
_placeDropdown() {
// Set width before calculating positionInfo
let idealWidth = this.options.constrainWidth
? this.el.getBoundingClientRect().width
: this.dropdownEl.getBoundingClientRect().width;
this.dropdownEl.style.width = idealWidth + 'px';
let positionInfo = this._getDropdownPosition();
this.dropdownEl.style.left = positionInfo.x + 'px';
this.dropdownEl.style.top = positionInfo.y + 'px';
this.dropdownEl.style.height = positionInfo.height + 'px';
this.dropdownEl.style.width = positionInfo.width + 'px';
this.dropdownEl.style.transformOrigin = `${
positionInfo.horizontalAlignment === 'left' ? '0' : '100%'
} ${positionInfo.verticalAlignment === 'top' ? '0' : '100%'}`;
}
/**
* Open Dropdown
*/
open() {
if (this.isOpen) {
return;
}
this.isOpen = true;
// onOpenStart callback
if (typeof this.options.onOpenStart === 'function') {
this.options.onOpenStart.call(this, this.el);
}
// Reset styles
this._resetDropdownStyles();
this.dropdownEl.style.display = 'block';
this._placeDropdown();
this._animateIn();
this._setupTemporaryEventHandlers();
}
/**
* Close Dropdown
*/
close() {
if (!this.isOpen) {
return;
}
this.isOpen = false;
this.focusedIndex = -1;
// onCloseStart callback
if (typeof this.options.onCloseStart === 'function') {
this.options.onCloseStart.call(this, this.el);
}
this._animateOut();
this._removeTemporaryEventHandlers();
if (this.options.autoFocus) {
this.el.focus();
}
}
/**
* Recalculate dimensions
*/
recalculateDimensions() {
if (this.isOpen) {
this.$dropdownEl.css({
width: '',
height: '',
left: '',
top: '',
'transform-origin': ''
});
this._placeDropdown();
}
}
}
/**
* @static
* @memberof Dropdown
*/
Dropdown._dropdowns = [];
M.Dropdown = Dropdown;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Dropdown, 'dropdown', 'M_Dropdown');
}
})(cash, M.anime);

275
resources/sass/materialize/js/forms.js vendored Normal file
View File

@ -0,0 +1,275 @@
(function($) {
// Function to update labels of text fields
M.updateTextFields = function() {
let input_selector =
'input[type=text], input[type=password], input[type=email], input[type=url], input[type=tel], input[type=number], input[type=search], input[type=date], input[type=time], textarea';
$(input_selector).each(function(element, index) {
let $this = $(this);
if (
element.value.length > 0 ||
$(element).is(':focus') ||
element.autofocus ||
$this.attr('placeholder') !== null
) {
$this.siblings('label').addClass('active');
} else if (element.validity) {
$this.siblings('label').toggleClass('active', element.validity.badInput === true);
} else {
$this.siblings('label').removeClass('active');
}
});
};
M.validate_field = function(object) {
let hasLength = object.attr('data-length') !== null;
let lenAttr = parseInt(object.attr('data-length'));
let len = object[0].value.length;
if (len === 0 && object[0].validity.badInput === false && !object.is(':required')) {
if (object.hasClass('validate')) {
object.removeClass('valid');
object.removeClass('invalid');
}
} else {
if (object.hasClass('validate')) {
// Check for character counter attributes
if (
(object.is(':valid') && hasLength && len <= lenAttr) ||
(object.is(':valid') && !hasLength)
) {
object.removeClass('invalid');
object.addClass('valid');
} else {
object.removeClass('valid');
object.addClass('invalid');
}
}
}
};
M.textareaAutoResize = function($textarea) {
// Wrap if native element
if ($textarea instanceof Element) {
$textarea = $($textarea);
}
if (!$textarea.length) {
console.error('No textarea element found');
return;
}
// Textarea Auto Resize
let hiddenDiv = $('.hiddendiv').first();
if (!hiddenDiv.length) {
hiddenDiv = $('<div class="hiddendiv common"></div>');
$('body').append(hiddenDiv);
}
// Set font properties of hiddenDiv
let fontFamily = $textarea.css('font-family');
let fontSize = $textarea.css('font-size');
let lineHeight = $textarea.css('line-height');
// Firefox can't handle padding shorthand.
let paddingTop = $textarea.css('padding-top');
let paddingRight = $textarea.css('padding-right');
let paddingBottom = $textarea.css('padding-bottom');
let paddingLeft = $textarea.css('padding-left');
if (fontSize) {
hiddenDiv.css('font-size', fontSize);
}
if (fontFamily) {
hiddenDiv.css('font-family', fontFamily);
}
if (lineHeight) {
hiddenDiv.css('line-height', lineHeight);
}
if (paddingTop) {
hiddenDiv.css('padding-top', paddingTop);
}
if (paddingRight) {
hiddenDiv.css('padding-right', paddingRight);
}
if (paddingBottom) {
hiddenDiv.css('padding-bottom', paddingBottom);
}
if (paddingLeft) {
hiddenDiv.css('padding-left', paddingLeft);
}
// Set original-height, if none
if (!$textarea.data('original-height')) {
$textarea.data('original-height', $textarea.height());
}
if ($textarea.attr('wrap') === 'off') {
hiddenDiv.css('overflow-wrap', 'normal').css('white-space', 'pre');
}
hiddenDiv.text($textarea[0].value + '\n');
let content = hiddenDiv.html().replace(/\n/g, '<br>');
hiddenDiv.html(content);
// When textarea is hidden, width goes crazy.
// Approximate with half of window size
if ($textarea[0].offsetWidth > 0 && $textarea[0].offsetHeight > 0) {
hiddenDiv.css('width', $textarea.width() + 'px');
} else {
hiddenDiv.css('width', window.innerWidth / 2 + 'px');
}
/**
* Resize if the new height is greater than the
* original height of the textarea
*/
if ($textarea.data('original-height') <= hiddenDiv.innerHeight()) {
$textarea.css('height', hiddenDiv.innerHeight() + 'px');
} else if ($textarea[0].value.length < $textarea.data('previous-length')) {
/**
* In case the new height is less than original height, it
* means the textarea has less text than before
* So we set the height to the original one
*/
$textarea.css('height', $textarea.data('original-height') + 'px');
}
$textarea.data('previous-length', $textarea[0].value.length);
};
$(document).ready(function() {
// Text based inputs
let input_selector =
'input[type=text], input[type=password], input[type=email], input[type=url], input[type=tel], input[type=number], input[type=search], input[type=date], input[type=time], textarea';
// Add active if form auto complete
$(document).on('change', input_selector, function() {
if (this.value.length !== 0 || $(this).attr('placeholder') !== null) {
$(this)
.siblings('label')
.addClass('active');
}
M.validate_field($(this));
});
// Add active if input element has been pre-populated on document ready
$(document).ready(function() {
M.updateTextFields();
});
// HTML DOM FORM RESET handling
$(document).on('reset', function(e) {
let formReset = $(e.target);
if (formReset.is('form')) {
formReset
.find(input_selector)
.removeClass('valid')
.removeClass('invalid');
formReset.find(input_selector).each(function(e) {
if (this.value.length) {
$(this)
.siblings('label')
.removeClass('active');
}
});
// Reset select (after native reset)
setTimeout(function() {
formReset.find('select').each(function() {
// check if initialized
if (this.M_FormSelect) {
$(this).trigger('change');
}
});
}, 0);
}
});
/**
* Add active when element has focus
* @param {Event} e
*/
document.addEventListener(
'focus',
function(e) {
if ($(e.target).is(input_selector)) {
$(e.target)
.siblings('label, .prefix')
.addClass('active');
}
},
true
);
/**
* Remove active when element is blurred
* @param {Event} e
*/
document.addEventListener(
'blur',
function(e) {
let $inputElement = $(e.target);
if ($inputElement.is(input_selector)) {
let selector = '.prefix';
if (
$inputElement[0].value.length === 0 &&
$inputElement[0].validity.badInput !== true &&
$inputElement.attr('placeholder') === null
) {
selector += ', label';
}
$inputElement.siblings(selector).removeClass('active');
M.validate_field($inputElement);
}
},
true
);
// Radio and Checkbox focus class
let radio_checkbox = 'input[type=radio], input[type=checkbox]';
$(document).on('keyup', radio_checkbox, function(e) {
// TAB, check if tabbing to radio or checkbox.
if (e.which === M.keys.TAB) {
$(this).addClass('tabbed');
let $this = $(this);
$this.one('blur', function(e) {
$(this).removeClass('tabbed');
});
return;
}
});
let text_area_selector = '.materialize-textarea';
$(text_area_selector).each(function() {
let $textarea = $(this);
/**
* Resize textarea on document load after storing
* the original height and the original length
*/
$textarea.data('original-height', $textarea.height());
$textarea.data('previous-length', this.value.length);
M.textareaAutoResize($textarea);
});
$(document).on('keyup', text_area_selector, function() {
M.textareaAutoResize($(this));
});
$(document).on('keydown', text_area_selector, function() {
M.textareaAutoResize($(this));
});
// File Input Path
$(document).on('change', '.file-field input[type="file"]', function() {
let file_field = $(this).closest('.file-field');
let path_input = file_field.find('input.file-path');
let files = $(this)[0].files;
let file_names = [];
for (let i = 0; i < files.length; i++) {
file_names.push(files[i].name);
}
path_input[0].value = file_names.join(', ');
path_input.trigger('change');
});
}); // End of $(document).ready
})(cash);

427
resources/sass/materialize/js/global.js vendored Normal file
View File

@ -0,0 +1,427 @@
// Required for Meteor package, the use of window prevents export by Meteor
(function(window) {
if (window.Package) {
M = {};
} else {
window.M = {};
}
// Check for jQuery
M.jQueryLoaded = !!window.jQuery;
})(window);
// AMD
if (typeof define === 'function' && define.amd) {
define('M', [], function() {
return M;
});
// Common JS
} else if (typeof exports !== 'undefined' && !exports.nodeType) {
if (typeof module !== 'undefined' && !module.nodeType && module.exports) {
exports = module.exports = M;
}
exports.default = M;
}
M.version = '1.0.0';
M.keys = {
TAB: 9,
ENTER: 13,
ESC: 27,
ARROW_UP: 38,
ARROW_DOWN: 40
};
/**
* TabPress Keydown handler
*/
M.tabPressed = false;
M.keyDown = false;
let docHandleKeydown = function(e) {
M.keyDown = true;
if (e.which === M.keys.TAB || e.which === M.keys.ARROW_DOWN || e.which === M.keys.ARROW_UP) {
M.tabPressed = true;
}
};
let docHandleKeyup = function(e) {
M.keyDown = false;
if (e.which === M.keys.TAB || e.which === M.keys.ARROW_DOWN || e.which === M.keys.ARROW_UP) {
M.tabPressed = false;
}
};
let docHandleFocus = function(e) {
if (M.keyDown) {
document.body.classList.add('keyboard-focused');
}
};
let docHandleBlur = function(e) {
document.body.classList.remove('keyboard-focused');
};
document.addEventListener('keydown', docHandleKeydown, true);
document.addEventListener('keyup', docHandleKeyup, true);
document.addEventListener('focus', docHandleFocus, true);
document.addEventListener('blur', docHandleBlur, true);
/**
* Initialize jQuery wrapper for plugin
* @param {Class} plugin javascript class
* @param {string} pluginName jQuery plugin name
* @param {string} classRef Class reference name
*/
M.initializeJqueryWrapper = function(plugin, pluginName, classRef) {
jQuery.fn[pluginName] = function(methodOrOptions) {
// Call plugin method if valid method name is passed in
if (plugin.prototype[methodOrOptions]) {
let params = Array.prototype.slice.call(arguments, 1);
// Getter methods
if (methodOrOptions.slice(0, 3) === 'get') {
let instance = this.first()[0][classRef];
return instance[methodOrOptions].apply(instance, params);
}
// Void methods
return this.each(function() {
let instance = this[classRef];
instance[methodOrOptions].apply(instance, params);
});
// Initialize plugin if options or no argument is passed in
} else if (typeof methodOrOptions === 'object' || !methodOrOptions) {
plugin.init(this, arguments[0]);
return this;
}
// Return error if an unrecognized method name is passed in
jQuery.error(`Method ${methodOrOptions} does not exist on jQuery.${pluginName}`);
};
};
/**
* Automatically initialize components
* @param {Element} context DOM Element to search within for components
*/
M.AutoInit = function(context) {
// Use document.body if no context is given
let root = !!context ? context : document.body;
let registry = {
Autocomplete: root.querySelectorAll('.autocomplete:not(.no-autoinit)'),
Carousel: root.querySelectorAll('.carousel:not(.no-autoinit)'),
Chips: root.querySelectorAll('.chips:not(.no-autoinit)'),
Collapsible: root.querySelectorAll('.collapsible:not(.no-autoinit)'),
Datepicker: root.querySelectorAll('.datepicker:not(.no-autoinit)'),
Dropdown: root.querySelectorAll('.dropdown-trigger:not(.no-autoinit)'),
Materialbox: root.querySelectorAll('.materialboxed:not(.no-autoinit)'),
Modal: root.querySelectorAll('.modal:not(.no-autoinit)'),
Parallax: root.querySelectorAll('.parallax:not(.no-autoinit)'),
Pushpin: root.querySelectorAll('.pushpin:not(.no-autoinit)'),
ScrollSpy: root.querySelectorAll('.scrollspy:not(.no-autoinit)'),
FormSelect: root.querySelectorAll('select:not(.no-autoinit)'),
Sidenav: root.querySelectorAll('.sidenav:not(.no-autoinit)'),
Tabs: root.querySelectorAll('.tabs:not(.no-autoinit)'),
TapTarget: root.querySelectorAll('.tap-target:not(.no-autoinit)'),
Timepicker: root.querySelectorAll('.timepicker:not(.no-autoinit)'),
Tooltip: root.querySelectorAll('.tooltipped:not(.no-autoinit)'),
FloatingActionButton: root.querySelectorAll('.fixed-action-btn:not(.no-autoinit)')
};
for (let pluginName in registry) {
let plugin = M[pluginName];
plugin.init(registry[pluginName]);
}
};
/**
* Generate approximated selector string for a jQuery object
* @param {jQuery} obj jQuery object to be parsed
* @returns {string}
*/
M.objectSelectorString = function(obj) {
let tagStr = obj.prop('tagName') || '';
let idStr = obj.attr('id') || '';
let classStr = obj.attr('class') || '';
return (tagStr + idStr + classStr).replace(/\s/g, '');
};
// Unique Random ID
M.guid = (function() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return function() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
};
})();
/**
* Escapes hash from special characters
* @param {string} hash String returned from this.hash
* @returns {string}
*/
M.escapeHash = function(hash) {
return hash.replace(/(:|\.|\[|\]|,|=|\/)/g, '\\$1');
};
M.elementOrParentIsFixed = function(element) {
let $element = $(element);
let $checkElements = $element.add($element.parents());
let isFixed = false;
$checkElements.each(function() {
if ($(this).css('position') === 'fixed') {
isFixed = true;
return false;
}
});
return isFixed;
};
/**
* @typedef {Object} Edges
* @property {Boolean} top If the top edge was exceeded
* @property {Boolean} right If the right edge was exceeded
* @property {Boolean} bottom If the bottom edge was exceeded
* @property {Boolean} left If the left edge was exceeded
*/
/**
* @typedef {Object} Bounding
* @property {Number} left left offset coordinate
* @property {Number} top top offset coordinate
* @property {Number} width
* @property {Number} height
*/
/**
* Escapes hash from special characters
* @param {Element} container Container element that acts as the boundary
* @param {Bounding} bounding element bounding that is being checked
* @param {Number} offset offset from edge that counts as exceeding
* @returns {Edges}
*/
M.checkWithinContainer = function(container, bounding, offset) {
let edges = {
top: false,
right: false,
bottom: false,
left: false
};
let containerRect = container.getBoundingClientRect();
// If body element is smaller than viewport, use viewport height instead.
let containerBottom =
container === document.body
? Math.max(containerRect.bottom, window.innerHeight)
: containerRect.bottom;
let scrollLeft = container.scrollLeft;
let scrollTop = container.scrollTop;
let scrolledX = bounding.left - scrollLeft;
let scrolledY = bounding.top - scrollTop;
// Check for container and viewport for each edge
if (scrolledX < containerRect.left + offset || scrolledX < offset) {
edges.left = true;
}
if (
scrolledX + bounding.width > containerRect.right - offset ||
scrolledX + bounding.width > window.innerWidth - offset
) {
edges.right = true;
}
if (scrolledY < containerRect.top + offset || scrolledY < offset) {
edges.top = true;
}
if (
scrolledY + bounding.height > containerBottom - offset ||
scrolledY + bounding.height > window.innerHeight - offset
) {
edges.bottom = true;
}
return edges;
};
M.checkPossibleAlignments = function(el, container, bounding, offset) {
let canAlign = {
top: true,
right: true,
bottom: true,
left: true,
spaceOnTop: null,
spaceOnRight: null,
spaceOnBottom: null,
spaceOnLeft: null
};
let containerAllowsOverflow = getComputedStyle(container).overflow === 'visible';
let containerRect = container.getBoundingClientRect();
let containerHeight = Math.min(containerRect.height, window.innerHeight);
let containerWidth = Math.min(containerRect.width, window.innerWidth);
let elOffsetRect = el.getBoundingClientRect();
let scrollLeft = container.scrollLeft;
let scrollTop = container.scrollTop;
let scrolledX = bounding.left - scrollLeft;
let scrolledYTopEdge = bounding.top - scrollTop;
let scrolledYBottomEdge = bounding.top + elOffsetRect.height - scrollTop;
// Check for container and viewport for left
canAlign.spaceOnRight = !containerAllowsOverflow
? containerWidth - (scrolledX + bounding.width)
: window.innerWidth - (elOffsetRect.left + bounding.width);
if (canAlign.spaceOnRight < 0) {
canAlign.left = false;
}
// Check for container and viewport for Right
canAlign.spaceOnLeft = !containerAllowsOverflow
? scrolledX - bounding.width + elOffsetRect.width
: elOffsetRect.right - bounding.width;
if (canAlign.spaceOnLeft < 0) {
canAlign.right = false;
}
// Check for container and viewport for Top
canAlign.spaceOnBottom = !containerAllowsOverflow
? containerHeight - (scrolledYTopEdge + bounding.height + offset)
: window.innerHeight - (elOffsetRect.top + bounding.height + offset);
if (canAlign.spaceOnBottom < 0) {
canAlign.top = false;
}
// Check for container and viewport for Bottom
canAlign.spaceOnTop = !containerAllowsOverflow
? scrolledYBottomEdge - (bounding.height - offset)
: elOffsetRect.bottom - (bounding.height + offset);
if (canAlign.spaceOnTop < 0) {
canAlign.bottom = false;
}
return canAlign;
};
M.getOverflowParent = function(element) {
if (element == null) {
return null;
}
if (element === document.body || getComputedStyle(element).overflow !== 'visible') {
return element;
}
return M.getOverflowParent(element.parentElement);
};
/**
* Gets id of component from a trigger
* @param {Element} trigger trigger
* @returns {string}
*/
M.getIdFromTrigger = function(trigger) {
let id = trigger.getAttribute('data-target');
if (!id) {
id = trigger.getAttribute('href');
if (id) {
id = id.slice(1);
} else {
id = '';
}
}
return id;
};
/**
* Multi browser support for document scroll top
* @returns {Number}
*/
M.getDocumentScrollTop = function() {
return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
};
/**
* Multi browser support for document scroll left
* @returns {Number}
*/
M.getDocumentScrollLeft = function() {
return window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
};
/**
* @typedef {Object} Edges
* @property {Boolean} top If the top edge was exceeded
* @property {Boolean} right If the right edge was exceeded
* @property {Boolean} bottom If the bottom edge was exceeded
* @property {Boolean} left If the left edge was exceeded
*/
/**
* @typedef {Object} Bounding
* @property {Number} left left offset coordinate
* @property {Number} top top offset coordinate
* @property {Number} width
* @property {Number} height
*/
/**
* Get time in ms
* @license https://raw.github.com/jashkenas/underscore/master/LICENSE
* @type {function}
* @return {number}
*/
let getTime =
Date.now ||
function() {
return new Date().getTime();
};
/**
* Returns a function, that, when invoked, will only be triggered at most once
* during a given window of time. Normally, the throttled function will run
* as much as it can, without ever going more than once per `wait` duration;
* but if you'd like to disable the execution on the leading edge, pass
* `{leading: false}`. To disable execution on the trailing edge, ditto.
* @license https://raw.github.com/jashkenas/underscore/master/LICENSE
* @param {function} func
* @param {number} wait
* @param {Object=} options
* @returns {Function}
*/
M.throttle = function(func, wait, options) {
let context, args, result;
let timeout = null;
let previous = 0;
options || (options = {});
let later = function() {
previous = options.leading === false ? 0 : getTime();
timeout = null;
result = func.apply(context, args);
context = args = null;
};
return function() {
let now = getTime();
if (!previous && options.leading === false) previous = now;
let remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};

View File

@ -0,0 +1,453 @@
(function($, anim) {
'use strict';
let _defaults = {
inDuration: 275,
outDuration: 200,
onOpenStart: null,
onOpenEnd: null,
onCloseStart: null,
onCloseEnd: null
};
/**
* @class
*
*/
class Materialbox extends Component {
/**
* Construct Materialbox instance
* @constructor
* @param {Element} el
* @param {Object} options
*/
constructor(el, options) {
super(Materialbox, el, options);
this.el.M_Materialbox = this;
/**
* Options for the modal
* @member Materialbox#options
* @prop {Number} [inDuration=275] - Length in ms of enter transition
* @prop {Number} [outDuration=200] - Length in ms of exit transition
* @prop {Function} onOpenStart - Callback function called before materialbox is opened
* @prop {Function} onOpenEnd - Callback function called after materialbox is opened
* @prop {Function} onCloseStart - Callback function called before materialbox is closed
* @prop {Function} onCloseEnd - Callback function called after materialbox is closed
*/
this.options = $.extend({}, Materialbox.defaults, options);
this.overlayActive = false;
this.doneAnimating = true;
this.placeholder = $('<div></div>').addClass('material-placeholder');
this.originalWidth = 0;
this.originalHeight = 0;
this.originInlineStyles = this.$el.attr('style');
this.caption = this.el.getAttribute('data-caption') || '';
// Wrap
this.$el.before(this.placeholder);
this.placeholder.append(this.$el);
this._setupEventHandlers();
}
static get defaults() {
return _defaults;
}
static init(els, options) {
return super.init(this, els, options);
}
/**
* Get Instance
*/
static getInstance(el) {
let domElem = !!el.jquery ? el[0] : el;
return domElem.M_Materialbox;
}
/**
* Teardown component
*/
destroy() {
this._removeEventHandlers();
this.el.M_Materialbox = undefined;
// Unwrap image
$(this.placeholder)
.after(this.el)
.remove();
this.$el.removeAttr('style');
}
/**
* Setup Event Handlers
*/
_setupEventHandlers() {
this._handleMaterialboxClickBound = this._handleMaterialboxClick.bind(this);
this.el.addEventListener('click', this._handleMaterialboxClickBound);
}
/**
* Remove Event Handlers
*/
_removeEventHandlers() {
this.el.removeEventListener('click', this._handleMaterialboxClickBound);
}
/**
* Handle Materialbox Click
* @param {Event} e
*/
_handleMaterialboxClick(e) {
// If already modal, return to original
if (this.doneAnimating === false || (this.overlayActive && this.doneAnimating)) {
this.close();
} else {
this.open();
}
}
/**
* Handle Window Scroll
*/
_handleWindowScroll() {
if (this.overlayActive) {
this.close();
}
}
/**
* Handle Window Resize
*/
_handleWindowResize() {
if (this.overlayActive) {
this.close();
}
}
/**
* Handle Window Resize
* @param {Event} e
*/
_handleWindowEscape(e) {
// ESC key
if (e.keyCode === 27 && this.doneAnimating && this.overlayActive) {
this.close();
}
}
/**
* Find ancestors with overflow: hidden; and make visible
*/
_makeAncestorsOverflowVisible() {
this.ancestorsChanged = $();
let ancestor = this.placeholder[0].parentNode;
while (ancestor !== null && !$(ancestor).is(document)) {
let curr = $(ancestor);
if (curr.css('overflow') !== 'visible') {
curr.css('overflow', 'visible');
if (this.ancestorsChanged === undefined) {
this.ancestorsChanged = curr;
} else {
this.ancestorsChanged = this.ancestorsChanged.add(curr);
}
}
ancestor = ancestor.parentNode;
}
}
/**
* Animate image in
*/
_animateImageIn() {
let animOptions = {
targets: this.el,
height: [this.originalHeight, this.newHeight],
width: [this.originalWidth, this.newWidth],
left:
M.getDocumentScrollLeft() +
this.windowWidth / 2 -
this.placeholder.offset().left -
this.newWidth / 2,
top:
M.getDocumentScrollTop() +
this.windowHeight / 2 -
this.placeholder.offset().top -
this.newHeight / 2,
duration: this.options.inDuration,
easing: 'easeOutQuad',
complete: () => {
this.doneAnimating = true;
// onOpenEnd callback
if (typeof this.options.onOpenEnd === 'function') {
this.options.onOpenEnd.call(this, this.el);
}
}
};
// Override max-width or max-height if needed
this.maxWidth = this.$el.css('max-width');
this.maxHeight = this.$el.css('max-height');
if (this.maxWidth !== 'none') {
animOptions.maxWidth = this.newWidth;
}
if (this.maxHeight !== 'none') {
animOptions.maxHeight = this.newHeight;
}
anim(animOptions);
}
/**
* Animate image out
*/
_animateImageOut() {
let animOptions = {
targets: this.el,
width: this.originalWidth,
height: this.originalHeight,
left: 0,
top: 0,
duration: this.options.outDuration,
easing: 'easeOutQuad',
complete: () => {
this.placeholder.css({
height: '',
width: '',
position: '',
top: '',
left: ''
});
// Revert to width or height attribute
if (this.attrWidth) {
this.$el.attr('width', this.attrWidth);
}
if (this.attrHeight) {
this.$el.attr('height', this.attrHeight);
}
this.$el.removeAttr('style');
this.originInlineStyles && this.$el.attr('style', this.originInlineStyles);
// Remove class
this.$el.removeClass('active');
this.doneAnimating = true;
// Remove overflow overrides on ancestors
if (this.ancestorsChanged.length) {
this.ancestorsChanged.css('overflow', '');
}
// onCloseEnd callback
if (typeof this.options.onCloseEnd === 'function') {
this.options.onCloseEnd.call(this, this.el);
}
}
};
anim(animOptions);
}
/**
* Update open and close vars
*/
_updateVars() {
this.windowWidth = window.innerWidth;
this.windowHeight = window.innerHeight;
this.caption = this.el.getAttribute('data-caption') || '';
}
/**
* Open Materialbox
*/
open() {
this._updateVars();
this.originalWidth = this.el.getBoundingClientRect().width;
this.originalHeight = this.el.getBoundingClientRect().height;
// Set states
this.doneAnimating = false;
this.$el.addClass('active');
this.overlayActive = true;
// onOpenStart callback
if (typeof this.options.onOpenStart === 'function') {
this.options.onOpenStart.call(this, this.el);
}
// Set positioning for placeholder
this.placeholder.css({
width: this.placeholder[0].getBoundingClientRect().width + 'px',
height: this.placeholder[0].getBoundingClientRect().height + 'px',
position: 'relative',
top: 0,
left: 0
});
this._makeAncestorsOverflowVisible();
// Set css on origin
this.$el.css({
position: 'absolute',
'z-index': 1000,
'will-change': 'left, top, width, height'
});
// Change from width or height attribute to css
this.attrWidth = this.$el.attr('width');
this.attrHeight = this.$el.attr('height');
if (this.attrWidth) {
this.$el.css('width', this.attrWidth + 'px');
this.$el.removeAttr('width');
}
if (this.attrHeight) {
this.$el.css('width', this.attrHeight + 'px');
this.$el.removeAttr('height');
}
// Add overlay
this.$overlay = $('<div id="materialbox-overlay"></div>')
.css({
opacity: 0
})
.one('click', () => {
if (this.doneAnimating) {
this.close();
}
});
// Put before in origin image to preserve z-index layering.
this.$el.before(this.$overlay);
// Set dimensions if needed
let overlayOffset = this.$overlay[0].getBoundingClientRect();
this.$overlay.css({
width: this.windowWidth + 'px',
height: this.windowHeight + 'px',
left: -1 * overlayOffset.left + 'px',
top: -1 * overlayOffset.top + 'px'
});
anim.remove(this.el);
anim.remove(this.$overlay[0]);
// Animate Overlay
anim({
targets: this.$overlay[0],
opacity: 1,
duration: this.options.inDuration,
easing: 'easeOutQuad'
});
// Add and animate caption if it exists
if (this.caption !== '') {
if (this.$photocaption) {
anim.remove(this.$photoCaption[0]);
}
this.$photoCaption = $('<div class="materialbox-caption"></div>');
this.$photoCaption.text(this.caption);
$('body').append(this.$photoCaption);
this.$photoCaption.css({ display: 'inline' });
anim({
targets: this.$photoCaption[0],
opacity: 1,
duration: this.options.inDuration,
easing: 'easeOutQuad'
});
}
// Resize Image
let ratio = 0;
let widthPercent = this.originalWidth / this.windowWidth;
let heightPercent = this.originalHeight / this.windowHeight;
this.newWidth = 0;
this.newHeight = 0;
if (widthPercent > heightPercent) {
ratio = this.originalHeight / this.originalWidth;
this.newWidth = this.windowWidth * 0.9;
this.newHeight = this.windowWidth * 0.9 * ratio;
} else {
ratio = this.originalWidth / this.originalHeight;
this.newWidth = this.windowHeight * 0.9 * ratio;
this.newHeight = this.windowHeight * 0.9;
}
this._animateImageIn();
// Handle Exit triggers
this._handleWindowScrollBound = this._handleWindowScroll.bind(this);
this._handleWindowResizeBound = this._handleWindowResize.bind(this);
this._handleWindowEscapeBound = this._handleWindowEscape.bind(this);
window.addEventListener('scroll', this._handleWindowScrollBound);
window.addEventListener('resize', this._handleWindowResizeBound);
window.addEventListener('keyup', this._handleWindowEscapeBound);
}
/**
* Close Materialbox
*/
close() {
this._updateVars();
this.doneAnimating = false;
// onCloseStart callback
if (typeof this.options.onCloseStart === 'function') {
this.options.onCloseStart.call(this, this.el);
}
anim.remove(this.el);
anim.remove(this.$overlay[0]);
if (this.caption !== '') {
anim.remove(this.$photoCaption[0]);
}
// disable exit handlers
window.removeEventListener('scroll', this._handleWindowScrollBound);
window.removeEventListener('resize', this._handleWindowResizeBound);
window.removeEventListener('keyup', this._handleWindowEscapeBound);
anim({
targets: this.$overlay[0],
opacity: 0,
duration: this.options.outDuration,
easing: 'easeOutQuad',
complete: () => {
this.overlayActive = false;
this.$overlay.remove();
}
});
this._animateImageOut();
// Remove Caption + reset css settings on image
if (this.caption !== '') {
anim({
targets: this.$photoCaption[0],
opacity: 0,
duration: this.options.outDuration,
easing: 'easeOutQuad',
complete: () => {
this.$photoCaption.remove();
}
});
}
}
}
M.Materialbox = Materialbox;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Materialbox, 'materialbox', 'M_Materialbox');
}
})(cash, M.anime);

382
resources/sass/materialize/js/modal.js vendored Normal file
View File

@ -0,0 +1,382 @@
(function($, anim) {
'use strict';
let _defaults = {
opacity: 0.5,
inDuration: 250,
outDuration: 250,
onOpenStart: null,
onOpenEnd: null,
onCloseStart: null,
onCloseEnd: null,
preventScrolling: true,
dismissible: true,
startingTop: '4%',
endingTop: '10%'
};
/**
* @class
*
*/
class Modal extends Component {
/**
* Construct Modal instance and set up overlay
* @constructor
* @param {Element} el
* @param {Object} options
*/
constructor(el, options) {
super(Modal, el, options);
this.el.M_Modal = this;
/**
* Options for the modal
* @member Modal#options
* @prop {Number} [opacity=0.5] - Opacity of the modal overlay
* @prop {Number} [inDuration=250] - Length in ms of enter transition
* @prop {Number} [outDuration=250] - Length in ms of exit transition
* @prop {Function} onOpenStart - Callback function called before modal is opened
* @prop {Function} onOpenEnd - Callback function called after modal is opened
* @prop {Function} onCloseStart - Callback function called before modal is closed
* @prop {Function} onCloseEnd - Callback function called after modal is closed
* @prop {Boolean} [dismissible=true] - Allow modal to be dismissed by keyboard or overlay click
* @prop {String} [startingTop='4%'] - startingTop
* @prop {String} [endingTop='10%'] - endingTop
*/
this.options = $.extend({}, Modal.defaults, options);
/**
* Describes open/close state of modal
* @type {Boolean}
*/
this.isOpen = false;
this.id = this.$el.attr('id');
this._openingTrigger = undefined;
this.$overlay = $('<div class="modal-overlay"></div>');
this.el.tabIndex = 0;
this._nthModalOpened = 0;
Modal._count++;
this._setupEventHandlers();
}
static get defaults() {
return _defaults;
}
static init(els, options) {
return super.init(this, els, options);
}
/**
* Get Instance
*/
static getInstance(el) {
let domElem = !!el.jquery ? el[0] : el;
return domElem.M_Modal;
}
/**
* Teardown component
*/
destroy() {
Modal._count--;
this._removeEventHandlers();
this.el.removeAttribute('style');
this.$overlay.remove();
this.el.M_Modal = undefined;
}
/**
* Setup Event Handlers
*/
_setupEventHandlers() {
this._handleOverlayClickBound = this._handleOverlayClick.bind(this);
this._handleModalCloseClickBound = this._handleModalCloseClick.bind(this);
if (Modal._count === 1) {
document.body.addEventListener('click', this._handleTriggerClick);
}
this.$overlay[0].addEventListener('click', this._handleOverlayClickBound);
this.el.addEventListener('click', this._handleModalCloseClickBound);
}
/**
* Remove Event Handlers
*/
_removeEventHandlers() {
if (Modal._count === 0) {
document.body.removeEventListener('click', this._handleTriggerClick);
}
this.$overlay[0].removeEventListener('click', this._handleOverlayClickBound);
this.el.removeEventListener('click', this._handleModalCloseClickBound);
}
/**
* Handle Trigger Click
* @param {Event} e
*/
_handleTriggerClick(e) {
let $trigger = $(e.target).closest('.modal-trigger');
if ($trigger.length) {
let modalId = M.getIdFromTrigger($trigger[0]);
let modalInstance = document.getElementById(modalId).M_Modal;
if (modalInstance) {
modalInstance.open($trigger);
}
e.preventDefault();
}
}
/**
* Handle Overlay Click
*/
_handleOverlayClick() {
if (this.options.dismissible) {
this.close();
}
}
/**
* Handle Modal Close Click
* @param {Event} e
*/
_handleModalCloseClick(e) {
let $closeTrigger = $(e.target).closest('.modal-close');
if ($closeTrigger.length) {
this.close();
}
}
/**
* Handle Keydown
* @param {Event} e
*/
_handleKeydown(e) {
// ESC key
if (e.keyCode === 27 && this.options.dismissible) {
this.close();
}
}
/**
* Handle Focus
* @param {Event} e
*/
_handleFocus(e) {
// Only trap focus if this modal is the last model opened (prevents loops in nested modals).
if (!this.el.contains(e.target) && this._nthModalOpened === Modal._modalsOpen) {
this.el.focus();
}
}
/**
* Animate in modal
*/
_animateIn() {
// Set initial styles
$.extend(this.el.style, {
display: 'block',
opacity: 0
});
$.extend(this.$overlay[0].style, {
display: 'block',
opacity: 0
});
// Animate overlay
anim({
targets: this.$overlay[0],
opacity: this.options.opacity,
duration: this.options.inDuration,
easing: 'easeOutQuad'
});
// Define modal animation options
let enterAnimOptions = {
targets: this.el,
duration: this.options.inDuration,
easing: 'easeOutCubic',
// Handle modal onOpenEnd callback
complete: () => {
if (typeof this.options.onOpenEnd === 'function') {
this.options.onOpenEnd.call(this, this.el, this._openingTrigger);
}
}
};
// Bottom sheet animation
if (this.el.classList.contains('bottom-sheet')) {
$.extend(enterAnimOptions, {
bottom: 0,
opacity: 1
});
anim(enterAnimOptions);
// Normal modal animation
} else {
$.extend(enterAnimOptions, {
top: [this.options.startingTop, this.options.endingTop],
opacity: 1,
scaleX: [0.8, 1],
scaleY: [0.8, 1]
});
anim(enterAnimOptions);
}
}
/**
* Animate out modal
*/
_animateOut() {
// Animate overlay
anim({
targets: this.$overlay[0],
opacity: 0,
duration: this.options.outDuration,
easing: 'easeOutQuart'
});
// Define modal animation options
let exitAnimOptions = {
targets: this.el,
duration: this.options.outDuration,
easing: 'easeOutCubic',
// Handle modal ready callback
complete: () => {
this.el.style.display = 'none';
this.$overlay.remove();
// Call onCloseEnd callback
if (typeof this.options.onCloseEnd === 'function') {
this.options.onCloseEnd.call(this, this.el);
}
}
};
// Bottom sheet animation
if (this.el.classList.contains('bottom-sheet')) {
$.extend(exitAnimOptions, {
bottom: '-100%',
opacity: 0
});
anim(exitAnimOptions);
// Normal modal animation
} else {
$.extend(exitAnimOptions, {
top: [this.options.endingTop, this.options.startingTop],
opacity: 0,
scaleX: 0.8,
scaleY: 0.8
});
anim(exitAnimOptions);
}
}
/**
* Open Modal
* @param {cash} [$trigger]
*/
open($trigger) {
if (this.isOpen) {
return;
}
this.isOpen = true;
Modal._modalsOpen++;
this._nthModalOpened = Modal._modalsOpen;
// Set Z-Index based on number of currently open modals
this.$overlay[0].style.zIndex = 1000 + Modal._modalsOpen * 2;
this.el.style.zIndex = 1000 + Modal._modalsOpen * 2 + 1;
// Set opening trigger, undefined indicates modal was opened by javascript
this._openingTrigger = !!$trigger ? $trigger[0] : undefined;
// onOpenStart callback
if (typeof this.options.onOpenStart === 'function') {
this.options.onOpenStart.call(this, this.el, this._openingTrigger);
}
if (this.options.preventScrolling) {
document.body.style.overflow = 'hidden';
}
this.el.classList.add('open');
this.el.insertAdjacentElement('afterend', this.$overlay[0]);
if (this.options.dismissible) {
this._handleKeydownBound = this._handleKeydown.bind(this);
this._handleFocusBound = this._handleFocus.bind(this);
document.addEventListener('keydown', this._handleKeydownBound);
document.addEventListener('focus', this._handleFocusBound, true);
}
anim.remove(this.el);
anim.remove(this.$overlay[0]);
this._animateIn();
// Focus modal
this.el.focus();
return this;
}
/**
* Close Modal
*/
close() {
if (!this.isOpen) {
return;
}
this.isOpen = false;
Modal._modalsOpen--;
this._nthModalOpened = 0;
// Call onCloseStart callback
if (typeof this.options.onCloseStart === 'function') {
this.options.onCloseStart.call(this, this.el);
}
this.el.classList.remove('open');
// Enable body scrolling only if there are no more modals open.
if (Modal._modalsOpen === 0) {
document.body.style.overflow = '';
}
if (this.options.dismissible) {
document.removeEventListener('keydown', this._handleKeydownBound);
document.removeEventListener('focus', this._handleFocusBound, true);
}
anim.remove(this.el);
anim.remove(this.$overlay[0]);
this._animateOut();
return this;
}
}
/**
* @static
* @memberof Modal
*/
Modal._modalsOpen = 0;
/**
* @static
* @memberof Modal
*/
Modal._count = 0;
M.Modal = Modal;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Modal, 'modal', 'M_Modal');
}
})(cash, M.anime);

View File

@ -0,0 +1,138 @@
(function($) {
'use strict';
let _defaults = {
responsiveThreshold: 0 // breakpoint for swipeable
};
class Parallax extends Component {
constructor(el, options) {
super(Parallax, el, options);
this.el.M_Parallax = this;
/**
* Options for the Parallax
* @member Parallax#options
* @prop {Number} responsiveThreshold
*/
this.options = $.extend({}, Parallax.defaults, options);
this._enabled = window.innerWidth > this.options.responsiveThreshold;
this.$img = this.$el.find('img').first();
this.$img.each(function() {
let el = this;
if (el.complete) $(el).trigger('load');
});
this._updateParallax();
this._setupEventHandlers();
this._setupStyles();
Parallax._parallaxes.push(this);
}
static get defaults() {
return _defaults;
}
static init(els, options) {
return super.init(this, els, options);
}
/**
* Get Instance
*/
static getInstance(el) {
let domElem = !!el.jquery ? el[0] : el;
return domElem.M_Parallax;
}
/**
* Teardown component
*/
destroy() {
Parallax._parallaxes.splice(Parallax._parallaxes.indexOf(this), 1);
this.$img[0].style.transform = '';
this._removeEventHandlers();
this.$el[0].M_Parallax = undefined;
}
static _handleScroll() {
for (let i = 0; i < Parallax._parallaxes.length; i++) {
let parallaxInstance = Parallax._parallaxes[i];
parallaxInstance._updateParallax.call(parallaxInstance);
}
}
static _handleWindowResize() {
for (let i = 0; i < Parallax._parallaxes.length; i++) {
let parallaxInstance = Parallax._parallaxes[i];
parallaxInstance._enabled =
window.innerWidth > parallaxInstance.options.responsiveThreshold;
}
}
_setupEventHandlers() {
this._handleImageLoadBound = this._handleImageLoad.bind(this);
this.$img[0].addEventListener('load', this._handleImageLoadBound);
if (Parallax._parallaxes.length === 0) {
Parallax._handleScrollThrottled = M.throttle(Parallax._handleScroll, 5);
window.addEventListener('scroll', Parallax._handleScrollThrottled);
Parallax._handleWindowResizeThrottled = M.throttle(Parallax._handleWindowResize, 5);
window.addEventListener('resize', Parallax._handleWindowResizeThrottled);
}
}
_removeEventHandlers() {
this.$img[0].removeEventListener('load', this._handleImageLoadBound);
if (Parallax._parallaxes.length === 0) {
window.removeEventListener('scroll', Parallax._handleScrollThrottled);
window.removeEventListener('resize', Parallax._handleWindowResizeThrottled);
}
}
_setupStyles() {
this.$img[0].style.opacity = 1;
}
_handleImageLoad() {
this._updateParallax();
}
_updateParallax() {
let containerHeight = this.$el.height() > 0 ? this.el.parentNode.offsetHeight : 500;
let imgHeight = this.$img[0].offsetHeight;
let parallaxDist = imgHeight - containerHeight;
let bottom = this.$el.offset().top + containerHeight;
let top = this.$el.offset().top;
let scrollTop = M.getDocumentScrollTop();
let windowHeight = window.innerHeight;
let windowBottom = scrollTop + windowHeight;
let percentScrolled = (windowBottom - top) / (containerHeight + windowHeight);
let parallax = parallaxDist * percentScrolled;
if (!this._enabled) {
this.$img[0].style.transform = '';
} else if (bottom > scrollTop && top < scrollTop + windowHeight) {
this.$img[0].style.transform = `translate3D(-50%, ${parallax}px, 0)`;
}
}
}
/**
* @static
* @memberof Parallax
*/
Parallax._parallaxes = [];
M.Parallax = Parallax;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Parallax, 'parallax', 'M_Parallax');
}
})(cash);

145
resources/sass/materialize/js/pushpin.js vendored Normal file
View File

@ -0,0 +1,145 @@
(function($) {
'use strict';
let _defaults = {
top: 0,
bottom: Infinity,
offset: 0,
onPositionChange: null
};
/**
* @class
*
*/
class Pushpin extends Component {
/**
* Construct Pushpin instance
* @constructor
* @param {Element} el
* @param {Object} options
*/
constructor(el, options) {
super(Pushpin, el, options);
this.el.M_Pushpin = this;
/**
* Options for the modal
* @member Pushpin#options
*/
this.options = $.extend({}, Pushpin.defaults, options);
this.originalOffset = this.el.offsetTop;
Pushpin._pushpins.push(this);
this._setupEventHandlers();
this._updatePosition();
}
static get defaults() {
return _defaults;
}
static init(els, options) {
return super.init(this, els, options);
}
/**
* Get Instance
*/
static getInstance(el) {
let domElem = !!el.jquery ? el[0] : el;
return domElem.M_Pushpin;
}
/**
* Teardown component
*/
destroy() {
this.el.style.top = null;
this._removePinClasses();
this._removeEventHandlers();
// Remove pushpin Inst
let index = Pushpin._pushpins.indexOf(this);
Pushpin._pushpins.splice(index, 1);
}
static _updateElements() {
for (let elIndex in Pushpin._pushpins) {
let pInstance = Pushpin._pushpins[elIndex];
pInstance._updatePosition();
}
}
_setupEventHandlers() {
document.addEventListener('scroll', Pushpin._updateElements);
}
_removeEventHandlers() {
document.removeEventListener('scroll', Pushpin._updateElements);
}
_updatePosition() {
let scrolled = M.getDocumentScrollTop() + this.options.offset;
if (
this.options.top <= scrolled &&
this.options.bottom >= scrolled &&
!this.el.classList.contains('pinned')
) {
this._removePinClasses();
this.el.style.top = `${this.options.offset}px`;
this.el.classList.add('pinned');
// onPositionChange callback
if (typeof this.options.onPositionChange === 'function') {
this.options.onPositionChange.call(this, 'pinned');
}
}
// Add pin-top (when scrolled position is above top)
if (scrolled < this.options.top && !this.el.classList.contains('pin-top')) {
this._removePinClasses();
this.el.style.top = 0;
this.el.classList.add('pin-top');
// onPositionChange callback
if (typeof this.options.onPositionChange === 'function') {
this.options.onPositionChange.call(this, 'pin-top');
}
}
// Add pin-bottom (when scrolled position is below bottom)
if (scrolled > this.options.bottom && !this.el.classList.contains('pin-bottom')) {
this._removePinClasses();
this.el.classList.add('pin-bottom');
this.el.style.top = `${this.options.bottom - this.originalOffset}px`;
// onPositionChange callback
if (typeof this.options.onPositionChange === 'function') {
this.options.onPositionChange.call(this, 'pin-bottom');
}
}
}
_removePinClasses() {
// IE 11 bug (can't remove multiple classes in one line)
this.el.classList.remove('pin-top');
this.el.classList.remove('pinned');
this.el.classList.remove('pin-bottom');
}
}
/**
* @static
* @memberof Pushpin
*/
Pushpin._pushpins = [];
M.Pushpin = Pushpin;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Pushpin, 'pushpin', 'M_Pushpin');
}
})(cash);

263
resources/sass/materialize/js/range.js vendored Normal file
View File

@ -0,0 +1,263 @@
(function($, anim) {
'use strict';
let _defaults = {};
/**
* @class
*
*/
class Range extends Component {
/**
* Construct Range instance
* @constructor
* @param {Element} el
* @param {Object} options
*/
constructor(el, options) {
super(Range, el, options);
this.el.M_Range = this;
/**
* Options for the range
* @member Range#options
*/
this.options = $.extend({}, Range.defaults, options);
this._mousedown = false;
// Setup
this._setupThumb();
this._setupEventHandlers();
}
static get defaults() {
return _defaults;
}
static init(els, options) {
return super.init(this, els, options);
}
/**
* Get Instance
*/
static getInstance(el) {
let domElem = !!el.jquery ? el[0] : el;
return domElem.M_Range;
}
/**
* Teardown component
*/
destroy() {
this._removeEventHandlers();
this._removeThumb();
this.el.M_Range = undefined;
}
/**
* Setup Event Handlers
*/
_setupEventHandlers() {
this._handleRangeChangeBound = this._handleRangeChange.bind(this);
this._handleRangeMousedownTouchstartBound = this._handleRangeMousedownTouchstart.bind(this);
this._handleRangeInputMousemoveTouchmoveBound = this._handleRangeInputMousemoveTouchmove.bind(
this
);
this._handleRangeMouseupTouchendBound = this._handleRangeMouseupTouchend.bind(this);
this._handleRangeBlurMouseoutTouchleaveBound = this._handleRangeBlurMouseoutTouchleave.bind(
this
);
this.el.addEventListener('change', this._handleRangeChangeBound);
this.el.addEventListener('mousedown', this._handleRangeMousedownTouchstartBound);
this.el.addEventListener('touchstart', this._handleRangeMousedownTouchstartBound);
this.el.addEventListener('input', this._handleRangeInputMousemoveTouchmoveBound);
this.el.addEventListener('mousemove', this._handleRangeInputMousemoveTouchmoveBound);
this.el.addEventListener('touchmove', this._handleRangeInputMousemoveTouchmoveBound);
this.el.addEventListener('mouseup', this._handleRangeMouseupTouchendBound);
this.el.addEventListener('touchend', this._handleRangeMouseupTouchendBound);
this.el.addEventListener('blur', this._handleRangeBlurMouseoutTouchleaveBound);
this.el.addEventListener('mouseout', this._handleRangeBlurMouseoutTouchleaveBound);
this.el.addEventListener('touchleave', this._handleRangeBlurMouseoutTouchleaveBound);
}
/**
* Remove Event Handlers
*/
_removeEventHandlers() {
this.el.removeEventListener('change', this._handleRangeChangeBound);
this.el.removeEventListener('mousedown', this._handleRangeMousedownTouchstartBound);
this.el.removeEventListener('touchstart', this._handleRangeMousedownTouchstartBound);
this.el.removeEventListener('input', this._handleRangeInputMousemoveTouchmoveBound);
this.el.removeEventListener('mousemove', this._handleRangeInputMousemoveTouchmoveBound);
this.el.removeEventListener('touchmove', this._handleRangeInputMousemoveTouchmoveBound);
this.el.removeEventListener('mouseup', this._handleRangeMouseupTouchendBound);
this.el.removeEventListener('touchend', this._handleRangeMouseupTouchendBound);
this.el.removeEventListener('blur', this._handleRangeBlurMouseoutTouchleaveBound);
this.el.removeEventListener('mouseout', this._handleRangeBlurMouseoutTouchleaveBound);
this.el.removeEventListener('touchleave', this._handleRangeBlurMouseoutTouchleaveBound);
}
/**
* Handle Range Change
* @param {Event} e
*/
_handleRangeChange() {
$(this.value).html(this.$el.val());
if (!$(this.thumb).hasClass('active')) {
this._showRangeBubble();
}
let offsetLeft = this._calcRangeOffset();
$(this.thumb)
.addClass('active')
.css('left', offsetLeft + 'px');
}
/**
* Handle Range Mousedown and Touchstart
* @param {Event} e
*/
_handleRangeMousedownTouchstart(e) {
// Set indicator value
$(this.value).html(this.$el.val());
this._mousedown = true;
this.$el.addClass('active');
if (!$(this.thumb).hasClass('active')) {
this._showRangeBubble();
}
if (e.type !== 'input') {
let offsetLeft = this._calcRangeOffset();
$(this.thumb)
.addClass('active')
.css('left', offsetLeft + 'px');
}
}
/**
* Handle Range Input, Mousemove and Touchmove
*/
_handleRangeInputMousemoveTouchmove() {
if (this._mousedown) {
if (!$(this.thumb).hasClass('active')) {
this._showRangeBubble();
}
let offsetLeft = this._calcRangeOffset();
$(this.thumb)
.addClass('active')
.css('left', offsetLeft + 'px');
$(this.value).html(this.$el.val());
}
}
/**
* Handle Range Mouseup and Touchend
*/
_handleRangeMouseupTouchend() {
this._mousedown = false;
this.$el.removeClass('active');
}
/**
* Handle Range Blur, Mouseout and Touchleave
*/
_handleRangeBlurMouseoutTouchleave() {
if (!this._mousedown) {
let paddingLeft = parseInt(this.$el.css('padding-left'));
let marginLeft = 7 + paddingLeft + 'px';
if ($(this.thumb).hasClass('active')) {
anim.remove(this.thumb);
anim({
targets: this.thumb,
height: 0,
width: 0,
top: 10,
easing: 'easeOutQuad',
marginLeft: marginLeft,
duration: 100
});
}
$(this.thumb).removeClass('active');
}
}
/**
* Setup dropdown
*/
_setupThumb() {
this.thumb = document.createElement('span');
this.value = document.createElement('span');
$(this.thumb).addClass('thumb');
$(this.value).addClass('value');
$(this.thumb).append(this.value);
this.$el.after(this.thumb);
}
/**
* Remove dropdown
*/
_removeThumb() {
$(this.thumb).remove();
}
/**
* morph thumb into bubble
*/
_showRangeBubble() {
let paddingLeft = parseInt(
$(this.thumb)
.parent()
.css('padding-left')
);
let marginLeft = -7 + paddingLeft + 'px'; // TODO: fix magic number?
anim.remove(this.thumb);
anim({
targets: this.thumb,
height: 30,
width: 30,
top: -30,
marginLeft: marginLeft,
duration: 300,
easing: 'easeOutQuint'
});
}
/**
* Calculate the offset of the thumb
* @return {Number} offset in pixels
*/
_calcRangeOffset() {
let width = this.$el.width() - 15;
let max = parseFloat(this.$el.attr('max')) || 100; // Range default max
let min = parseFloat(this.$el.attr('min')) || 0; // Range default min
let percent = (parseFloat(this.$el.val()) - min) / (max - min);
return percent * width;
}
}
M.Range = Range;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Range, 'range', 'M_Range');
}
Range.init($('input[type=range]'));
})(cash, M.anime);

View File

@ -0,0 +1,295 @@
(function($, anim) {
'use strict';
let _defaults = {
throttle: 100,
scrollOffset: 200, // offset - 200 allows elements near bottom of page to scroll
activeClass: 'active',
getActiveElement: function(id) {
return 'a[href="#' + id + '"]';
}
};
/**
* @class
*
*/
class ScrollSpy extends Component {
/**
* Construct ScrollSpy instance
* @constructor
* @param {Element} el
* @param {Object} options
*/
constructor(el, options) {
super(ScrollSpy, el, options);
this.el.M_ScrollSpy = this;
/**
* Options for the modal
* @member Modal#options
* @prop {Number} [throttle=100] - Throttle of scroll handler
* @prop {Number} [scrollOffset=200] - Offset for centering element when scrolled to
* @prop {String} [activeClass='active'] - Class applied to active elements
* @prop {Function} [getActiveElement] - Used to find active element
*/
this.options = $.extend({}, ScrollSpy.defaults, options);
// setup
ScrollSpy._elements.push(this);
ScrollSpy._count++;
ScrollSpy._increment++;
this.tickId = -1;
this.id = ScrollSpy._increment;
this._setupEventHandlers();
this._handleWindowScroll();
}
static get defaults() {
return _defaults;
}
static init(els, options) {
return super.init(this, els, options);
}
/**
* Get Instance
*/
static getInstance(el) {
let domElem = !!el.jquery ? el[0] : el;
return domElem.M_ScrollSpy;
}
/**
* Teardown component
*/
destroy() {
ScrollSpy._elements.splice(ScrollSpy._elements.indexOf(this), 1);
ScrollSpy._elementsInView.splice(ScrollSpy._elementsInView.indexOf(this), 1);
ScrollSpy._visibleElements.splice(ScrollSpy._visibleElements.indexOf(this.$el), 1);
ScrollSpy._count--;
this._removeEventHandlers();
$(this.options.getActiveElement(this.$el.attr('id'))).removeClass(this.options.activeClass);
this.el.M_ScrollSpy = undefined;
}
/**
* Setup Event Handlers
*/
_setupEventHandlers() {
let throttledResize = M.throttle(this._handleWindowScroll, 200);
this._handleThrottledResizeBound = throttledResize.bind(this);
this._handleWindowScrollBound = this._handleWindowScroll.bind(this);
if (ScrollSpy._count === 1) {
window.addEventListener('scroll', this._handleWindowScrollBound);
window.addEventListener('resize', this._handleThrottledResizeBound);
document.body.addEventListener('click', this._handleTriggerClick);
}
}
/**
* Remove Event Handlers
*/
_removeEventHandlers() {
if (ScrollSpy._count === 0) {
window.removeEventListener('scroll', this._handleWindowScrollBound);
window.removeEventListener('resize', this._handleThrottledResizeBound);
document.body.removeEventListener('click', this._handleTriggerClick);
}
}
/**
* Handle Trigger Click
* @param {Event} e
*/
_handleTriggerClick(e) {
let $trigger = $(e.target);
for (let i = ScrollSpy._elements.length - 1; i >= 0; i--) {
let scrollspy = ScrollSpy._elements[i];
if ($trigger.is('a[href="#' + scrollspy.$el.attr('id') + '"]')) {
e.preventDefault();
let offset = scrollspy.$el.offset().top + 1;
anim({
targets: [document.documentElement, document.body],
scrollTop: offset - scrollspy.options.scrollOffset,
duration: 400,
easing: 'easeOutCubic'
});
break;
}
}
}
/**
* Handle Window Scroll
*/
_handleWindowScroll() {
// unique tick id
ScrollSpy._ticks++;
// viewport rectangle
let top = M.getDocumentScrollTop(),
left = M.getDocumentScrollLeft(),
right = left + window.innerWidth,
bottom = top + window.innerHeight;
// determine which elements are in view
let intersections = ScrollSpy._findElements(top, right, bottom, left);
for (let i = 0; i < intersections.length; i++) {
let scrollspy = intersections[i];
let lastTick = scrollspy.tickId;
if (lastTick < 0) {
// entered into view
scrollspy._enter();
}
// update tick id
scrollspy.tickId = ScrollSpy._ticks;
}
for (let i = 0; i < ScrollSpy._elementsInView.length; i++) {
let scrollspy = ScrollSpy._elementsInView[i];
let lastTick = scrollspy.tickId;
if (lastTick >= 0 && lastTick !== ScrollSpy._ticks) {
// exited from view
scrollspy._exit();
scrollspy.tickId = -1;
}
}
// remember elements in view for next tick
ScrollSpy._elementsInView = intersections;
}
/**
* Find elements that are within the boundary
* @param {number} top
* @param {number} right
* @param {number} bottom
* @param {number} left
* @return {Array.<ScrollSpy>} A collection of elements
*/
static _findElements(top, right, bottom, left) {
let hits = [];
for (let i = 0; i < ScrollSpy._elements.length; i++) {
let scrollspy = ScrollSpy._elements[i];
let currTop = top + scrollspy.options.scrollOffset || 200;
if (scrollspy.$el.height() > 0) {
let elTop = scrollspy.$el.offset().top,
elLeft = scrollspy.$el.offset().left,
elRight = elLeft + scrollspy.$el.width(),
elBottom = elTop + scrollspy.$el.height();
let isIntersect = !(
elLeft > right ||
elRight < left ||
elTop > bottom ||
elBottom < currTop
);
if (isIntersect) {
hits.push(scrollspy);
}
}
}
return hits;
}
_enter() {
ScrollSpy._visibleElements = ScrollSpy._visibleElements.filter(function(value) {
return value.height() != 0;
});
if (ScrollSpy._visibleElements[0]) {
$(this.options.getActiveElement(ScrollSpy._visibleElements[0].attr('id'))).removeClass(
this.options.activeClass
);
if (
ScrollSpy._visibleElements[0][0].M_ScrollSpy &&
this.id < ScrollSpy._visibleElements[0][0].M_ScrollSpy.id
) {
ScrollSpy._visibleElements.unshift(this.$el);
} else {
ScrollSpy._visibleElements.push(this.$el);
}
} else {
ScrollSpy._visibleElements.push(this.$el);
}
$(this.options.getActiveElement(ScrollSpy._visibleElements[0].attr('id'))).addClass(
this.options.activeClass
);
}
_exit() {
ScrollSpy._visibleElements = ScrollSpy._visibleElements.filter(function(value) {
return value.height() != 0;
});
if (ScrollSpy._visibleElements[0]) {
$(this.options.getActiveElement(ScrollSpy._visibleElements[0].attr('id'))).removeClass(
this.options.activeClass
);
ScrollSpy._visibleElements = ScrollSpy._visibleElements.filter((el) => {
return el.attr('id') != this.$el.attr('id');
});
if (ScrollSpy._visibleElements[0]) {
// Check if empty
$(this.options.getActiveElement(ScrollSpy._visibleElements[0].attr('id'))).addClass(
this.options.activeClass
);
}
}
}
}
/**
* @static
* @memberof ScrollSpy
* @type {Array.<ScrollSpy>}
*/
ScrollSpy._elements = [];
/**
* @static
* @memberof ScrollSpy
* @type {Array.<ScrollSpy>}
*/
ScrollSpy._elementsInView = [];
/**
* @static
* @memberof ScrollSpy
* @type {Array.<cash>}
*/
ScrollSpy._visibleElements = [];
/**
* @static
* @memberof ScrollSpy
*/
ScrollSpy._count = 0;
/**
* @static
* @memberof ScrollSpy
*/
ScrollSpy._increment = 0;
/**
* @static
* @memberof ScrollSpy
*/
ScrollSpy._ticks = 0;
M.ScrollSpy = ScrollSpy;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(ScrollSpy, 'scrollSpy', 'M_ScrollSpy');
}
})(cash, M.anime);

432
resources/sass/materialize/js/select.js vendored Normal file
View File

@ -0,0 +1,432 @@
(function($) {
'use strict';
let _defaults = {
classes: '',
dropdownOptions: {}
};
/**
* @class
*
*/
class FormSelect extends Component {
/**
* Construct FormSelect instance
* @constructor
* @param {Element} el
* @param {Object} options
*/
constructor(el, options) {
super(FormSelect, el, options);
// Don't init if browser default version
if (this.$el.hasClass('browser-default')) {
return;
}
this.el.M_FormSelect = this;
/**
* Options for the select
* @member FormSelect#options
*/
this.options = $.extend({}, FormSelect.defaults, options);
this.isMultiple = this.$el.prop('multiple');
// Setup
this.el.tabIndex = -1;
this._keysSelected = {};
this._valueDict = {}; // Maps key to original and generated option element.
this._setupDropdown();
this._setupEventHandlers();
}
static get defaults() {
return _defaults;
}
static init(els, options) {
return super.init(this, els, options);
}
/**
* Get Instance
*/
static getInstance(el) {
let domElem = !!el.jquery ? el[0] : el;
return domElem.M_FormSelect;
}
/**
* Teardown component
*/
destroy() {
this._removeEventHandlers();
this._removeDropdown();
this.el.M_FormSelect = undefined;
}
/**
* Setup Event Handlers
*/
_setupEventHandlers() {
this._handleSelectChangeBound = this._handleSelectChange.bind(this);
this._handleOptionClickBound = this._handleOptionClick.bind(this);
this._handleInputClickBound = this._handleInputClick.bind(this);
$(this.dropdownOptions)
.find('li:not(.optgroup)')
.each((el) => {
el.addEventListener('click', this._handleOptionClickBound);
});
this.el.addEventListener('change', this._handleSelectChangeBound);
this.input.addEventListener('click', this._handleInputClickBound);
}
/**
* Remove Event Handlers
*/
_removeEventHandlers() {
$(this.dropdownOptions)
.find('li:not(.optgroup)')
.each((el) => {
el.removeEventListener('click', this._handleOptionClickBound);
});
this.el.removeEventListener('change', this._handleSelectChangeBound);
this.input.removeEventListener('click', this._handleInputClickBound);
}
/**
* Handle Select Change
* @param {Event} e
*/
_handleSelectChange(e) {
this._setValueToInput();
}
/**
* Handle Option Click
* @param {Event} e
*/
_handleOptionClick(e) {
e.preventDefault();
let option = $(e.target).closest('li')[0];
let key = option.id;
if (!$(option).hasClass('disabled') && !$(option).hasClass('optgroup') && key.length) {
let selected = true;
if (this.isMultiple) {
// Deselect placeholder option if still selected.
let placeholderOption = $(this.dropdownOptions).find('li.disabled.selected');
if (placeholderOption.length) {
placeholderOption.removeClass('selected');
placeholderOption.find('input[type="checkbox"]').prop('checked', false);
this._toggleEntryFromArray(placeholderOption[0].id);
}
selected = this._toggleEntryFromArray(key);
} else {
$(this.dropdownOptions)
.find('li')
.removeClass('selected');
$(option).toggleClass('selected', selected);
}
// Set selected on original select option
// Only trigger if selected state changed
let prevSelected = $(this._valueDict[key].el).prop('selected');
if (prevSelected !== selected) {
$(this._valueDict[key].el).prop('selected', selected);
this.$el.trigger('change');
}
}
e.stopPropagation();
}
/**
* Handle Input Click
*/
_handleInputClick() {
if (this.dropdown && this.dropdown.isOpen) {
this._setValueToInput();
this._setSelectedStates();
}
}
/**
* Setup dropdown
*/
_setupDropdown() {
this.wrapper = document.createElement('div');
$(this.wrapper).addClass('select-wrapper ' + this.options.classes);
this.$el.before($(this.wrapper));
this.wrapper.appendChild(this.el);
if (this.el.disabled) {
this.wrapper.classList.add('disabled');
}
// Create dropdown
this.$selectOptions = this.$el.children('option, optgroup');
this.dropdownOptions = document.createElement('ul');
this.dropdownOptions.id = `select-options-${M.guid()}`;
$(this.dropdownOptions).addClass(
'dropdown-content select-dropdown ' + (this.isMultiple ? 'multiple-select-dropdown' : '')
);
// Create dropdown structure.
if (this.$selectOptions.length) {
this.$selectOptions.each((el) => {
if ($(el).is('option')) {
// Direct descendant option.
let optionEl;
if (this.isMultiple) {
optionEl = this._appendOptionWithIcon(this.$el, el, 'multiple');
} else {
optionEl = this._appendOptionWithIcon(this.$el, el);
}
this._addOptionToValueDict(el, optionEl);
} else if ($(el).is('optgroup')) {
// Optgroup.
let selectOptions = $(el).children('option');
$(this.dropdownOptions).append(
$('<li class="optgroup"><span>' + el.getAttribute('label') + '</span></li>')[0]
);
selectOptions.each((el) => {
let optionEl = this._appendOptionWithIcon(this.$el, el, 'optgroup-option');
this._addOptionToValueDict(el, optionEl);
});
}
});
}
this.$el.after(this.dropdownOptions);
// Add input dropdown
this.input = document.createElement('input');
$(this.input).addClass('select-dropdown dropdown-trigger');
this.input.setAttribute('type', 'text');
this.input.setAttribute('readonly', 'true');
this.input.setAttribute('data-target', this.dropdownOptions.id);
if (this.el.disabled) {
$(this.input).prop('disabled', 'true');
}
this.$el.before(this.input);
this._setValueToInput();
// Add caret
let dropdownIcon = $(
'<svg class="caret" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M7 10l5 5 5-5z"/><path d="M0 0h24v24H0z" fill="none"/></svg>'
);
this.$el.before(dropdownIcon[0]);
// Initialize dropdown
if (!this.el.disabled) {
let dropdownOptions = $.extend({}, this.options.dropdownOptions);
// Add callback for centering selected option when dropdown content is scrollable
dropdownOptions.onOpenEnd = (el) => {
let selectedOption = $(this.dropdownOptions)
.find('.selected')
.first();
if (selectedOption.length) {
// Focus selected option in dropdown
M.keyDown = true;
this.dropdown.focusedIndex = selectedOption.index();
this.dropdown._focusFocusedItem();
M.keyDown = false;
// Handle scrolling to selected option
if (this.dropdown.isScrollable) {
let scrollOffset =
selectedOption[0].getBoundingClientRect().top -
this.dropdownOptions.getBoundingClientRect().top; // scroll to selected option
scrollOffset -= this.dropdownOptions.clientHeight / 2; // center in dropdown
this.dropdownOptions.scrollTop = scrollOffset;
}
}
};
if (this.isMultiple) {
dropdownOptions.closeOnClick = false;
}
this.dropdown = M.Dropdown.init(this.input, dropdownOptions);
}
// Add initial selections
this._setSelectedStates();
}
/**
* Add option to value dict
* @param {Element} el original option element
* @param {Element} optionEl generated option element
*/
_addOptionToValueDict(el, optionEl) {
let index = Object.keys(this._valueDict).length;
let key = this.dropdownOptions.id + index;
let obj = {};
optionEl.id = key;
obj.el = el;
obj.optionEl = optionEl;
this._valueDict[key] = obj;
}
/**
* Remove dropdown
*/
_removeDropdown() {
$(this.wrapper)
.find('.caret')
.remove();
$(this.input).remove();
$(this.dropdownOptions).remove();
$(this.wrapper).before(this.$el);
$(this.wrapper).remove();
}
/**
* Setup dropdown
* @param {Element} select select element
* @param {Element} option option element from select
* @param {String} type
* @return {Element} option element added
*/
_appendOptionWithIcon(select, option, type) {
// Add disabled attr if disabled
let disabledClass = option.disabled ? 'disabled ' : '';
let optgroupClass = type === 'optgroup-option' ? 'optgroup-option ' : '';
let multipleCheckbox = this.isMultiple
? `<label><input type="checkbox"${disabledClass}"/><span>${option.innerHTML}</span></label>`
: option.innerHTML;
let liEl = $('<li></li>');
let spanEl = $('<span></span>');
spanEl.html(multipleCheckbox);
liEl.addClass(`${disabledClass} ${optgroupClass}`);
liEl.append(spanEl);
// add icons
let iconUrl = option.getAttribute('data-icon');
if (!!iconUrl) {
let imgEl = $(`<img alt="" src="${iconUrl}">`);
liEl.prepend(imgEl);
}
// Check for multiple type.
$(this.dropdownOptions).append(liEl[0]);
return liEl[0];
}
/**
* Toggle entry from option
* @param {String} key Option key
* @return {Boolean} if entry was added or removed
*/
_toggleEntryFromArray(key) {
let notAdded = !this._keysSelected.hasOwnProperty(key);
let $optionLi = $(this._valueDict[key].optionEl);
if (notAdded) {
this._keysSelected[key] = true;
} else {
delete this._keysSelected[key];
}
$optionLi.toggleClass('selected', notAdded);
// Set checkbox checked value
$optionLi.find('input[type="checkbox"]').prop('checked', notAdded);
// use notAdded instead of true (to detect if the option is selected or not)
$optionLi.prop('selected', notAdded);
return notAdded;
}
/**
* Set text value to input
*/
_setValueToInput() {
let values = [];
let options = this.$el.find('option');
options.each((el) => {
if ($(el).prop('selected')) {
let text = $(el).text();
values.push(text);
}
});
if (!values.length) {
let firstDisabled = this.$el.find('option:disabled').eq(0);
if (firstDisabled.length && firstDisabled[0].value === '') {
values.push(firstDisabled.text());
}
}
this.input.value = values.join(', ');
}
/**
* Set selected state of dropdown to match actual select element
*/
_setSelectedStates() {
this._keysSelected = {};
for (let key in this._valueDict) {
let option = this._valueDict[key];
let optionIsSelected = $(option.el).prop('selected');
$(option.optionEl)
.find('input[type="checkbox"]')
.prop('checked', optionIsSelected);
if (optionIsSelected) {
this._activateOption($(this.dropdownOptions), $(option.optionEl));
this._keysSelected[key] = true;
} else {
$(option.optionEl).removeClass('selected');
}
}
}
/**
* Make option as selected and scroll to selected position
* @param {jQuery} collection Select options jQuery element
* @param {Element} newOption element of the new option
*/
_activateOption(collection, newOption) {
if (newOption) {
if (!this.isMultiple) {
collection.find('li.selected').removeClass('selected');
}
let option = $(newOption);
option.addClass('selected');
}
}
/**
* Get Selected Values
* @return {Array} Array of selected values
*/
getSelectedValues() {
let selectedValues = [];
for (let key in this._keysSelected) {
selectedValues.push(this._valueDict[key].el.value);
}
return selectedValues;
}
}
M.FormSelect = FormSelect;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(FormSelect, 'formSelect', 'M_FormSelect');
}
})(cash);

580
resources/sass/materialize/js/sidenav.js vendored Normal file
View File

@ -0,0 +1,580 @@
(function($, anim) {
'use strict';
let _defaults = {
edge: 'left',
draggable: true,
inDuration: 250,
outDuration: 200,
onOpenStart: null,
onOpenEnd: null,
onCloseStart: null,
onCloseEnd: null,
preventScrolling: true
};
/**
* @class
*/
class Sidenav extends Component {
/**
* Construct Sidenav instance and set up overlay
* @constructor
* @param {Element} el
* @param {Object} options
*/
constructor(el, options) {
super(Sidenav, el, options);
this.el.M_Sidenav = this;
this.id = this.$el.attr('id');
/**
* Options for the Sidenav
* @member Sidenav#options
* @prop {String} [edge='left'] - Side of screen on which Sidenav appears
* @prop {Boolean} [draggable=true] - Allow swipe gestures to open/close Sidenav
* @prop {Number} [inDuration=250] - Length in ms of enter transition
* @prop {Number} [outDuration=200] - Length in ms of exit transition
* @prop {Function} onOpenStart - Function called when sidenav starts entering
* @prop {Function} onOpenEnd - Function called when sidenav finishes entering
* @prop {Function} onCloseStart - Function called when sidenav starts exiting
* @prop {Function} onCloseEnd - Function called when sidenav finishes exiting
*/
this.options = $.extend({}, Sidenav.defaults, options);
/**
* Describes open/close state of Sidenav
* @type {Boolean}
*/
this.isOpen = false;
/**
* Describes if Sidenav is fixed
* @type {Boolean}
*/
this.isFixed = this.el.classList.contains('sidenav-fixed');
/**
* Describes if Sidenav is being draggeed
* @type {Boolean}
*/
this.isDragged = false;
// Window size variables for window resize checks
this.lastWindowWidth = window.innerWidth;
this.lastWindowHeight = window.innerHeight;
this._createOverlay();
this._createDragTarget();
this._setupEventHandlers();
this._setupClasses();
this._setupFixed();
Sidenav._sidenavs.push(this);
}
static get defaults() {
return _defaults;
}
static init(els, options) {
return super.init(this, els, options);
}
/**
* Get Instance
*/
static getInstance(el) {
let domElem = !!el.jquery ? el[0] : el;
return domElem.M_Sidenav;
}
/**
* Teardown component
*/
destroy() {
this._removeEventHandlers();
this._enableBodyScrolling();
this._overlay.parentNode.removeChild(this._overlay);
this.dragTarget.parentNode.removeChild(this.dragTarget);
this.el.M_Sidenav = undefined;
this.el.style.transform = '';
let index = Sidenav._sidenavs.indexOf(this);
if (index >= 0) {
Sidenav._sidenavs.splice(index, 1);
}
}
_createOverlay() {
let overlay = document.createElement('div');
this._closeBound = this.close.bind(this);
overlay.classList.add('sidenav-overlay');
overlay.addEventListener('click', this._closeBound);
document.body.appendChild(overlay);
this._overlay = overlay;
}
_setupEventHandlers() {
if (Sidenav._sidenavs.length === 0) {
document.body.addEventListener('click', this._handleTriggerClick);
}
this._handleDragTargetDragBound = this._handleDragTargetDrag.bind(this);
this._handleDragTargetReleaseBound = this._handleDragTargetRelease.bind(this);
this._handleCloseDragBound = this._handleCloseDrag.bind(this);
this._handleCloseReleaseBound = this._handleCloseRelease.bind(this);
this._handleCloseTriggerClickBound = this._handleCloseTriggerClick.bind(this);
this.dragTarget.addEventListener('touchmove', this._handleDragTargetDragBound);
this.dragTarget.addEventListener('touchend', this._handleDragTargetReleaseBound);
this._overlay.addEventListener('touchmove', this._handleCloseDragBound);
this._overlay.addEventListener('touchend', this._handleCloseReleaseBound);
this.el.addEventListener('touchmove', this._handleCloseDragBound);
this.el.addEventListener('touchend', this._handleCloseReleaseBound);
this.el.addEventListener('click', this._handleCloseTriggerClickBound);
// Add resize for side nav fixed
if (this.isFixed) {
this._handleWindowResizeBound = this._handleWindowResize.bind(this);
window.addEventListener('resize', this._handleWindowResizeBound);
}
}
_removeEventHandlers() {
if (Sidenav._sidenavs.length === 1) {
document.body.removeEventListener('click', this._handleTriggerClick);
}
this.dragTarget.removeEventListener('touchmove', this._handleDragTargetDragBound);
this.dragTarget.removeEventListener('touchend', this._handleDragTargetReleaseBound);
this._overlay.removeEventListener('touchmove', this._handleCloseDragBound);
this._overlay.removeEventListener('touchend', this._handleCloseReleaseBound);
this.el.removeEventListener('touchmove', this._handleCloseDragBound);
this.el.removeEventListener('touchend', this._handleCloseReleaseBound);
this.el.removeEventListener('click', this._handleCloseTriggerClickBound);
// Remove resize for side nav fixed
if (this.isFixed) {
window.removeEventListener('resize', this._handleWindowResizeBound);
}
}
/**
* Handle Trigger Click
* @param {Event} e
*/
_handleTriggerClick(e) {
let $trigger = $(e.target).closest('.sidenav-trigger');
if (e.target && $trigger.length) {
let sidenavId = M.getIdFromTrigger($trigger[0]);
let sidenavInstance = document.getElementById(sidenavId).M_Sidenav;
if (sidenavInstance) {
sidenavInstance.open($trigger);
}
e.preventDefault();
}
}
/**
* Set variables needed at the beggining of drag
* and stop any current transition.
* @param {Event} e
*/
_startDrag(e) {
let clientX = e.targetTouches[0].clientX;
this.isDragged = true;
this._startingXpos = clientX;
this._xPos = this._startingXpos;
this._time = Date.now();
this._width = this.el.getBoundingClientRect().width;
this._overlay.style.display = 'block';
this._initialScrollTop = this.isOpen ? this.el.scrollTop : M.getDocumentScrollTop();
this._verticallyScrolling = false;
anim.remove(this.el);
anim.remove(this._overlay);
}
/**
* Set variables needed at each drag move update tick
* @param {Event} e
*/
_dragMoveUpdate(e) {
let clientX = e.targetTouches[0].clientX;
let currentScrollTop = this.isOpen ? this.el.scrollTop : M.getDocumentScrollTop();
this.deltaX = Math.abs(this._xPos - clientX);
this._xPos = clientX;
this.velocityX = this.deltaX / (Date.now() - this._time);
this._time = Date.now();
if (this._initialScrollTop !== currentScrollTop) {
this._verticallyScrolling = true;
}
}
/**
* Handles Dragging of Sidenav
* @param {Event} e
*/
_handleDragTargetDrag(e) {
// Check if draggable
if (!this.options.draggable || this._isCurrentlyFixed() || this._verticallyScrolling) {
return;
}
// If not being dragged, set initial drag start variables
if (!this.isDragged) {
this._startDrag(e);
}
// Run touchmove updates
this._dragMoveUpdate(e);
// Calculate raw deltaX
let totalDeltaX = this._xPos - this._startingXpos;
// dragDirection is the attempted user drag direction
let dragDirection = totalDeltaX > 0 ? 'right' : 'left';
// Don't allow totalDeltaX to exceed Sidenav width or be dragged in the opposite direction
totalDeltaX = Math.min(this._width, Math.abs(totalDeltaX));
if (this.options.edge === dragDirection) {
totalDeltaX = 0;
}
/**
* transformX is the drag displacement
* transformPrefix is the initial transform placement
* Invert values if Sidenav is right edge
*/
let transformX = totalDeltaX;
let transformPrefix = 'translateX(-100%)';
if (this.options.edge === 'right') {
transformPrefix = 'translateX(100%)';
transformX = -transformX;
}
// Calculate open/close percentage of sidenav, with open = 1 and close = 0
this.percentOpen = Math.min(1, totalDeltaX / this._width);
// Set transform and opacity styles
this.el.style.transform = `${transformPrefix} translateX(${transformX}px)`;
this._overlay.style.opacity = this.percentOpen;
}
/**
* Handle Drag Target Release
*/
_handleDragTargetRelease() {
if (this.isDragged) {
if (this.percentOpen > 0.2) {
this.open();
} else {
this._animateOut();
}
this.isDragged = false;
this._verticallyScrolling = false;
}
}
/**
* Handle Close Drag
* @param {Event} e
*/
_handleCloseDrag(e) {
if (this.isOpen) {
// Check if draggable
if (!this.options.draggable || this._isCurrentlyFixed() || this._verticallyScrolling) {
return;
}
// If not being dragged, set initial drag start variables
if (!this.isDragged) {
this._startDrag(e);
}
// Run touchmove updates
this._dragMoveUpdate(e);
// Calculate raw deltaX
let totalDeltaX = this._xPos - this._startingXpos;
// dragDirection is the attempted user drag direction
let dragDirection = totalDeltaX > 0 ? 'right' : 'left';
// Don't allow totalDeltaX to exceed Sidenav width or be dragged in the opposite direction
totalDeltaX = Math.min(this._width, Math.abs(totalDeltaX));
if (this.options.edge !== dragDirection) {
totalDeltaX = 0;
}
let transformX = -totalDeltaX;
if (this.options.edge === 'right') {
transformX = -transformX;
}
// Calculate open/close percentage of sidenav, with open = 1 and close = 0
this.percentOpen = Math.min(1, 1 - totalDeltaX / this._width);
// Set transform and opacity styles
this.el.style.transform = `translateX(${transformX}px)`;
this._overlay.style.opacity = this.percentOpen;
}
}
/**
* Handle Close Release
*/
_handleCloseRelease() {
if (this.isOpen && this.isDragged) {
if (this.percentOpen > 0.8) {
this._animateIn();
} else {
this.close();
}
this.isDragged = false;
this._verticallyScrolling = false;
}
}
/**
* Handles closing of Sidenav when element with class .sidenav-close
*/
_handleCloseTriggerClick(e) {
let $closeTrigger = $(e.target).closest('.sidenav-close');
if ($closeTrigger.length && !this._isCurrentlyFixed()) {
this.close();
}
}
/**
* Handle Window Resize
*/
_handleWindowResize() {
// Only handle horizontal resizes
if (this.lastWindowWidth !== window.innerWidth) {
if (window.innerWidth > 992) {
this.open();
} else {
this.close();
}
}
this.lastWindowWidth = window.innerWidth;
this.lastWindowHeight = window.innerHeight;
}
_setupClasses() {
if (this.options.edge === 'right') {
this.el.classList.add('right-aligned');
this.dragTarget.classList.add('right-aligned');
}
}
_removeClasses() {
this.el.classList.remove('right-aligned');
this.dragTarget.classList.remove('right-aligned');
}
_setupFixed() {
if (this._isCurrentlyFixed()) {
this.open();
}
}
_isCurrentlyFixed() {
return this.isFixed && window.innerWidth > 992;
}
_createDragTarget() {
let dragTarget = document.createElement('div');
dragTarget.classList.add('drag-target');
document.body.appendChild(dragTarget);
this.dragTarget = dragTarget;
}
_preventBodyScrolling() {
let body = document.body;
body.style.overflow = 'hidden';
}
_enableBodyScrolling() {
let body = document.body;
body.style.overflow = '';
}
open() {
if (this.isOpen === true) {
return;
}
this.isOpen = true;
// Run onOpenStart callback
if (typeof this.options.onOpenStart === 'function') {
this.options.onOpenStart.call(this, this.el);
}
// Handle fixed Sidenav
if (this._isCurrentlyFixed()) {
anim.remove(this.el);
anim({
targets: this.el,
translateX: 0,
duration: 0,
easing: 'easeOutQuad'
});
this._enableBodyScrolling();
this._overlay.style.display = 'none';
// Handle non-fixed Sidenav
} else {
if (this.options.preventScrolling) {
this._preventBodyScrolling();
}
if (!this.isDragged || this.percentOpen != 1) {
this._animateIn();
}
}
}
close() {
if (this.isOpen === false) {
return;
}
this.isOpen = false;
// Run onCloseStart callback
if (typeof this.options.onCloseStart === 'function') {
this.options.onCloseStart.call(this, this.el);
}
// Handle fixed Sidenav
if (this._isCurrentlyFixed()) {
let transformX = this.options.edge === 'left' ? '-105%' : '105%';
this.el.style.transform = `translateX(${transformX})`;
// Handle non-fixed Sidenav
} else {
this._enableBodyScrolling();
if (!this.isDragged || this.percentOpen != 0) {
this._animateOut();
} else {
this._overlay.style.display = 'none';
}
}
}
_animateIn() {
this._animateSidenavIn();
this._animateOverlayIn();
}
_animateSidenavIn() {
let slideOutPercent = this.options.edge === 'left' ? -1 : 1;
if (this.isDragged) {
slideOutPercent =
this.options.edge === 'left'
? slideOutPercent + this.percentOpen
: slideOutPercent - this.percentOpen;
}
anim.remove(this.el);
anim({
targets: this.el,
translateX: [`${slideOutPercent * 100}%`, 0],
duration: this.options.inDuration,
easing: 'easeOutQuad',
complete: () => {
// Run onOpenEnd callback
if (typeof this.options.onOpenEnd === 'function') {
this.options.onOpenEnd.call(this, this.el);
}
}
});
}
_animateOverlayIn() {
let start = 0;
if (this.isDragged) {
start = this.percentOpen;
} else {
$(this._overlay).css({
display: 'block'
});
}
anim.remove(this._overlay);
anim({
targets: this._overlay,
opacity: [start, 1],
duration: this.options.inDuration,
easing: 'easeOutQuad'
});
}
_animateOut() {
this._animateSidenavOut();
this._animateOverlayOut();
}
_animateSidenavOut() {
let endPercent = this.options.edge === 'left' ? -1 : 1;
let slideOutPercent = 0;
if (this.isDragged) {
slideOutPercent =
this.options.edge === 'left'
? endPercent + this.percentOpen
: endPercent - this.percentOpen;
}
anim.remove(this.el);
anim({
targets: this.el,
translateX: [`${slideOutPercent * 100}%`, `${endPercent * 105}%`],
duration: this.options.outDuration,
easing: 'easeOutQuad',
complete: () => {
// Run onOpenEnd callback
if (typeof this.options.onCloseEnd === 'function') {
this.options.onCloseEnd.call(this, this.el);
}
}
});
}
_animateOverlayOut() {
anim.remove(this._overlay);
anim({
targets: this._overlay,
opacity: 0,
duration: this.options.outDuration,
easing: 'easeOutQuad',
complete: () => {
$(this._overlay).css('display', 'none');
}
});
}
}
/**
* @static
* @memberof Sidenav
* @type {Array.<Sidenav>}
*/
Sidenav._sidenavs = [];
M.Sidenav = Sidenav;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Sidenav, 'sidenav', 'M_Sidenav');
}
})(cash, M.anime);

Some files were not shown because too many files have changed in this diff Show More