mirror of
https://github.com/LeCoupa/awesome-cheatsheets.git
synced 2026-01-25 04:38:51 -08:00
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1 +1,5 @@
|
||||
# Miscelleaneous
|
||||
.DS_Store
|
||||
|
||||
# Editors
|
||||
.vscode/
|
||||
|
||||
79
README.md
79
README.md
@@ -1,23 +1,16 @@
|
||||

|
||||
[](https://lecoupa.github.io/awesome-cheatsheets/)
|
||||
|
||||
[](https://awesome.re) [](https://github.com/LeCoupa/awesome-cheatsheets/blob/master/LICENSE)
|
||||
|
||||
**WEBSITE DIRECTORY**: [Available here](https://lecoupa.github.io/awesome-cheatsheets/).
|
||||
|
||||
> 📚 Awesome cheatsheets for popular programming languages, frameworks and development tools. They include everything you should know in one single file.
|
||||
|
||||
> ❤️ **If you like this repository, [you can click here to tweet it and make it spread](https://ctt.ec/PHba4).**
|
||||
|
||||
|
||||
## 🤔 Why Awesome-Cheatsheets?
|
||||
|
||||
I always make a cheatsheet when I want to improve my skills on a programming language, a framework or a development tool. [I started doing these kind of things a long time ago on Gist](https://gist.github.com/LeCoupa) To better keep track of the history and to let people contribute to them, I reorganized everything into this single repository. Most of the content is coming from official documentations and some books I have read.
|
||||
|
||||
Feel free to browse each cheatsheet to learn new things and to keep them at hand when you forgot about one command. They have been designed to provide a quick way to assess your knowledge and to save you time.
|
||||
|
||||
|
||||
## 🙌🏼 How to Contribute?
|
||||
|
||||
You are more than welcome to contribute and build your own cheatsheet for your favorite programming language, framework or development tool. Just submit changes via pull request and I will review them before merging.
|
||||
I usually make a cheatsheet when I want to improve my skills on a programming language, a framework or a development tool. [I started doing these kind of things a long time ago on Gist](https://gist.github.com/LeCoupa). To better keep track of the history and to let people contribute, I reorganized all of them into this single repository. Most of the content is coming from official documentations and some books I have read.
|
||||
|
||||
Feel free to take a look. You might learn new things. They have been designed to provide a quick way to assess your knowledge and to save you time.
|
||||
|
||||
## 📚 Table of Contents
|
||||
|
||||
@@ -28,17 +21,19 @@ You are more than welcome to contribute and build your own cheatsheet for your f
|
||||
|
||||
#### Command line interface
|
||||
|
||||
* [Bash](languages/bash.sh)
|
||||
- [Bash](languages/bash.sh)
|
||||
|
||||
#### Imperative
|
||||
|
||||
* [PHP](languages/php.php)
|
||||
- [C](languages/C.txt)
|
||||
- [C#](languages/C%23.txt)
|
||||
- [PHP](languages/php.php)
|
||||
|
||||
#### Functional
|
||||
|
||||
* [JavaScript](languages/javascript.js)
|
||||
</details>
|
||||
- [JavaScript](languages/javascript.js)
|
||||
|
||||
</details>
|
||||
|
||||
### 📦 Backend
|
||||
|
||||
@@ -47,15 +42,15 @@ You are more than welcome to contribute and build your own cheatsheet for your f
|
||||
|
||||
#### Python
|
||||
|
||||
* [Django](backend/django.py)
|
||||
- [Django](backend/django.py)
|
||||
|
||||
#### Javascript
|
||||
|
||||
* [Feathers.js](backend/feathers.js)
|
||||
* [Moleculer](backend/moleculer.js)
|
||||
* [Node.js](backend/node.js)
|
||||
</details>
|
||||
|
||||
- [Feathers.js](backend/feathers.js)
|
||||
- [Moleculer](backend/moleculer.js)
|
||||
- [Node.js](backend/node.js)
|
||||
- [Sails.js](backend/sails.js)
|
||||
</details>
|
||||
|
||||
### 🌐 Frontend
|
||||
|
||||
@@ -64,13 +59,16 @@ You are more than welcome to contribute and build your own cheatsheet for your f
|
||||
|
||||
#### Basics
|
||||
|
||||
* [HTML5](frontend/html5.html)
|
||||
- [HTML5](frontend/html5.html)
|
||||
|
||||
#### Frameworks
|
||||
|
||||
* [Vue.js](frontend/vue.js)
|
||||
</details>
|
||||
|
||||
- [React.js](frontend/react.js)
|
||||
- [Vue.js](frontend/vue.js)
|
||||
- [Ember.js](frontend/ember.js)
|
||||
- [Angular (2+)](frontend/angular.js)
|
||||
- [AngularJS](frontend/angularjs.js)
|
||||
</details>
|
||||
|
||||
### 🗃️ Databases
|
||||
|
||||
@@ -79,9 +77,8 @@ You are more than welcome to contribute and build your own cheatsheet for your f
|
||||
|
||||
#### NoSQL
|
||||
|
||||
* [Redis](databases/redis.sh)
|
||||
</details>
|
||||
|
||||
- [Redis](databases/redis.sh)
|
||||
</details>
|
||||
|
||||
### 🔧 Tools
|
||||
|
||||
@@ -90,27 +87,30 @@ You are more than welcome to contribute and build your own cheatsheet for your f
|
||||
|
||||
#### Development
|
||||
|
||||
* [VIM](tools/vim.txt)
|
||||
* [Xcode](tools/xcode.txt)
|
||||
- [VIM](tools/vim.txt)
|
||||
- [Xcode](tools/xcode.txt)
|
||||
|
||||
#### Infrastructure
|
||||
|
||||
* [Docker](tools/docker.sh)
|
||||
* [Kubernetes](tools/kubernetes.sh)
|
||||
* [Nanobox Boxfile](tools/nanobox_boxfile.yml)
|
||||
* [Nanobox CLI](tools/nanobox_cli.sh)
|
||||
</details>
|
||||
- [Docker](tools/docker.sh)
|
||||
- [Kubernetes](tools/kubernetes.sh)
|
||||
- [Nanobox Boxfile](tools/nanobox_boxfile.yml)
|
||||
- [Nanobox CLI](tools/nanobox_cli.sh)
|
||||
</details>
|
||||
|
||||
## 🙌🏼 How to Contribute?
|
||||
|
||||
You are more than welcome to contribute and build your own cheatsheet for your favorite programming language, framework or development tool. Just submit changes via pull request and I will review them before merging.
|
||||
|
||||
## 🙏🏻 Contribution
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center">
|
||||
<a href="https://anyleads.com/" target="_blank"><img src="https://pbs.twimg.com/profile_images/838140522476761094/A4WpBe5M_400x400.jpg" height="64" /></a>
|
||||
<a href="https://crisp.chat/?ta=oR1nEv43TM" target="_blank"><img src="https://pbs.twimg.com/profile_images/651629444944273408/r5Kd_ifq_400x400.png" height="64" /></a>
|
||||
</td>
|
||||
<td align="center">
|
||||
<a href="https://crisp.chat/" target="_blank"><img src="https://pbs.twimg.com/profile_images/651629444944273408/r5Kd_ifq_400x400.png" height="64" /></a>
|
||||
<a href="http://try.anyleads.com/secret" target="_blank"><img src="https://pbs.twimg.com/profile_images/838140522476761094/A4WpBe5M_400x400.jpg" height="64" /></a>
|
||||
</td>
|
||||
<td align="center">
|
||||
<a href="https://hackr.io/" target="_blank"><img src="https://d1eq8vvyuam4eq.cloudfront.net/assets/images/code-images/code-apple-touch-icon-precomposed.png" height="64" /></a>
|
||||
@@ -118,6 +118,9 @@ You are more than welcome to contribute and build your own cheatsheet for your f
|
||||
<td align="center">
|
||||
<a href="https://learnk8s.io/" target="_blank"><img src="https://pbs.twimg.com/profile_images/925127335573114880/9yCkEIe3_400x400.jpg" height="64" /></a>
|
||||
</td>
|
||||
<td align="center">
|
||||
<a href="https://www.voxygen.com/" target="_blank"><img src="https://imgur.com/XQoVtag.png" height="64" /></a>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
BIN
_design/Awesome Cheatsheets.sketch
Normal file
BIN
_design/Awesome Cheatsheets.sketch
Normal file
Binary file not shown.
BIN
_design/awesome_cheatsheets_logo.png
Normal file
BIN
_design/awesome_cheatsheets_logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 6.0 KiB |
BIN
_design/awesome_cheatsheets_logo.psd
Normal file
BIN
_design/awesome_cheatsheets_logo.psd
Normal file
Binary file not shown.
BIN
_design/awesome_cheatsheets_logo@2x.png
Normal file
BIN
_design/awesome_cheatsheets_logo@2x.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
BIN
_design/awesome_cheatsheets_logo@4x.png
Normal file
BIN
_design/awesome_cheatsheets_logo@4x.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 69 KiB |
BIN
_design/cover_github@2x.png
Normal file
BIN
_design/cover_github@2x.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 42 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 6.7 KiB |
Binary file not shown.
Binary file not shown.
|
Before Width: | Height: | Size: 38 KiB |
@@ -15,7 +15,7 @@
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
```bash
|
||||
```
|
||||
# Provides the ability to initialize new application instances
|
||||
npm install @feathersjs/feathers --save
|
||||
|
||||
@@ -185,7 +185,7 @@ app.on('login', (payload, info) => {}) // sent by the authentication module and
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
```bash
|
||||
```
|
||||
# Contains Express framework integrations
|
||||
npm install @feathersjs/express --save
|
||||
|
||||
@@ -252,7 +252,7 @@ app.configure(primus(options, callback)) // sets up the Primus transport with t
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
```bash
|
||||
```
|
||||
# Bundles the separate Feathers client side modules into one providing the code as ES5 (compatible with modern browsers)
|
||||
# You do not have to install or load any of the other modules listed below
|
||||
npm install @feathersjs/client --save
|
||||
@@ -299,7 +299,7 @@ primus(socket, options) // initialize the Primus client using a given socket an
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
```bash
|
||||
```
|
||||
# Assists in using JWT for authentication
|
||||
npm install @feathersjs/authentication --save
|
||||
|
||||
@@ -562,7 +562,7 @@ app.service('authentication').hooks({
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
```bash
|
||||
```
|
||||
# [MEMORY/FILESYSTEM] In-memory database adapter
|
||||
npm install feathers-memory --save
|
||||
|
||||
|
||||
734
backend/sails.js
Normal file
734
backend/sails.js
Normal file
@@ -0,0 +1,734 @@
|
||||
/********************************************************************************************
|
||||
* SAILS.JS CHEATSHEET
|
||||
* REFERENCE: https://sailsjs.com/documentation/reference
|
||||
* CONCEPTS: https://sailsjs.com/documentation/concepts
|
||||
* APP STRUCTURE: https://sailsjs.com/documentation/anatomy
|
||||
*
|
||||
* 1. APPLICATION
|
||||
* 2. BLUEPRINT API
|
||||
* 3. COMMAND-LINE INTERFACE
|
||||
* 4. CONFIGURATION
|
||||
* 5. REQUEST
|
||||
* 6. RESPONSE
|
||||
* 7. WATERLINE ORM
|
||||
* 8. WEBSOCKETS
|
||||
********************************************************************************************/
|
||||
|
||||
/********************************************************************************************
|
||||
* 1. APPLICATION
|
||||
* https://sailsjs.com/documentation/reference/application
|
||||
********************************************************************************************/
|
||||
|
||||
// A dictionary of all loaded Sails models, indexed by their identity.
|
||||
sails.models
|
||||
|
||||
// A dictionary of all accessible helpers, including organics.
|
||||
sails.helpers
|
||||
|
||||
// A dictionary of all loaded Sails hooks, indexed by their identity.
|
||||
sails.hooks
|
||||
|
||||
// The full set of configuration options for the Sails instance
|
||||
// It is assembled automatically when Sails loads your app
|
||||
// merging together command-line arguments, environment variables, your .sailsrc file,
|
||||
// and the configuration objects exported from any and all modules in your app's config/ directory.
|
||||
sails.config
|
||||
|
||||
// The runtime values of your app's custom configuration settings.
|
||||
sails.config.custom
|
||||
|
||||
// A set of convenience methods for low - level interaction with connected websockets.
|
||||
sails.sockets
|
||||
|
||||
// Talk to Socket.io directly.
|
||||
sails.io
|
||||
|
||||
// A regular expression designed for use in identifying URL paths that seem like they are probably
|
||||
// for a static asset of some kind (e.g. image, stylesheet, favicon.ico, robots.txt, etc).
|
||||
sails.LOOKS_LIKE_ASSET_RX
|
||||
|
||||
// Return a dictionary of Sails actions.
|
||||
sails.getActions()
|
||||
|
||||
// Look up the first route pointing at the specified target (e.g. MeController.login)
|
||||
// and return a dictionary containing its method and URL.
|
||||
sails.getRouteFor(target)
|
||||
|
||||
// Look up the first route pointing at the specified target (e.g. entrance/view-login)
|
||||
// and return its URL.
|
||||
sails.getUrlFor(target)
|
||||
|
||||
// Lift a Sails app programmatically.
|
||||
// This does exactly what you might be used to seeing by now when you run sails lift.
|
||||
sailsApp.lift(configOverrides, function(err) {})
|
||||
|
||||
// Load a Sails app into memory-- but without lifting an HTTP server.
|
||||
// Useful for writing tests, command - line scripts, and scheduled jobs.
|
||||
sailsApp.load(configOverrides, function(err) {})
|
||||
|
||||
// Shut down a lifted Sails app and have it cease listening for / responding to any future requests.
|
||||
sails.lower(callback)
|
||||
|
||||
// Register a new Sails action that can then be bound to a route.
|
||||
sails.registerAction(action, name)
|
||||
|
||||
// Register a new action middleware function that will be applied to actions
|
||||
// with the specified identities.
|
||||
sails.registerActionMiddleware(actionMiddlewareFns, actionIdentities)
|
||||
|
||||
// Flush and reload all Sails actions.
|
||||
sails.reloadActions()
|
||||
|
||||
// Compile a view into an HTML template.
|
||||
sails.renderView(pathToView, templateData)
|
||||
|
||||
// Make a virtual request to a running Sails instance.
|
||||
sails.request(request)
|
||||
sails.request(url, body)
|
||||
sails.request(url, callback)
|
||||
sails.request(url, body, callback)
|
||||
|
||||
// Access a particular datastore, or the default datastore.
|
||||
sails.getDatastore(datastoreName)
|
||||
|
||||
// Log a message or some data at the "debug" log level using Sails' built-in logger.
|
||||
sails.log(message)
|
||||
|
||||
/********************************************************************************************
|
||||
* 2. BLUEPRINT API
|
||||
* https://sailsjs.com/documentation/reference/blueprint-api
|
||||
********************************************************************************************/
|
||||
|
||||
// Find a list of records that match the specified criteria
|
||||
// and (if possible) subscribe to each of them.
|
||||
GET /:model
|
||||
|
||||
// Look up the record with the specified id from the database
|
||||
// and (if possible) subscribe to the record to hear about any future changes.
|
||||
GET /:model/:id
|
||||
|
||||
// Populate and return foreign record(s) for the given association of this record.
|
||||
GET /:model/:id/:association
|
||||
|
||||
// Create a new record in your database
|
||||
// and notify subscribed sockets that a newly record is created
|
||||
POST /:model
|
||||
|
||||
// Update an existing record in the database
|
||||
// and notify subscribed sockets that it has changed.
|
||||
PATCH /:model/:id
|
||||
|
||||
// Replace all of the foreign records in one of this record's collections
|
||||
// and notify subscribed sockets to the parent record.
|
||||
PUT /:model/:id/:association
|
||||
|
||||
// Add a foreign record to one of this record's collections
|
||||
// and notify subscribed sockets to the parent record.
|
||||
PUT /:model/:id/:association/:fk
|
||||
|
||||
// Delete the record specified by id from the database forever
|
||||
// and notify subscribed sockets that a record has been deleted
|
||||
DELETE /:model/:id
|
||||
|
||||
// Remove a foreign record from one of this record's collections
|
||||
// and notify subscribed sockets about this removed child
|
||||
DELETE /:model/:id/:association/:fk
|
||||
|
||||
/********************************************************************************************
|
||||
* 3. COMMAND-LINE INTERFACE
|
||||
* https://sailsjs.com/documentation/reference/command-line-interface
|
||||
********************************************************************************************/
|
||||
|
||||
// Lift your Node.js/Sails.js app in interactive mode, and enter the REPL.
|
||||
// Useful for trying out Waterline queries, quickly managing your data, and checking
|
||||
// out your project's runtime configuration.
|
||||
sails console [--dontLift]
|
||||
|
||||
// Generate api/models/Foo.js, including attributes with the specified types if provided.
|
||||
sails generate model
|
||||
|
||||
// Generate a standalone action.
|
||||
sails generate action
|
||||
|
||||
// Generate a helper at api/helpers/foo.js.
|
||||
sails generate helper
|
||||
|
||||
// Generate api/controllers/FooController.js, including actions with the specified names if provided.
|
||||
sails generate controller
|
||||
|
||||
// Generate a project hook in api/hooks/foo/.
|
||||
sails generate hook
|
||||
|
||||
// Generate a foo folder containing the files necessary for building a new generator.
|
||||
sails generate generator
|
||||
|
||||
// Generate a custom response at api/responses/foo.js
|
||||
sails generate response
|
||||
|
||||
// Generate a api/adapters/foo/ folder containing the files necessary for building a new adapter.
|
||||
sails generate adapter
|
||||
|
||||
// Generate a sails.io.js file at the specified location, overwriting the default sails.io.js if applicable.
|
||||
sails generate sails.io.js
|
||||
|
||||
// Generate api/models/Foo.js and api/controllers/FooController.js.
|
||||
sails generate api
|
||||
|
||||
// Alias for sails new.
|
||||
sails generate new
|
||||
|
||||
// Experimental. Adds the following files to your app:
|
||||
// .gitignore, .jshintrc, .editorconfig, .npmignore, .travis.yml, .appveyor.yml
|
||||
sails generate etc
|
||||
|
||||
// Attach the node debugger and lift the sails app; similar to running node--inspect app.js.
|
||||
// You can then use a tool like the Chrome DevTools to interactively debug your apps.
|
||||
sails inspect
|
||||
|
||||
// Run the Sails app in the current dir
|
||||
// (if node_modules/sails exists, it will be used instead of the globally installed Sails)
|
||||
sails lift [--prod] [--port <portNum>] [--verbose] [--silly]
|
||||
|
||||
// Create a new sails project.
|
||||
sails new <yourAppName> [--no-frontend] [--minimal] [--without=package,package,package]
|
||||
|
||||
// Get the version of your computer's globally installed Sails command-line tool
|
||||
// (i.e. the version you installed with npm install -g sails).
|
||||
sails version
|
||||
|
||||
/********************************************************************************************
|
||||
* 4. CONFIGURATION
|
||||
* https://sailsjs.com/documentation/reference/configuration
|
||||
********************************************************************************************/
|
||||
|
||||
// Determines which TCP port your Sails app will use to listen for incoming requests.
|
||||
sails.config.port
|
||||
|
||||
// Declare the host name of your Sails app (By default, Sails will assume localhost).
|
||||
sails.config.explicitHost
|
||||
|
||||
// The runtime “environment” of your Sails app (usually either development or production).
|
||||
sails.config.environment
|
||||
|
||||
// A time limit, in milliseconds, imposed on all hooks in your app (default to 20000)
|
||||
sails.config.hookTimeout
|
||||
|
||||
// Configure SSL settings for HTTPs and WSS
|
||||
sails.config.ssl
|
||||
|
||||
// These configurable settings allow you to configure the blueprint API in Sails.
|
||||
sails.config.blueprints
|
||||
|
||||
// Asynchronous bootstrap function that runs before your Sails app gets lifted (i.e. starts up).
|
||||
// Can be used for setting up baseline data, running sanity checks on the status of your database...
|
||||
sails.config.bootstrap
|
||||
|
||||
// Custom configuration for your app (one-off settings specific to your application)
|
||||
// Things like the domain to use when sending emails, or 3rd party API keys for Stripe, Mailgun...
|
||||
sails.config.custom
|
||||
|
||||
// Datastore configurations(or simply datastores) are like "saved settings" for your adapters.
|
||||
sails.config.datastores
|
||||
|
||||
// Configuration for the global variables that Sails exposes by default.
|
||||
sails.config.globals
|
||||
|
||||
// Configuration for your app's underlying HTTP server.
|
||||
sails.config.http
|
||||
|
||||
// Configuration for Sails' built-in internationalization & localization features.
|
||||
sails.config.i18n
|
||||
|
||||
// Configuration for the logger in your Sails app.
|
||||
sails.config.log
|
||||
|
||||
// Your default project-wide model settings.
|
||||
sails.config.models
|
||||
|
||||
// Dictionary that maps policies to an app’s actions.
|
||||
sails.config.policies
|
||||
|
||||
// Configuration for custom (aka "explicit") routes.
|
||||
sails.config.routes
|
||||
|
||||
// Configuration for your app's security settings.
|
||||
sails.config.security
|
||||
|
||||
// Configuration for Sails's built-in session support.
|
||||
sails.config.session
|
||||
|
||||
// Provide transparent access to Socket.io
|
||||
sails.config.sockets
|
||||
|
||||
// Configuration for your app's server-side views.
|
||||
sails.config.views
|
||||
|
||||
/********************************************************************************************
|
||||
* 5. REQUEST
|
||||
* https://sailsjs.com/documentation/reference/request-req
|
||||
********************************************************************************************/
|
||||
|
||||
// The moment that Sails started processing the request, as a Javascript Date object.
|
||||
req._startTime
|
||||
|
||||
// An object containing text parameters from the parsed request body, defaulting to {}.
|
||||
// If a request contains one or more file uploads, only the text parameters sent before
|
||||
// the first file parameter will be available in req.body.
|
||||
req.body
|
||||
|
||||
// An object containing all of the unsigned cookies from this request (req).
|
||||
req.cookies
|
||||
|
||||
// A flag indicating the user-agent sending this request (req) wants "fresh" data
|
||||
// (as indicated by the "if-none-match", "cache-control", and/or "if-modified-since" request headers.)
|
||||
req.fresh
|
||||
|
||||
// An object containing pre-defined/custom header given in the current request.
|
||||
req.headers
|
||||
|
||||
// Returns the hostname supplied in the host HTTP header.
|
||||
// This header may be set either by the client or by the proxy.
|
||||
req.hostname
|
||||
|
||||
// The IP address of the client who sent this request (req).
|
||||
req.ip
|
||||
|
||||
// Contains the IP addresses in this request's "X-Forwarded-For" header
|
||||
// as an array of the IP address strings.
|
||||
req.ips
|
||||
|
||||
// A flag indicating whether or not this request (req) originated from a Socket.io connection.
|
||||
req.isSocket
|
||||
|
||||
// The request method (aka "verb".)
|
||||
// All requests to a Sails server have a "method", even via WebSockets.
|
||||
req.method
|
||||
|
||||
// Dictionary (plain JavaScript object) of request-agnostic settings available in your app's actions.
|
||||
req.options
|
||||
|
||||
// Retains the original request URL allowing you to rewrite req.url freely for internal routing purposes.
|
||||
// In almost all cases, you’ll want to use req.url instead.
|
||||
req.originalUrl
|
||||
|
||||
// An object containing parameter values parsed from the URL path.
|
||||
req.params
|
||||
|
||||
// The URL pathname from the request URL string of the current request (req).
|
||||
req.path
|
||||
|
||||
// The protocol used to send this request (req).
|
||||
req.protocol
|
||||
|
||||
// A dictionary containing the parsed query-string, defaulting to {}.
|
||||
req.query
|
||||
|
||||
// Indicates whether or not the request was sent over a secure TLS connection (i.e. https:// or wss://).
|
||||
req.secure
|
||||
|
||||
// A dictionary containing all of the signed cookies from this request (req).
|
||||
req.signedCookies
|
||||
|
||||
// If the current Request (req) originated from a connected Socket.io client,
|
||||
// req.socket refers to the raw Socket.io socket instance.
|
||||
req.socket
|
||||
|
||||
// An array of all the subdomains in this request's URL.
|
||||
req.subdomains
|
||||
|
||||
// Like req.path, but also includes the query string suffix.
|
||||
req.url
|
||||
|
||||
// A flag indicating whether the requesting client would prefer a JSON response
|
||||
// (as opposed to some other format, like XML or HTML.)
|
||||
req.wantsJSON
|
||||
|
||||
// A flag indicating whether the current request (req) appears to be an AJAX request.
|
||||
req.xhr
|
||||
|
||||
// Return whether this request (req) advertises that it understands the specified media type.
|
||||
req.accepts(mediaType)
|
||||
|
||||
// Return whether this request (req) advertises that it is able to handle any of the specified
|
||||
// character set(s), and if so, which one.
|
||||
req.acceptsCharsets(charset1, charset2, …)
|
||||
|
||||
// Return whether this request (req) advertises that it understands any of the specified
|
||||
// language(s), and if so, which one.
|
||||
req.acceptsLanguages(language1, language2, …)
|
||||
|
||||
// Returns the value of all parameters sent in the request, merged together into a single dictionary
|
||||
req.allParams()
|
||||
|
||||
// Build and return a Skipper Upstream representing an incoming multipart file upload from the specified field.
|
||||
req.file(field)
|
||||
|
||||
// Returns the value of the specified header field in this request (req). Note that header names are case-insensitive.
|
||||
req.get(header)
|
||||
|
||||
// Returns true if this request's declared "Content-Type" matches the specified media/mime type.
|
||||
req.is(type)
|
||||
|
||||
// Returns the value of the parameter with the specified name.
|
||||
req.param(name[, defaultValue])
|
||||
|
||||
// Override the inferred locale for this request.
|
||||
req.setLocale(override)
|
||||
|
||||
// Time out this request if a response is not sent within the specified number of milliseconds.
|
||||
req.setTimeout(numMilliseconds)
|
||||
|
||||
/********************************************************************************************
|
||||
* 6. RESPONSE
|
||||
* https://sailsjs.com/documentation/reference/response-res
|
||||
********************************************************************************************/
|
||||
|
||||
// Indicate to a web browser or other user agent that an outgoing file download sent
|
||||
// in this response should be "Saved as..." rather than "Opened", and optionally specify the
|
||||
// name for the newly downloaded file on disk.
|
||||
res.attachment([filename])
|
||||
|
||||
// This method is used to send a 200 ("OK") response back down to the client.
|
||||
res.ok(data)
|
||||
|
||||
// This method is used to send a 400 ("Bad Request") response back down
|
||||
// to the client indicating that the request is invalid.
|
||||
res.badRequest(data)
|
||||
|
||||
// This method is used to send a 403 ("Forbidden") response back down
|
||||
// to the client indicating that the request is not allowed.
|
||||
res.forbidden()
|
||||
|
||||
// This method is used to send a 404 ("Not Found") response using either res.json() or res.view().
|
||||
res.notFound()
|
||||
|
||||
// This method is used to send a 500 ("Server Error") response back down to the client indicating
|
||||
// that some kind of server error occurred (i.e. the error is not the requesting user agent's fault).
|
||||
res.serverError(err)
|
||||
res.serverError()
|
||||
|
||||
// Sets a cookie with name (name) and value (value) to be sent along with the response.
|
||||
res.cookie(name, value[, options])
|
||||
|
||||
// Clears cookie (name) in the response.
|
||||
res.clearCookie(name[, options])
|
||||
|
||||
// Returns the current value of the specified response header (header).
|
||||
res.get(header)
|
||||
|
||||
// Sets specified response header (header) to the specified value (value).
|
||||
res.set(header, value)
|
||||
res.set(headers)
|
||||
|
||||
// Sends a JSON response composed of a stringified version of the specified data.
|
||||
res.json([statusCode,] data)
|
||||
|
||||
// Send a JSON or JSONP response.
|
||||
res.jsonp()
|
||||
|
||||
// Sets the "Location" response header to the specified URL expression(url).
|
||||
res.location(url)
|
||||
|
||||
// Redirect the requesting user-agent to the given absolute or relative url.
|
||||
res.redirect(url)
|
||||
res.redirect(statusCode, url)
|
||||
|
||||
// Send a string response in a format other than JSON (XML, CSV, plain text, etc.
|
||||
// If you want to send a dictionary or JSON, use res.json().
|
||||
// If you want to send a custom status code, call req.status() first.
|
||||
res.send([string])
|
||||
|
||||
// Set the status code of this response.
|
||||
res.status(statusCode)
|
||||
|
||||
// Sets the "Content-Type" response header to the specified type.
|
||||
res.type(type)
|
||||
|
||||
// Respond with an HTML page.
|
||||
res.view(pathToView, locals)
|
||||
res.view(pathToView)
|
||||
res.view(locals)
|
||||
res.view()
|
||||
|
||||
/********************************************************************************************
|
||||
* 7. WATERLINE ORM
|
||||
* https://sailsjs.com/documentation/reference/waterline-orm
|
||||
********************************************************************************************/
|
||||
|
||||
// --> DATASTORE <--
|
||||
|
||||
// Return the default datastore
|
||||
var datastore = sails.getDatastore()
|
||||
|
||||
// The generic, stateless, low-level driver for this datastore (if the adapter supports it).
|
||||
datastore.driver
|
||||
|
||||
// The live connection manager for this datastore.
|
||||
datastore.manager
|
||||
|
||||
// Lease a new connection from the datastore for use in running multiple queries
|
||||
// on the same connection (i.e. so that the logic provided in during can reuse the db connection).
|
||||
await datastore.leaseConnection(during)
|
||||
|
||||
// Execute a raw SQL query using this datastore.
|
||||
await datastore.sendNativeQuery(sql, valuesToEscape)
|
||||
|
||||
// Fetch a preconfigured deferred object hooked up to the sails-mysql or sails-postgresql adapter
|
||||
// (and consequently the appropriate driver)
|
||||
await datastore.transaction(during)
|
||||
|
||||
// --> MODELS <--
|
||||
|
||||
// Add one or more existing child records to the specified collection.
|
||||
MyModel.addToCollection(parentId, association).members(childIds)
|
||||
|
||||
// Remove one or more members from the specified collection
|
||||
MyModel.removeFromCollection()
|
||||
|
||||
// Replace all members of the specified collection
|
||||
MyModel.replaceCollection()
|
||||
|
||||
// Archive ("soft-delete") records that match the specified criteria,
|
||||
// saving them as new records in the built-in Archive model, then destroying the originals.
|
||||
MyModel.archive(criteria)
|
||||
|
||||
// Archive ("soft-delete") the record that matches the specified criteria,
|
||||
// saving it (if it exists) as a new record in the built-in Archive model, then destroying the original.
|
||||
MyModel.archiveOne(criteria);
|
||||
|
||||
// Get the total number of records matching the specified criteria.
|
||||
MyModel.count(criteria)
|
||||
|
||||
// Get the aggregate mean of the specified attribute across all matching records.
|
||||
MyModel.avg(numericAttrName, criteria)
|
||||
|
||||
// Get the aggregate sum of the specified attribute across all matching records.
|
||||
MyModel.sum(numericAttrName, criteria)
|
||||
|
||||
// Find records in your database that match the given criteria.
|
||||
MyModel.find(criteria)
|
||||
|
||||
// Attempt to find a particular record in your database that matches the given criteria.
|
||||
MyModel.findOne(criteria)
|
||||
|
||||
// Find the record matching the specified criteria.
|
||||
// If no such record exists, create one using the provided initial values.
|
||||
MyModel.findOrCreate(criteria, initialValues)
|
||||
|
||||
// Create a record in the database.
|
||||
MyModel.create(initialValues)
|
||||
MyModel.create(initialValues).fetch() // Created record will be returned
|
||||
|
||||
// Create a set of records in the database.
|
||||
MyModel.createEach(initialValues)
|
||||
MyModel.createEach(initialValues).fetch() // Created records will be returned
|
||||
|
||||
// Update all records matching criteria.
|
||||
MyModel.update(criteria, valuesToSet)
|
||||
MyModel.update(criteria, valuesToSet).fetch() // Updated records will be returned
|
||||
|
||||
// Update the record that matches the given criteria, if one exists.
|
||||
MyModel.updateOne(criteria).set(valuesToSet);
|
||||
|
||||
// Destroy records in your database that match the given criteria.
|
||||
MyModel.destroy(criteria)
|
||||
MyModel.destroy(criteria).fetch() // Destroyed record will be returned
|
||||
|
||||
// Destroy the record in your database that matches the given criteria, if one exists.
|
||||
MyModel.destroyOne(criteria);
|
||||
|
||||
// Access the datastore for a particular model.
|
||||
MyModel.getDatastore()
|
||||
|
||||
// Stream records from your database one at a time or in batches,
|
||||
// without first having to buffer the entire result set in memory.
|
||||
MyModel.stream(criteria)
|
||||
|
||||
// Verify that a value would be valid for a given attribute, then return it, loosely coerced.
|
||||
MyModel.validate(attrName, value)
|
||||
|
||||
// --> QUERIES <--
|
||||
|
||||
// Set the maximum number of records to retrieve when executing a query instance.
|
||||
query.limit(maximum)
|
||||
|
||||
// Indicate a number of records to skip before returning the results from executing a query instance.
|
||||
query.skip(numRecordsToSkip)
|
||||
|
||||
// Set the order in which retrieved records should be returned when executing a query instance.
|
||||
query.sort(sortClause)
|
||||
|
||||
// Specify a where clause for filtering a query.
|
||||
query.where(whereClause)
|
||||
|
||||
// Tell Waterline (and the underlying database adapter) to send back records that were
|
||||
// updated/destroyed/created when performing an .update(), .create(), .createEach() or .destroy()
|
||||
// query. Otherwise, no data will be returned (or if you are using callbacks, the second argument
|
||||
// to the .exec() callback will be undefined.)
|
||||
// This is just a shortcut for .meta({fetch: true})
|
||||
// Warning: This is not recommended for update/destroy queries that affect large numbers of records.
|
||||
query.fetch()
|
||||
|
||||
// Modify a query instance so that, when executed, it will populate child records for the
|
||||
// specified collection, optionally filtering by subcriteria. Populate may be called more than
|
||||
// once on the same query, as long as each call is for a different association.
|
||||
query.populate()
|
||||
|
||||
// Decrypt any auto-encrypted attributes in the records returned for this particular query.
|
||||
// This is just a shortcut for .meta({decrypt: true})
|
||||
query.decrypt()
|
||||
|
||||
// Execute a Waterline query instance.
|
||||
query.exec(function (err, result) {})
|
||||
|
||||
// Begin executing a Waterline query instance and return a promise.
|
||||
// This is an alternative to .exec().
|
||||
query.toPromise()
|
||||
|
||||
// Capture and intercept the specified error, automatically modifying and re-throwing it,
|
||||
// or specifying a new Error to be thrown instead. (Still throws.)
|
||||
query.intercept(filter, handler)
|
||||
query.intercept(handler)
|
||||
|
||||
// Provide additional options to Waterline when executing a query instance.
|
||||
query.meta(options)
|
||||
|
||||
// Execute a Waterline query instance using promises.
|
||||
// Whenever possible, it is recommended that you use await instead of calling this method.
|
||||
// This is an alternative to .exec(). When combined with .catch(), it provides the same functionality.
|
||||
query.then(callback)
|
||||
|
||||
// Execute a Waterline query instance using promises.
|
||||
// Whenever possible, it is recommended that you use await instead of calling this method.
|
||||
// This is an alternative to .exec(). When combined with .then(), it provides the same functionality.
|
||||
query.catch(callback)
|
||||
|
||||
// Tolerate (swallow) the specified error, and return a new result value (or undefined) instead. (Don't throw.)
|
||||
query.tolerate(filter, handler)
|
||||
query.tolerate(filter)
|
||||
query.tolerate(handler)
|
||||
|
||||
// Specify an existing database connection to use for this query.
|
||||
query.usingConnection(connection)
|
||||
|
||||
/********************************************************************************************
|
||||
* 8. WEB SOCKETS
|
||||
* https://sailsjs.com/documentation/reference/web-sockets
|
||||
********************************************************************************************/
|
||||
|
||||
// --> RESOURCEFUL PUBSUB (HIGHER LEVEL ABSTRACTION WHICH ARE USED BY SAILS BLUEPRINT API) <--
|
||||
|
||||
// Retrieve the name of the PubSub “room” for a given record.
|
||||
MyModel.getRoomName(id)
|
||||
|
||||
// Broadcast an arbitrary message to socket clients subscribed to one or more of this model's records.
|
||||
// Be sure and check req.isSocket === true before passing in req to refer to the requesting socket.
|
||||
// If used, the provided req must be from a socket request, not just any old HTTP request.
|
||||
// Is like sails.sockets.broadcast()
|
||||
MyModel.publish(ids, data, req)
|
||||
|
||||
// Subscribe the requesting client socket to changes/deletions of one or more database records.
|
||||
// Is like sails.sockets.join()
|
||||
MyModel.subscribe(req, ids)
|
||||
|
||||
// Unsubscribe the requesting client socket from one or more database records.
|
||||
// Is like sails.sockets.leave()
|
||||
MyModel.unsubscribe(req, ids)
|
||||
|
||||
// --> SAILS.SOCKETS <--
|
||||
|
||||
// Subscribe all members of a room to one or more additional rooms.
|
||||
// In a multi-server environment, the callback function (cb) will be executed when the
|
||||
// .addRoomMembersToRooms() call completes on the current server. This does not guarantee that
|
||||
// other servers in the cluster have already finished running the operation.
|
||||
sails.sockets.addRoomMembersToRooms(sourceRoom, destRooms, cb)
|
||||
|
||||
// Broadcast a message to all sockets connected to the server (or any server in the cluster,
|
||||
// if you have a multi-server deployment using Redis).
|
||||
sails.sockets.blast(data)
|
||||
sails.sockets.blast(eventName, data)
|
||||
sails.sockets.blast(data, socketToOmit)
|
||||
sails.sockets.blast(eventName, data, socketToOmit)
|
||||
|
||||
// Broadcast a message to all sockets in a room (or to a particular socket).
|
||||
sails.sockets.broadcast(roomNames, data)
|
||||
sails.sockets.broadcast(roomNames, eventName, data)
|
||||
sails.sockets.broadcast(roomNames, data, socketToOmit)
|
||||
sails.sockets.broadcast(roomNames, eventName, data, socketToOmit)
|
||||
|
||||
// Parse the socket ID from an incoming socket request (req).
|
||||
sails.sockets.getId(req)
|
||||
|
||||
// Subscribe a socket to a room.
|
||||
sails.sockets.join(socket, roomName)
|
||||
sails.sockets.join(socket, roomName, cb)
|
||||
|
||||
// Unsubscribe a socket from a room.
|
||||
sails.sockets.leave(socket, roomName)
|
||||
sails.sockets.leave(socket, roomName, cb)
|
||||
|
||||
// Unsubscribe all members of a room (e.g. chatroom7) from that room and every other room
|
||||
// they are currently subscribed to; except the automatic room associated with their socket ID.
|
||||
sails.sockets.leaveAll(roomName, cb)
|
||||
|
||||
// Unsubscribe all members of a room from one or more other rooms.
|
||||
sails.sockets.removeRoomMembersFromRooms(sourceRoom, destRooms, cb)
|
||||
|
||||
// --> SOCKET CLIENT <--
|
||||
|
||||
// Home of global configuration options for the sails.io.js library, as well as any sockets it creates.
|
||||
io.sails
|
||||
|
||||
// Wait one cycle of the event loop after loading and then attempt to create a new SailsSocket
|
||||
// and connect it to the URL specified by io.sails.url.
|
||||
io.sails.autoConnect
|
||||
|
||||
// Sockets will automatically (and continuously) attempt to reconnect to the server
|
||||
// if they become disconnected unexpectedly.
|
||||
io.sails.reconnection
|
||||
|
||||
// Dictionary of headers to be sent by default with every request from this socket.
|
||||
// Can be overridden via the headers option in .request().
|
||||
io.sails.headers
|
||||
|
||||
// Set an environment for sails.io.js, which affects how much information is logged to the console.
|
||||
// Valid values are development (full logs) and production (minimal logs).
|
||||
io.sails.environment
|
||||
|
||||
// The URL that the socket is connected to, or will attempt to connect to.
|
||||
io.sails.url
|
||||
|
||||
// The transports that the socket will attempt to connect using.
|
||||
io.sails.transports
|
||||
|
||||
// Used for creating new socket connections manually.
|
||||
io.sails.connect([url], [options])
|
||||
|
||||
// Unbind the specified event handler (opposite of .on()).
|
||||
// To force a client socket to stop receiving broadcasted messages, do not use this method.
|
||||
// Instead, unsubscribe the socket in your server-side code:
|
||||
// In order to use .off(), you will need to store the handlerFn argument you passed in to .on() in a variable.
|
||||
io.socket.off(eventIdentity, handlerFn)
|
||||
|
||||
// Start listening for socket events from Sails with the specified eventName.
|
||||
// Will trigger the provided callback function when a matching event is received.
|
||||
// This happens when the server broadcasts a message to this socket directly, or to a room of which it is a member.
|
||||
io.socket.on(eventName, function (msg) { })
|
||||
|
||||
// Send a virtual DELETE request to a Sails server using Socket.io.
|
||||
io.socket.delete(url, data, function (data, jwres) {})
|
||||
|
||||
// Send a socket request(virtual GET) to a Sails server using Socket.io.
|
||||
io.socket.get(url, data, function (resData, jwres) {})
|
||||
|
||||
// Send a socket request (virtual PATCH) to a Sails server using Socket.io.
|
||||
io.socket.patch(url, data, function (resData, jwres) {})
|
||||
|
||||
// Send a socket request (virtual POST) to a Sails server using Socket.io.
|
||||
io.socket.post(url, data, function (resData, jwres) {})
|
||||
|
||||
// Send a socket request (virtual PUT) to a Sails server using Socket.io.
|
||||
io.socket.put(url, data, function (resData, jwres) {})
|
||||
|
||||
// Send a virtual request to a Sails server using Socket.io.
|
||||
io.socket.request(options, function (resData, jwres) {})
|
||||
@@ -49,6 +49,7 @@ LINSERT key BEFORE|AFTER pivot value # insert an element before or after anothe
|
||||
LLEN key # return the current length of the list
|
||||
LPOP key # remove the first element from the list and returns it
|
||||
LSET key index value # set the value of an element in a list by its index
|
||||
LREM key number_of_occurrences value # delete occurrences of value if the list stored in key
|
||||
LTRIM key start stop # trim a list to the specified range
|
||||
RPOP key # remove the last element from the list and returns it
|
||||
RPOPLPUSH source destination # remove the last element in a list, prepend it to another list and return it
|
||||
|
||||
443
frontend/angular.js
vendored
Normal file
443
frontend/angular.js
vendored
Normal file
@@ -0,0 +1,443 @@
|
||||
/* *******************************************************************************************
|
||||
* ANGULAR (2+) CHEATSHEET
|
||||
* BASED ON https://angular.io/guide/cheatsheet
|
||||
* DOCUMENTATION: https://angular.io/docs
|
||||
* STYLE GUIDE: https://angular.io/guide/styleguide
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
```
|
||||
npm install --save @angular/cli // install command line interface (CLI) for Angular apps
|
||||
ng serve // serve the app
|
||||
ng build // build the release
|
||||
```
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* BOOSTRAPPING
|
||||
* https://angular.io/guide/bootstrapping
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
|
||||
|
||||
// Bootstraps the app, using the root component from the specified NgModule.
|
||||
platformBrowserDynamic().bootstrapModule(AppModule);
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* NG MODULES
|
||||
* https://angular.io/guide/ngmodules
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
import { NgModule } from '@angular/core';
|
||||
|
||||
@NgModule({
|
||||
declarations: ...,
|
||||
imports: ...,
|
||||
exports: ...,
|
||||
providers: ...,
|
||||
bootstrap: ...
|
||||
})
|
||||
|
||||
// Defines a module that contains components, directives, pipes, and providers.
|
||||
class MyModule {}
|
||||
|
||||
// List of components, directives, and pipes that belong to this module.
|
||||
declarations: [MyRedComponent, MyBlueComponent, MyDatePipe]
|
||||
|
||||
// List of modules to import into this module. Everything from the imported modules is available
|
||||
// to declarations of this module.
|
||||
imports: [BrowserModule, SomeOtherModule]
|
||||
|
||||
// List of components, directives, and pipes visible to modules that import this module.
|
||||
exports: [MyRedComponent, MyDatePipe]
|
||||
|
||||
// List of dependency injection providers visible both to the contents of this module and to
|
||||
// importers of this module.
|
||||
providers: [MyService, { provide: ... }]
|
||||
|
||||
// List of components to bootstrap when this module is bootstrapped.
|
||||
bootstrap: [MyAppComponent]
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* TEMPLATE SYNTAX
|
||||
* https://angular.io/guide/template-syntax
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
// Binds property value to the result of expression firstName.
|
||||
// <input [value]="firstName">
|
||||
|
||||
// Binds attribute role to the result of expression myAriaRole.
|
||||
// <div [attr.role]="myAriaRole">
|
||||
|
||||
// Binds the presence of the CSS class extra-sparkle on the element to the truthiness of the
|
||||
// expression isDelightful.
|
||||
// <div [class.extra-sparkle]="isDelightful">
|
||||
|
||||
// Binds style property width to the result of expression mySize in pixels. Units are optional.
|
||||
// <div [style.width.px]="mySize">
|
||||
|
||||
// Calls method readRainbow when a click event is triggered on this button element (or its
|
||||
// children) and passes in the event object.
|
||||
// <button (click)="readRainbow($event)">
|
||||
|
||||
// Binds a property to an interpolated string, for example, "Hello Seabiscuit".
|
||||
// Equivalent to: <div [title]="'Hello ' + ponyName">
|
||||
// <div title="Hello {{ponyName}}">
|
||||
|
||||
// Binds text content to an interpolated string, for example, "Hello Seabiscuit".
|
||||
// <p>Hello {{ponyName}}</p>
|
||||
|
||||
// Sets up two-way data binding. Equivalent to: <my-cmp [title]="name" (titleChange)="name=$event">
|
||||
// <my-cmp [(title)]="name">
|
||||
|
||||
// Creates a local variable movieplayer that provides access to the video element instance in
|
||||
// data-binding and event-binding expressions in the current template.
|
||||
// <video #movieplayer ...>
|
||||
// <button (click)="movieplayer.play()">
|
||||
// </video>
|
||||
|
||||
// The * symbol turns the current element into an embedded template.
|
||||
// Equivalent to: <ng-template [myUnless]="myExpression"><p>...</p></ng-template>
|
||||
// <p *myUnless="myExpression">...</p>
|
||||
|
||||
// Transforms the current value of expression cardNumber via the pipe called myCardNumberFormatter.
|
||||
// <p>Card No.: {{cardNumber | myCardNumberFormatter}}</p>
|
||||
|
||||
// The safe navigation operator (?) means that the employer field is optional and if undefined,
|
||||
// the rest of the expression should be ignored.
|
||||
// <p>Employer: {{employer?.companyName}}</p>
|
||||
|
||||
// An SVG snippet template needs an svg: prefix on its root element to disambiguate the SVG
|
||||
// element from an HTML component.
|
||||
// <svg:rect x="0" y="0" width="100" height="100"/>
|
||||
|
||||
// An <svg> root element is detected as an SVG element automatically, without the prefix.
|
||||
// <svg>
|
||||
// <rect x="0" y="0" width="100" height="100"/>
|
||||
// </svg>
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* BUILT-IN DIRECTIVES
|
||||
* https://angular.io/guide/attribute-directives
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
import { CommonModule } from '@angular/common';
|
||||
|
||||
// Removes or recreates a portion of the DOM tree based on the showSection expression.
|
||||
// <section *ngIf="showSection">
|
||||
|
||||
// Turns the li element and its contents into a template, and uses that to instantiate a view for
|
||||
// each item in list.
|
||||
// <li *ngFor="let item of list">
|
||||
|
||||
// Conditionally swaps the contents of the div by selecting one of the embedded templates based on
|
||||
// the current value of conditionExpression.
|
||||
// <div [ngSwitch]="conditionExpression">
|
||||
// <ng-template [ngSwitchCase]="case1Exp">...</ng-template>
|
||||
// <ng-template ngSwitchCase="case2LiteralString">...</ng-template>
|
||||
// <ng-template ngSwitchDefault>...</ng-template>
|
||||
// </div>
|
||||
|
||||
// Binds the presence of CSS classes on the element to the truthiness of the associated map
|
||||
// values. The right-hand expression should return {class-name: true/false} map.
|
||||
// <div [ngClass]="{'active': isActive, 'disabled': isDisabled}">
|
||||
|
||||
// Allows you to assign styles to an HTML element using CSS. You can use CSS directly, as in the
|
||||
// first example, or you can call a method from the component.
|
||||
// <div [ngStyle]="{'property': 'value'}">
|
||||
// <div [ngStyle]="dynamicStyles()">
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* FORMS
|
||||
* https://angular.io/guide/forms
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
import { FormsModule } from '@angular/forms';
|
||||
|
||||
// Provides two-way data-binding, parsing, and validation for form controls.
|
||||
// <input [(ngModel)]="userName">
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* CLASS DECORATORS
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
import { Directive, ... } from '@angular/core';
|
||||
|
||||
// Declares that a class is a component and provides metadata about the component.
|
||||
@Component({...})
|
||||
class MyComponent() {}
|
||||
|
||||
// Declares that a class is a directive and provides metadata about the directive.
|
||||
@Directive({...})
|
||||
class MyDirective() {}
|
||||
|
||||
// Declares that a class is a pipe and provides metadata about the pipe.
|
||||
@Pipe({...})
|
||||
class MyPipe() {}
|
||||
|
||||
// Declares that a class can be injected into the constructor of another class
|
||||
// by the dependency injector.
|
||||
@Injectable()
|
||||
class MyService() {}
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* DIRECTIVE CONFIGURATION
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
@Directive({ property1: value1, ... })
|
||||
|
||||
// Specifies a CSS selector that identifies this directive within a template. Supported selectors
|
||||
// include element, [attribute], .class, and :not().
|
||||
selector: '.cool-button:not(a)'
|
||||
|
||||
// Does not support parent-child relationship selectors.
|
||||
|
||||
// List of dependency injection providers for this directive and its children.
|
||||
providers: [MyService, { provide: ... }]
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* COMPONENT CONFIGURATION
|
||||
* https://angular.io/api/core/Component
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
@Component extends @Directive, so the @Directive configuration applies to components as well
|
||||
|
||||
// If set, the templateUrl and styleUrl are resolved relative to the component.
|
||||
moduleId: module.id
|
||||
|
||||
// List of dependency injection providers scoped to this component's view.
|
||||
viewProviders: [MyService, { provide: ... }]
|
||||
|
||||
// Inline template or external template URL of the component's view.
|
||||
template: 'Hello {{name}}'
|
||||
templateUrl: 'my-component.html'
|
||||
|
||||
// List of inline CSS styles or external stylesheet URLs for styling the component’s view.
|
||||
styles: ['.primary {color: red}']
|
||||
styleUrls: ['my-component.css']
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* CLASS FIELD DECORATORS FOR DIRECTIVES AND COMPONENTS
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
import { Input, ... } from '@angular/core';
|
||||
|
||||
// Declares an input property that you can update via property binding
|
||||
// (example: <my-cmp [myProperty]="someExpression">).
|
||||
@Input() myProperty;
|
||||
|
||||
// Declares an output property that fires events that you can subscribe to with an event binding
|
||||
// (example: <my-cmp (myEvent)="doSomething()">).
|
||||
@Output() myEvent = new EventEmitter();
|
||||
|
||||
// Binds a host element property (here, the CSS class valid) to a directive/component property
|
||||
// (isValid).
|
||||
@HostBinding('class.valid') isValid;
|
||||
|
||||
// Subscribes to a host element event (click) with a directive/component method (onClick),
|
||||
// optionally passing an argument ($event).
|
||||
@HostListener('click', ['$event']) onClick(e) {...}
|
||||
|
||||
// Binds the first result of the component content query (myPredicate) to a property
|
||||
// (myChildComponent) of the class.
|
||||
@ContentChild(myPredicate) myChildComponent;
|
||||
|
||||
// Binds the results of the component content query (myPredicate) to a property
|
||||
// (myChildComponents) of the class.
|
||||
@ContentChildren(myPredicate) myChildComponents;
|
||||
|
||||
// Binds the first result of the component view query (myPredicate) to a property
|
||||
// (myChildComponent) of the class. Not available for directives.
|
||||
@ViewChild(myPredicate) myChildComponent;
|
||||
|
||||
// Binds the results of the component view query (myPredicate) to a property (myChildComponents)
|
||||
// of the class. Not available for directives.
|
||||
@ViewChildren(myPredicate) myChildComponents;
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* DIRECTIVE AND COMPONENT CHANGE DETECTION AND LIFECYCLE HOOKS
|
||||
* ******************************************************************************************* */
|
||||
|
||||
// (implemented as class methods)
|
||||
|
||||
// Called before any other lifecycle hook. Use it to inject dependencies, but avoid any serious
|
||||
// work here.
|
||||
constructor(myService: MyService, ...) { ... }
|
||||
|
||||
// Called after every change to input properties and before processing content or child views.
|
||||
ngOnChanges(changeRecord) { ... }
|
||||
|
||||
// Called after the constructor, initializing input properties, and the first call to ngOnChanges.
|
||||
ngOnInit() { ... }
|
||||
|
||||
// Called every time that the input properties of a component or a directive are checked. Use it
|
||||
// to extend change detection by performing a custom check.
|
||||
ngDoCheck() { ... }
|
||||
|
||||
// Called after ngOnInit when the component's or directive's content has been initialized.
|
||||
ngAfterContentInit() { ... }
|
||||
|
||||
// Called after every check of the component's or directive's content.
|
||||
ngAfterContentChecked() { ... }
|
||||
|
||||
// Called after ngAfterContentInit when the component's views and child views / the view that a
|
||||
// directive is in has been initialized.
|
||||
ngAfterViewInit() { ... }
|
||||
|
||||
// Called after every check of the component's views and child views / the view that a directive
|
||||
// is in.
|
||||
ngAfterViewChecked() { ... }
|
||||
|
||||
// Called once, before the instance is destroyed.
|
||||
ngOnDestroy() { ... }
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* DEPENDENCY INJECTION CONFIGURATION
|
||||
* https://angular.io/guide/dependency-injection
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
// Sets or overrides the provider for MyService to the MyMockService class.
|
||||
{ provide: MyService, useClass: MyMockService }
|
||||
|
||||
// Sets or overrides the provider for MyService to the myFactory factory function.
|
||||
{ provide: MyService, useFactory: myFactory }
|
||||
|
||||
// Sets or overrides the provider for MyValue to the value 41.
|
||||
{ provide: MyValue, useValue: 41 }
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* ROUTING AND NAVIGATION
|
||||
* https://angular.io/guide/router
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
import { Routes, RouterModule, ... } from '@angular/router';
|
||||
|
||||
const routes: Routes = [
|
||||
{ path: '', component: HomeComponent },
|
||||
{ path: 'path/:routeParam', component: MyComponent },
|
||||
{ path: 'staticPath', component: ... },
|
||||
{ path: '**', component: ... },
|
||||
{ path: 'oldPath', redirectTo: '/staticPath' },
|
||||
{ path: ..., component: ..., data: { message: 'Custom' } }
|
||||
]);
|
||||
|
||||
// Configures routes for the application. Supports static, parameterized, redirect, and wildcard
|
||||
// routes. Also supports custom route data and resolve.
|
||||
const routing = RouterModule.forRoot(routes);
|
||||
|
||||
// Marks the location to load the component of the active route.
|
||||
// <router-outlet></router-outlet>
|
||||
// <router-outlet name="aux"></router-outlet>
|
||||
|
||||
// Creates a link to a different view based on a route instruction consisting of a route path,
|
||||
// required and optional parameters, query parameters, and a fragment. To navigate to a root
|
||||
// route, use the / prefix; for a child route, use the ./prefix; for a sibling or parent, use the
|
||||
// ../ prefix.
|
||||
// <a routerLink="/path">
|
||||
// <a [routerLink]="[ '/path', routeParam ]">
|
||||
// <a [routerLink]="[ '/path', { matrixParam: 'value' } ]">
|
||||
// <a [routerLink]="[ '/path' ]" [queryParams]="{ page: 1 }">
|
||||
// <a [routerLink]="[ '/path' ]" fragment="anchor">
|
||||
|
||||
// The provided classes are added to the element when the routerLink becomes the current active
|
||||
// route.
|
||||
// <a [routerLink]="[ '/path' ]" routerLinkActive="active">
|
||||
|
||||
class CanActivateGuard implements CanActivate {
|
||||
canActivate(
|
||||
route: ActivatedRouteSnapshot,
|
||||
state: RouterStateSnapshot
|
||||
): Observable<boolean>|Promise<boolean>|boolean { ... }
|
||||
}
|
||||
|
||||
// An interface for defining a class that the router should call first to determine if it should
|
||||
// activate this component. Should return a boolean or an Observable/Promise that resolves to a
|
||||
// boolean.
|
||||
{
|
||||
path: ...,
|
||||
canActivate: [CanActivateGuard]
|
||||
}
|
||||
|
||||
class CanDeactivateGuard implements CanDeactivate<T> {
|
||||
canDeactivate(
|
||||
component: T,
|
||||
route: ActivatedRouteSnapshot,
|
||||
state: RouterStateSnapshot
|
||||
): Observable<boolean>|Promise<boolean>|boolean { ... }
|
||||
}
|
||||
|
||||
// An interface for defining a class that the router should call first to determine if it should
|
||||
// deactivate this component after a navigation. Should return a boolean or an Observable/Promise
|
||||
// that resolves to a boolean.
|
||||
{
|
||||
path: ...,
|
||||
canDeactivate: [CanDeactivateGuard]
|
||||
}
|
||||
|
||||
class CanActivateChildGuard implements CanActivateChild {
|
||||
canActivateChild(
|
||||
route: ActivatedRouteSnapshot,
|
||||
state: RouterStateSnapshot
|
||||
): Observable<boolean>|Promise<boolean>|boolean { ... }
|
||||
}
|
||||
|
||||
// An interface for defining a class that the router should call first to determine if it should
|
||||
// activate the child route. Should return a boolean or an Observable/Promise that resolves to a
|
||||
// boolean.
|
||||
{
|
||||
path: ...,
|
||||
canActivateChild: [CanActivateGuard],
|
||||
children: ...
|
||||
}
|
||||
|
||||
class ResolveGuard implements Resolve<T> {
|
||||
resolve(
|
||||
route: ActivatedRouteSnapshot,
|
||||
state: RouterStateSnapshot
|
||||
): Observable<any>|Promise<any>|any { ... }
|
||||
}
|
||||
|
||||
// An interface for defining a class that the router should call first to resolve route data
|
||||
// before rendering the route. Should return a value or an Observable/Promise that resolves to a
|
||||
// value.
|
||||
{
|
||||
path: ...,
|
||||
resolve: [ResolveGuard]
|
||||
}
|
||||
|
||||
class CanLoadGuard implements CanLoad {
|
||||
canLoad(
|
||||
route: Route
|
||||
): Observable<boolean>|Promise<boolean>|boolean { ... }
|
||||
}
|
||||
|
||||
// An interface for defining a class that the router should call first to check if the lazy loaded
|
||||
// module should be loaded. Should return a boolean or an Observable/Promise that resolves to a
|
||||
// boolean.
|
||||
{
|
||||
path: ...,
|
||||
canLoad: [CanLoadGuard],
|
||||
loadChildren: ...
|
||||
}
|
||||
434
frontend/angularjs.js
vendored
Normal file
434
frontend/angularjs.js
vendored
Normal file
@@ -0,0 +1,434 @@
|
||||
/* *******************************************************************************************
|
||||
* ANGULARJS CHEATSHEET
|
||||
* API DOCUMENTATION: https://docs.angularjs.org/api
|
||||
* DEVELOPER GUIDE: https://docs.angularjs.org/guide
|
||||
* ERROR REFERENCE: https://docs.angularjs.org/error
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* TIPS & TRICKS
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
// You can retrieve a scope for any DOM element by using:
|
||||
angular.element(aDomElement).scope()
|
||||
|
||||
// An object that contains information about the current AngularJS version.
|
||||
// This object has the following properties: full, major, minor, dot, codeName
|
||||
angular.version
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* CSS CLASS USED BY ANGULAR
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
// AngularJS applies this class to any element for which a new scope is defined.
|
||||
ng-scope
|
||||
|
||||
// AngularJS applies this class to any element for which a new isolate scope is defined.
|
||||
ng-isolate-scope
|
||||
|
||||
// AngularJS applies this class to any element that is attached to a data binding, via ng-bind or {{}} curly braces, for example.
|
||||
ng-binding
|
||||
|
||||
// AngularJS applies this class to a form control widget element if that element's input does not pass validation.
|
||||
ng-invalid, ng-valid
|
||||
|
||||
// AngularJS ngModel directive applies ng-pristine class to a new form control widget which did not have user interaction.
|
||||
// Once the user interacts with the form control, the class is changed to ng-dirty.
|
||||
ng-pristine, ng-dirty
|
||||
|
||||
// AngularJS ngModel directive applies ng-untouched class to a new form control widget which has not been blurred.
|
||||
// Once the user blurs the form control, the class is changed to ng-touched.
|
||||
ng-touched, ng-untouched
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* NG MODULE > FUNCTIONS
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
// Returns a function which calls function fn bound to self (self becomes the this for fn).
|
||||
// You can supply optional args that are prebound to the function.
|
||||
// This feature is also known as partial application, as distinguished from function currying.
|
||||
angular.bind(self, fn, args)
|
||||
|
||||
// Use this function to manually start up AngularJS application.
|
||||
angular.bootstrap(element, [modules], [config])
|
||||
|
||||
// Creates a deep copy of source, which should be an object or an array.
|
||||
angular.copy(source, [destination])
|
||||
|
||||
// Wraps a raw DOM element or HTML string as a jQuery element.
|
||||
angular.element(element)
|
||||
|
||||
// Determines if two objects or two values are equivalent.
|
||||
// Supports value types, regular expressions, arrays and objects.
|
||||
angular.equals(o1, o2)
|
||||
|
||||
// Configure several aspects of error handling in AngularJS if used as a setter or return the current configuration if used as a getter.
|
||||
angular.errorHandlingConfig([config])
|
||||
|
||||
// Extends the destination object dst by copying own enumerable properties from the src object(s) to dst.
|
||||
// You can specify multiple src objects.
|
||||
angular.extend(dst, src)
|
||||
|
||||
// Invokes the iterator function once for each item in obj collection, which can be either an object or an array.
|
||||
angular.forEach(obj, iterator, [context])
|
||||
|
||||
// Deserializes a JSON string.
|
||||
angular.fromJson(json)
|
||||
|
||||
// A function that returns its first argument.
|
||||
// This function is useful when writing code in the functional style.
|
||||
angular.identity(value)
|
||||
|
||||
// Creates an injector object that can be used for retrieving services as well as for dependency injection.
|
||||
angular.injector(modules, [strictDi])
|
||||
|
||||
// Determines if a reference is an Array.
|
||||
angular.isArray(value)
|
||||
|
||||
// Determines if a value is a date.
|
||||
angular.isDate(value)
|
||||
|
||||
// Determines if a reference is defined.
|
||||
angular.isDefined(value)
|
||||
|
||||
// Determines if a reference is a DOM element (or wrapped jQuery element).
|
||||
angular.isElement(value)
|
||||
|
||||
// Determines if a reference is a Function.
|
||||
angular.isFunction(value)
|
||||
|
||||
// Determines if a reference is a Number.
|
||||
angular.isNumber(value)
|
||||
|
||||
// Determines if a reference is an Object. Unlike typeof in JavaScript, nulls are not considered to be objects.
|
||||
angular.isObject(value)
|
||||
|
||||
// Determines if a reference is a String.
|
||||
angular.isString(value)
|
||||
|
||||
// Determines if a reference is undefined.
|
||||
angular.isUndefined(value)
|
||||
|
||||
// The angular.module is a global place for creating, registering and retrieving AngularJS modules.
|
||||
// All modules (AngularJS core or 3rd party) that should be available to an application must be registered using this mechanism.
|
||||
// Passing one argument retrieves an existing angular.Module, whereas passing more than one argument creates a new angular.Module
|
||||
angular.module(name, [requires], [configFn])
|
||||
|
||||
// A function that performs no operations.
|
||||
// This function can be useful when writing code in the functional style.
|
||||
angular.noop()
|
||||
|
||||
// Use this function to reload the current application with debug information turned on.
|
||||
// This takes precedence over a call to $compileProvider.debugInfoEnabled(false).
|
||||
angular.reloadWithDebugInfo()
|
||||
|
||||
// Serializes input into a JSON-formatted string.
|
||||
// Properties with leading $$ characters will be stripped since AngularJS uses this notation internally.
|
||||
angular.toJson(obj, pretty)
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* NG MODULE > DIRECTIVES
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
// Use this directive to auto-bootstrap an AngularJS application.
|
||||
// Only one AngularJS application can be auto-bootstrapped per HTML document.
|
||||
// You can specify an AngularJS module to be used as the root module for the application.
|
||||
'ng-app'
|
||||
|
||||
// The ngBind attribute tells AngularJS to replace the text content of the specified HTML element with
|
||||
// the value of a given expression, and to update the text content when the value of that expression changes.
|
||||
'ng-bind'
|
||||
|
||||
// Evaluates the expression and inserts the resulting HTML into the element in a secure way.
|
||||
'ng-bind-html'
|
||||
|
||||
// The ngBindTemplate directive specifies that the element text content should be replaced with
|
||||
// the interpolation of the template in the ngBindTemplate attribute.
|
||||
'ng-bind-template'
|
||||
|
||||
// Specify custom behavior on blur event.
|
||||
'ng-blur'
|
||||
|
||||
// Evaluate the given expression when the user changes the input.
|
||||
'ng-change'
|
||||
|
||||
// Sets the checked attribute on the element, if the expression inside ngChecked is truthy.
|
||||
'ng-checked'
|
||||
|
||||
// The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding
|
||||
// an expression that represents all classes to be added.
|
||||
'ng-class'
|
||||
|
||||
// The ngClassOdd and ngClassEven directives work exactly as ngClass, except they work in
|
||||
// conjunction with ngRepeat and take effect only on odd (even) rows.
|
||||
'ng-class-even'
|
||||
|
||||
// The ngClassOdd and ngClassEven directives work exactly as ngClass, except they work in
|
||||
// conjunction with ngRepeat and take effect only on odd (even) rows.
|
||||
'ng-class-odd'
|
||||
|
||||
// The ngClick directive allows you to specify custom behavior when an element is clicked.
|
||||
'ng-click'
|
||||
|
||||
// The ngCloak directive is used to prevent the AngularJS html template from being briefly displayed
|
||||
// by the browser in its raw (uncompiled) form while your application is loading.
|
||||
'ng-cloak'
|
||||
|
||||
// The ngController directive attaches a controller class to the view.
|
||||
'ng-controller'
|
||||
|
||||
// Specify custom behavior on copy event.
|
||||
'ng-copy'
|
||||
|
||||
// Specify custom behavior on cut event.
|
||||
'ng-cut'
|
||||
|
||||
// Allows you to specify custom behavior on a dblclick event.
|
||||
'ng-dblclick'
|
||||
|
||||
// This directive sets the disabled attribute on the element (typically a form control, e.g. input, button, select etc.)
|
||||
// if the expression inside ngDisabled evaluates to truthy.
|
||||
'ng-disabled'
|
||||
|
||||
// Specify custom behavior on focus event.
|
||||
'ng-focus'
|
||||
|
||||
// Nestable alias of form directive. HTML does not allow nesting of form elements.
|
||||
// It is useful to nest forms, for example if the validity of a sub-group of controls needs to be determined.
|
||||
'ng-form'
|
||||
|
||||
// Shows or hides the given HTML element based on the expression provided to the ngHide attribute.
|
||||
'ng-hide'
|
||||
|
||||
// Executes the expression and replaces with the right href link
|
||||
'ng-href'
|
||||
|
||||
// Removes or recreates a portion of the DOM tree based on an {expression}.
|
||||
'ng-if'
|
||||
|
||||
// Fetches, compiles and includes an external HTML fragment.
|
||||
'ng-include'
|
||||
|
||||
// Allows you to evaluate an expression in the current scope.
|
||||
'ng-init'
|
||||
|
||||
// Force the angular.element library.
|
||||
// This should be used to force either jqLite by leaving ng-jq blank or setting the name of the jquery variable under window (eg. jQuery).
|
||||
'ng-jq'
|
||||
|
||||
// Specify custom behavior on keydown event.
|
||||
'ng-keydown'
|
||||
|
||||
// Specify custom behavior on keypress event.
|
||||
'ng-keypress'
|
||||
|
||||
// Specify custom behavior on keyup event.
|
||||
'ng-keyup'
|
||||
|
||||
// Text input that converts between a delimited string and an array of strings.
|
||||
'ng-list'
|
||||
|
||||
// Adds the maxlength validator to ngModel.
|
||||
'ng-maxlength'
|
||||
|
||||
// Adds the minlength validator to ngModel.
|
||||
'ng-minlength'
|
||||
|
||||
// The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope using NgModelController,
|
||||
// which is created and exposed by this directive.
|
||||
'ng-model'
|
||||
|
||||
// Modify the behaviour of ngModel directives within your application.
|
||||
// You can specify an ngModelOptions directive on any element.
|
||||
// All ngModel directives will use the options of their nearest ngModelOptions ancestor.
|
||||
'ng-model-options'
|
||||
|
||||
// Allows you to specify custom behavior on mousedown event.
|
||||
'ng-mousedown'
|
||||
|
||||
// Specify custom behavior on mouseenter event.
|
||||
'ng-mouseenter'
|
||||
|
||||
// Specify custom behavior on mouseleave event.
|
||||
'ng-mouseleave'
|
||||
|
||||
// Specify custom behavior on mousemove event.
|
||||
'ng-mousemove'
|
||||
|
||||
// Specify custom behavior on mouseover event.
|
||||
'ng-mouseover'
|
||||
|
||||
// Specify custom behavior on mouseup event.
|
||||
'ng-mouseup'
|
||||
|
||||
// Tells AngularJS not to compile or bind the contents of the current DOM element,
|
||||
// including directives on the element itself that have a lower priority than ngNonBindable.
|
||||
'ng-non-bindable'
|
||||
|
||||
// Sets the open attribute on the element, if the expression inside ngOpen is truthy.
|
||||
'ng-open'
|
||||
|
||||
// The ngOptions attribute can be used to dynamically generate a list of <option> elements for the <select>
|
||||
// element using the array or object obtained by evaluating the ngOptions comprehension expression.
|
||||
'ng-options'
|
||||
|
||||
// Specify custom behavior on paste event.
|
||||
'ng-paste'
|
||||
|
||||
// ngPattern adds the pattern validator to ngModel.
|
||||
// It is most often used for text-based input controls, but can also be applied to custom text-based controls.
|
||||
'ng-pattern'
|
||||
|
||||
// Displays messages according to en-US localization rules.
|
||||
'ng-pluralize'
|
||||
|
||||
// Sets the readonly attribute on the element, if the expression inside ngReadonly is truthy
|
||||
'ng-readonly'
|
||||
|
||||
// Instantiates a template once per item from a collection
|
||||
// Special properties are exposed on the local scope of each template instance, including:
|
||||
// $index, $first, $middle, $last, $even, $odd
|
||||
'ng-repeat'
|
||||
|
||||
// ngRequired adds the required validator to ngModel.
|
||||
// It is most often used for input and select controls, but can also be applied to custom controls.
|
||||
'ng-required'
|
||||
|
||||
// Sets the selected attribute on the element, if the expression inside ngSelected is truthy.
|
||||
'ng-selected'
|
||||
|
||||
// Shows or hides the given HTML element based on the expression provided to the ngShow attribute.
|
||||
'ng-show'
|
||||
|
||||
// Using AngularJS markup like {{hash}} in a src attribute doesn't work right:
|
||||
// The browser will fetch from the URL with the literal text {{hash}} until AngularJS
|
||||
// replaces the expression inside {{hash}}. The ngSrc directive solves this problem.
|
||||
'ng-src'
|
||||
|
||||
// Using AngularJS markup like {{hash}} in a srcset attribute doesn't work right:
|
||||
// The browser will fetch from the URL with the literal text {{hash}} until AngularJS
|
||||
// replaces the expression inside {{hash}}. The ngSrcset directive solves this problem.
|
||||
'ng-srcset'
|
||||
|
||||
// Allows you to set CSS style on an HTML element conditionally.
|
||||
'ng-style'
|
||||
|
||||
// Enables binding AngularJS expressions to onsubmit events.
|
||||
'ng-submit'
|
||||
|
||||
// Used to conditionally swap DOM structure on your template based on a scope expression.
|
||||
'ng-switch'
|
||||
|
||||
// Marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
|
||||
'ng-transclude'
|
||||
|
||||
// Binds the given expression to the value of the element.
|
||||
// It is mainly used on input[radio] and option elements, so that when the element is selected,
|
||||
// the ngModel of that element (or its select parent element) is set to the bound value.
|
||||
'ng-value'
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* NG MODULE > TYPE
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
// A cache object used to store and retrieve data, primarily used by $templateRequest
|
||||
// and the script directive to cache templates and other data.
|
||||
$cacheFactory.Cache
|
||||
|
||||
// Don't forget the cache
|
||||
|
||||
// A shared object between directive compile / linking functions which contains normalized
|
||||
// DOM element attributes. The values reflect current binding state {{ }}.
|
||||
$compile.directive.Attributes
|
||||
|
||||
// Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with x- or data-)
|
||||
// to its normalized, camelCase form.
|
||||
$compile.directive.Attributes.$normalize(name)
|
||||
|
||||
// Adds the CSS class value specified by the classVal parameter to the element.
|
||||
// If animations are enabled then an animation will be triggered for the class addition.
|
||||
$compile.directive.Attributes.$addClass(classVal)
|
||||
|
||||
// Removes the CSS class value specified by the classVal parameter from the element.
|
||||
// If animations are enabled then an animation will be triggered for the class removal.
|
||||
$compile.directive.Attributes.$removeClass(classVal)
|
||||
|
||||
// Adds and removes the appropriate CSS class values to the element based on the difference
|
||||
// between the new and old CSS class values (specified as newClasses and oldClasses).
|
||||
$compile.directive.Attributes.$updateClass(newClasses, oldClasses)
|
||||
|
||||
// Observes an interpolated attribute.
|
||||
$compile.directive.Attributes.$observe(key, fn)
|
||||
|
||||
// Set DOM element attribute value.
|
||||
$compile.directive.Attributes.$set(name, value)
|
||||
|
||||
// A map of DOM element attribute names to the normalized name.
|
||||
// This is needed to do reverse lookup from normalized name back to actual name.
|
||||
$compile.directive.Attributes.$attr
|
||||
|
||||
// A root scope can be retrieved using the $rootScope key from the $injector.
|
||||
$rootScope.Scope([providers], [instanceCache])
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* NG MODULE > FILTERS
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
// Formats a number as a currency (ie $1,234.56).
|
||||
// When no currency symbol is provided, default symbol for current locale is used.
|
||||
{{ currency_expression | currency : symbol : fractionSize}}
|
||||
$filter('currency')(amount, symbol, fractionSize)
|
||||
|
||||
// Formats date to a string based on the requested format.
|
||||
{{ date_expression | date : format : timezone}}
|
||||
$filter('date')(date, format, timezone)
|
||||
|
||||
// Selects a subset of items from array and returns it as a new array.
|
||||
{{ filter_expression | filter : expression : comparator : anyPropertyKey}}
|
||||
$filter('filter')(array, expression, comparator, anyPropertyKey)
|
||||
|
||||
// Allows you to convert a JavaScript object into JSON string.
|
||||
// This filter is mostly useful for debugging.
|
||||
// When using the double curly notation the binding is automatically converted to JSON.
|
||||
{{ json_expression | json : spacing}}
|
||||
$filter('json')(object, spacing)
|
||||
|
||||
// Creates a new array or string containing only a specified number of elements.
|
||||
// The elements are taken from either the beginning or the end of the source array,
|
||||
// string or number, as specified by the value and sign (positive or negative) of limit.
|
||||
// Other array-like objects are also supported (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc).
|
||||
// If a number is used as input, it is converted to a string.
|
||||
{{ limitTo_expression | limitTo : limit : begin}}
|
||||
$filter('limitTo')(input, limit, begin)
|
||||
|
||||
// Converts string to lowercase.
|
||||
{{ lowercase_expression | lowercase}}
|
||||
$filter('lowercase')()
|
||||
|
||||
// Formats a number as text.
|
||||
// If the input is null or undefined, it will just be returned.
|
||||
// If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively.
|
||||
// If the input is not a number an empty string is returned.
|
||||
{{ number_expression | number : fractionSize}}
|
||||
$filter('number')(number, fractionSize)
|
||||
|
||||
// Returns an array containing the items from the specified collection,
|
||||
// ordered by a comparator function based on the values computed using the expression predicate.
|
||||
{{ orderBy_expression | orderBy : expression : reverse : comparator}}
|
||||
$filter('orderBy')(collection, expression, reverse, comparator)
|
||||
|
||||
// Converts string to uppercase.
|
||||
{{ uppercase_expression | uppercase}}
|
||||
$filter('uppercase')()
|
||||
743
frontend/ember.js
Normal file
743
frontend/ember.js
Normal file
@@ -0,0 +1,743 @@
|
||||
/*
|
||||
* -----------------------
|
||||
* Ember.js Cheatsheet
|
||||
* -----------------------
|
||||
*
|
||||
* Docs: https://guides.emberjs.com/
|
||||
* Quick start: https://guides.emberjs.com/current/getting-started/quick-start/
|
||||
*
|
||||
* Table of contents
|
||||
* -------------------
|
||||
* 01 | Installation
|
||||
* 02 | Ember CLI
|
||||
* 03 | Directory layout
|
||||
* 04 | Routes
|
||||
* 05 | Templates
|
||||
* 06 | Components
|
||||
* 07 | Models
|
||||
* 08 | Services
|
||||
* 09 | Testing
|
||||
* 10 | Addons
|
||||
* 11 | Configuration
|
||||
* 12 | Community
|
||||
*
|
||||
*/
|
||||
|
||||
/*
|
||||
* 01 | Installation
|
||||
* --------------------------------------------------------------
|
||||
* Getting started with Ember is easy. Ember projects are created
|
||||
* and managed through our command line build tool Ember CLI.
|
||||
*/
|
||||
|
||||
```
|
||||
npm install -g ember-cli
|
||||
ember new <application-name>
|
||||
ember serve
|
||||
```
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* 02 | Ember CLI
|
||||
* --------------------------------------------------------------
|
||||
* Ember CLI is the Ember.js command line utility that provides a
|
||||
* fast Broccoli-powered asset pipeline, a strong conventional
|
||||
* project structure, and a powerful addon system for extension.
|
||||
*
|
||||
* Among the principal features of Ember CLI are:
|
||||
- Project/Addon creation: create new projects quickly without having to worry about project structure;
|
||||
- Build pipeline: asset compilation, finger-printing and more out of the box;
|
||||
- Generators: use the built-in generators and get files that follow the latest practices, and matching tests;
|
||||
- Ember Addons: extend both your application and Ember CLI itself with community solutions. Also an excellent
|
||||
way to easily integrate 3rd party libraries into your Ember app.
|
||||
*/
|
||||
|
||||
Basic commands
|
||||
|
||||
Command | Aliases | Description
|
||||
--------------------------------------------------
|
||||
```
|
||||
ember new | | Create new project with the provided name (ex. ember new <app-name>)
|
||||
ember server | ember s | Starts development server (default port is 4200)
|
||||
ember test | ember t | Run tests in CI mode
|
||||
ember generate | ember g | Run generator
|
||||
ember destroy | ember d | Remove code created by generator
|
||||
ember help | ember h | Get more info on available cli command
|
||||
ember install | ember i | Install given addon into project and save to package.json
|
||||
ember | | List available cli commands
|
||||
```
|
||||
|
||||
Useful commands
|
||||
```
|
||||
ember s --proxy <proxy-url>
|
||||
ember s --port <port>
|
||||
```
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* 03 | Directory Layout
|
||||
* --------------------------------------------------------------
|
||||
*
|
||||
* Layout of the root folder */
|
||||
|
||||
app/
|
||||
` This is where folders and files for models, components, routes, templates and styles are stored. The majority of your coding on an Ember project happens in this folder. `
|
||||
config/
|
||||
` The config directory contains the environment.js where you can configure settings for your app. `
|
||||
node_modules/
|
||||
` This directory is from npm. npm is the package manager for Node.js. Ember is built with Node and uses a variety of Node.js modules for operation. The package.json file maintains the list of current npm dependencies for the app. Any Ember CLI addons you install will also show up here. `
|
||||
public/
|
||||
` This directory contains assets such as images and fonts. `
|
||||
vendor/
|
||||
` This directory is where front-end dependencies (such as JavaScript or CSS) that are not managed by NPM go. `
|
||||
tests/testem.js
|
||||
` Automated tests for our app go in the tests folder, and Ember CLI's test runner testem is configured in testem.js. `
|
||||
ember-cli-build.js
|
||||
` This file describes how Ember CLI should build our app. `
|
||||
package.json
|
||||
` Packages listed in package.json are installed in the node_modules directory. `
|
||||
|
||||
/*
|
||||
* Layout of the app directory */
|
||||
adapters/
|
||||
` Adapters with the convention adapter-name.js. `
|
||||
components/
|
||||
` Components with the convention component-name.js. Components must have a dash in their name. So blog-post is an acceptable name, but post is not. `
|
||||
controllers/
|
||||
` Controllers behave like a specialized type of Component that is rendered by the router when entering a Route. `
|
||||
helpers/
|
||||
` Helpers with the convention helper-name.js. Helpers must have a dash in their name. Remember that you must register your helpers by exporting makeBoundHelper or calling registerBoundHelper explicitly. `
|
||||
models/
|
||||
` Models with the convention model-name.js. `
|
||||
routes/
|
||||
` Routes with the convention route-name.js. Child routes are defined in sub-directories, parent/child.js. To provide a custom implementation for generated routes (equivalent to App.Route when using globals), use app/routes/basic.js. `
|
||||
styles/
|
||||
` Contains your stylesheets, whether SASS, LESS, Stylus, Compass, or plain CSS (though only one type is allowed, see Asset Compilation). These are all compiled into <app-name>.css. `
|
||||
templates/
|
||||
` Your HTMLBars templates. These are compiled to /dist/assets/<app-name>.js. The templates are named the same as their filename, minus the extension (i.e. templates/foo/bar.hbs -> foo/bar). `
|
||||
serializers/
|
||||
` Serializers for your models or adapter, where model-name.js or adapter-name.js. `
|
||||
utils/
|
||||
` Utility modules with the convention utility-name.js. `
|
||||
router.js
|
||||
` Your route configuration. The routes defined here correspond to routes in app/routes/. `
|
||||
|
||||
|
||||
/*
|
||||
* 03 | Routes
|
||||
* --------------------------------------------------------------
|
||||
*
|
||||
* When your application starts, the router matches the current URL to the routes that you've defined.
|
||||
* The routes, in turn, are responsible for displaying templates, loading data, and setting up application state.
|
||||
*
|
||||
* > ember g route <route-name>
|
||||
*/
|
||||
|
||||
import Route from '@ember/routing/route';
|
||||
|
||||
export default Route.extend({
|
||||
model() {
|
||||
// Typically, the model hook should return an Ember Data record,
|
||||
// but it can also return any promise object (Ember Data records are
|
||||
// promises), or a plain JavaScript object or array. Ember will wait
|
||||
// until the data finishes loading (until the promise is resolved)
|
||||
// before rendering the template.
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* 04 | Templates
|
||||
* --------------------------------------------------------------
|
||||
*
|
||||
* Ember uses the Handlebars templating library to power your app's user
|
||||
* interface. Handlebars templates contain static HTML and dynamic
|
||||
* content inside Handlebars expressions, which are invoked with
|
||||
* double curly braces: {{}}.
|
||||
*
|
||||
* Templates are backed with a context. A context is an object from
|
||||
* which Handlebars expressions read their properties. In Ember this
|
||||
* is often a component. For templates rendered by a route (like application.hbs),
|
||||
* the context is a controller.
|
||||
*
|
||||
* > ember g template <template-name>
|
||||
*/
|
||||
|
||||
|
||||
// Here's an basic exmpale of a template
|
||||
```hbs
|
||||
Hello, <strong>{{firstName}} {{lastName}}</strong>!
|
||||
```
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* 05 | Components
|
||||
* --------------------------------------------------------------
|
||||
*
|
||||
* Ember components are used to encapsulate markup and style into
|
||||
* reusable content. Components consist of two parts: a JavaScript
|
||||
* component file that defines behavior, and its accompanying Handlebars
|
||||
* template that defines the markup for the component's UI.
|
||||
*
|
||||
* > ember g component <component-name>
|
||||
*/
|
||||
|
||||
// app/components/<component-name>.js
|
||||
import Component from '@ember/component';
|
||||
|
||||
export default Component.extend({
|
||||
});
|
||||
|
||||
// app/templates/components/<component-name>.hbs
|
||||
```hbs
|
||||
{{yield}}
|
||||
```
|
||||
|
||||
/*
|
||||
* Actions
|
||||
*
|
||||
* Provide a means to communicate events and changes
|
||||
*/
|
||||
|
||||
// app/components/rental-listing.js
|
||||
import Component from '@ember/component';
|
||||
|
||||
export default Component.extend({
|
||||
|
||||
isWide: false,
|
||||
|
||||
actions: {
|
||||
toggleImageSize() {
|
||||
this.toggleProperty('isWide');
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
// Actions can be attached to DOM elements inside templates using the {{action}} helper
|
||||
``` app/templates/components/rental-listing.hbs
|
||||
<article class="listing">
|
||||
<a {{action 'toggleImageSize'}} class="image {{if isWide "wide"}}">
|
||||
<img src="http://www.fillmurray.com/200/300" alt="">
|
||||
</a>
|
||||
</article>
|
||||
```
|
||||
|
||||
/*
|
||||
* Component lifecycle
|
||||
*
|
||||
* As components are rendered, re-rendered and finally removed, Ember provides
|
||||
* lifecycle hooks that allow you to run code at specific times in a component's life.
|
||||
*/
|
||||
|
||||
On Initial Render
|
||||
1 init
|
||||
2 didReceiveAttrs
|
||||
3 willRender
|
||||
4 didInsertElement // Good place to integrate with 3rd party libraries
|
||||
5 didRender
|
||||
|
||||
On Re-Render
|
||||
1 didUpdateAttrs
|
||||
2 didReceiveAttrs
|
||||
3 willUpdate
|
||||
4 willRender
|
||||
5 didUpdate
|
||||
6 didRender
|
||||
|
||||
On Component Destroy
|
||||
1 willDestroyElement
|
||||
2 willClearRender
|
||||
2 didDestroyElement
|
||||
|
||||
|
||||
/*
|
||||
* Block params
|
||||
*
|
||||
* Components can have properties passed in, but they can also return
|
||||
* output to be used in a block expression.
|
||||
*/
|
||||
|
||||
// Here an entire blog post model is being passed to the component as a
|
||||
// single component property. In turn the component is returning values using yield.
|
||||
|
||||
``` app/templates/index.hbs
|
||||
{{blog-post post=model}}
|
||||
```
|
||||
|
||||
``` app/templates/components/blog-post.hbs
|
||||
{{yield post.title post.body post.author}}
|
||||
```
|
||||
|
||||
// The block expression can then use block params to bind names to any yielded
|
||||
// values for use in the block. This allows for template customization when using
|
||||
// a component, where the markup is provided by the consuming template, but any
|
||||
// event handling behavior implemented in the component is retained such as click() handlers.
|
||||
|
||||
``` app/templates/index.hbs
|
||||
{{#blog-post post=model as |title body author|}}
|
||||
<h2>{{title}}</h2>
|
||||
<p class="author">by {{author}}</p>
|
||||
<p class="post-body">{{body}}</p>
|
||||
{{/blog-post}}
|
||||
```
|
||||
// The names are bound in the order that they are passed to yield in the component template.
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* 06 | Models
|
||||
* --------------------------------------------------------------
|
||||
*
|
||||
* Models are objects that represent the underlying data that your application
|
||||
* presents to the user. Different apps will have very different models,
|
||||
* depending on what problems they're trying to solve.
|
||||
*
|
||||
* Ember Data, included by default when you create a new application,
|
||||
* is a library that integrates tightly with Ember to make it easy to
|
||||
* retrieve models from your server as JSON, save updates back to the server,
|
||||
* and create new models in the browser.
|
||||
*
|
||||
* > ember g model <model-name>
|
||||
*/
|
||||
|
||||
import DS from 'ember-data';
|
||||
import { computed } from '@ember/object';
|
||||
|
||||
const { attr, Model } = DS;
|
||||
|
||||
export default Model.extend({
|
||||
|
||||
firstName: attr('string'),
|
||||
lastName: attr('string'),
|
||||
birthday: attr('date'),
|
||||
|
||||
|
||||
// Computed properties
|
||||
// These are effectively fuctions declared as properties. The function's result
|
||||
// will recompute every time one of the provided 'dependent keys' changes.
|
||||
|
||||
fullName: computed('firstName', 'lastName', function() {
|
||||
let firstName = this.get('firstName');
|
||||
let lastName = this.get('lastName');
|
||||
|
||||
return `${firstName} ${lastName}`;
|
||||
})
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* 07 | Services
|
||||
* --------------------------------------------------------------
|
||||
*
|
||||
* A Service is an Ember object that lives for the duration of the application, and can
|
||||
* be made available in different parts of your application. Services are useful for
|
||||
* features that require shared state or persistent connections.
|
||||
*
|
||||
* Example uses of services might include:
|
||||
*
|
||||
* - User/session authentication.
|
||||
* - Geolocation.
|
||||
* - WebSockets.
|
||||
* - Server-sent events or notifications.
|
||||
* - Server-backed API calls that may not fit Ember Data.
|
||||
* - Third-party APIs.
|
||||
* - Logging.
|
||||
*
|
||||
* > ember g service <service-name>
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
* Defining services
|
||||
*
|
||||
* Like any Ember object, a service is initialized and can have properties and
|
||||
* methods of its own. Below, the shopping cart service manages an items array
|
||||
* that represents the items currently in the shopping cart.
|
||||
*/
|
||||
|
||||
// app/services/shopping-cart.js
|
||||
import Service from '@ember/service';
|
||||
|
||||
export default Service.extend({
|
||||
items: null,
|
||||
|
||||
init() {
|
||||
this._super(...arguments);
|
||||
this.set('items', []);
|
||||
},
|
||||
|
||||
remove(item) {
|
||||
this.get('items').removeObject(item);
|
||||
}
|
||||
});
|
||||
|
||||
/*
|
||||
* Accessing services
|
||||
*
|
||||
* To access a service, you can inject it in any object such as a component or another
|
||||
* service using the `inject` function from the `@ember/service` module.
|
||||
*/
|
||||
|
||||
// app/components/cart-contents.js
|
||||
import Component from '@ember/component';
|
||||
import { inject } from '@ember/service';
|
||||
|
||||
export default Component.extend({
|
||||
|
||||
shoppingCart: inject() // will load the service in file /app/services/shopping-cart.js
|
||||
|
||||
actions: {
|
||||
remove(item) {
|
||||
this.get('shoppingCart').remove(item);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Once injected into a component, a service can also be used in the template.
|
||||
// Note cart being used below to get data from the cart.
|
||||
```hbs app/templates/components/cart-contents.hbs
|
||||
<ul>
|
||||
{{#each cart.items as |item|}}
|
||||
<li>
|
||||
{{item.name}}
|
||||
<button {{action "remove" item}}>Remove</button>
|
||||
</li>
|
||||
{{/each}}
|
||||
</ul>
|
||||
```
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* 08 | Testing
|
||||
* --------------------------------------------------------------
|
||||
*
|
||||
* Testing is a core part of the Ember framework and its development cycle.
|
||||
*
|
||||
* > ember g acceptance-test <test-name>
|
||||
* > ember g integration-test <test-name>
|
||||
* > ember g unit-test <test-name>
|
||||
* > ember t --server
|
||||
* > ember s && visit localhost:4200/tests
|
||||
*/
|
||||
|
||||
/*
|
||||
* Acceptance & application tests
|
||||
*
|
||||
* In these kinds of tests, we interact with the application in the same ways that a
|
||||
* user would, such as filling out form fields and clicking buttons. Application
|
||||
* tests ensure that the interactions within a project are basically functional, the
|
||||
* core features of a project have not regressed, and the project's goals are being met.
|
||||
*
|
||||
* Some useful helpers from '@ember/test-helpers':
|
||||
* - `click(selector)`
|
||||
* Clicks an element and triggers any actions triggered by the element's click event and
|
||||
* returns a promise that fulfills when all resulting async behavior is complete.
|
||||
*
|
||||
* - `fillIn(selector, value)`
|
||||
* Fills in the selected input with the given value and returns a promise that
|
||||
* fulfills when all resulting async behavior is complete. Works with <select> elements
|
||||
* as well as <input> elements. Keep in mind that with <select> elements, value must be set
|
||||
* to the value of the <option> tag, rather than its content (for example, true rather than "Yes").
|
||||
*
|
||||
* - `triggerKeyEvent(selector, type, keyCode)`
|
||||
* Simulates a key event type, e.g. keypress, keydown, keyup with the desired keyCode on element found by the selector.
|
||||
*
|
||||
* - `triggerEvent(selector, type, options)`
|
||||
* Triggers the given event, e.g. blur, dblclick on the element identified by the provided selector.
|
||||
*
|
||||
* - `visit(url)`
|
||||
* Visits the given route and returns a promise that fulfills when all resulting async behavior is complete.
|
||||
*
|
||||
* - `currentURL()`
|
||||
* Returns the current URL.
|
||||
*
|
||||
* - `find(selector, context)`
|
||||
* Finds an element within the app's root element and within the context (optional). Scoping to the
|
||||
* root element is especially useful to avoid conflicts with the test framework's reporter, and this
|
||||
* is done by default if the context is not specified.
|
||||
*
|
||||
* - `findAll(selector)`
|
||||
* Find all elements matched by the given selector. Equivalent to calling querySelectorAll() on the
|
||||
* test root element. Returns an array of matched elements.
|
||||
*
|
||||
*/
|
||||
|
||||
import { module, test } from 'qunit';
|
||||
import { setupApplicationTest } from 'ember-qunit';
|
||||
import { visit, fillIn, click } from '@ember/test-helpers';
|
||||
|
||||
module('Acceptance | posts', function(hooks) {
|
||||
|
||||
// `setupApplicationTest` deals with application setup and teardown.
|
||||
setupApplicationTest(hooks);
|
||||
|
||||
test('should add new post', async function(assert) {
|
||||
await visit('/posts/new');
|
||||
await fillIn('input.title', 'My new post');
|
||||
await click('button.submit');
|
||||
|
||||
const title = this.element.querySelector('ul.posts li:first').textContent;
|
||||
assert.equal(title, 'My new post');
|
||||
});
|
||||
});
|
||||
|
||||
/*
|
||||
* Integration & rendering tests
|
||||
*
|
||||
* Rendering Tests are, as the name suggests, rendering components and helpers
|
||||
* by verifying the correct behaviour when the component or helper interacts
|
||||
* with the system in the same way that it will within the context of the application,
|
||||
* including being rendered from a template and receiving Ember's lifecycle hooks.
|
||||
*
|
||||
* If we need to test the interactions between various parts of the application,
|
||||
* such as behaviour between UI controls we can utilize Rendering Tests.
|
||||
*/
|
||||
|
||||
// app/components/pretty-color.js
|
||||
import Component from '@ember/component';
|
||||
import { computed } from '@ember/object';
|
||||
|
||||
export default Component.extend({
|
||||
attributeBindings: ['style'],
|
||||
|
||||
style: computed('name', function() {
|
||||
const name = this.get('name');
|
||||
return `color: ${name}`;
|
||||
})
|
||||
});
|
||||
|
||||
// tests/integration/components/pretty-color-test.js
|
||||
import { module, test } from 'qunit';
|
||||
import { setupRenderingTest } from 'ember-qunit';
|
||||
import { render } from '@ember/test-helpers';
|
||||
import hbs from 'htmlbars-inline-precompile';
|
||||
|
||||
module('Integration | Component | pretty color', function(hooks) {
|
||||
|
||||
// Make sure to call the setupRenderingTest function together with the hooks
|
||||
// parameter first in your new module. This will do the necessary setup for
|
||||
// testing your component for you, including setting up a way to access the
|
||||
// rendered DOM of your component later on in the test, and cleaning up
|
||||
// once your tests in this module are finished.
|
||||
setupRenderingTest(hooks);
|
||||
|
||||
test('it renders', async function(assert) {
|
||||
assert.expect(2);
|
||||
|
||||
// set the outer context to red
|
||||
this.set('colorValue', 'red');
|
||||
|
||||
await render(hbs`{{pretty-color name=colorValue}}`);
|
||||
|
||||
assert.equal(this.element.querySelector('div').getAttribute('style'), 'color: red', 'starts as red');
|
||||
|
||||
this.set('colorValue', 'blue');
|
||||
|
||||
assert.equal(this.element.querySelector('div').getAttribute('style'), 'color: blue', 'updates to blue'); });
|
||||
});
|
||||
|
||||
|
||||
// Stubbing services
|
||||
//
|
||||
// In cases where components have dependencies on Ember services, it is
|
||||
// possible to stub these dependencies for rendering tests. You stub Ember
|
||||
// services by using the built-in register() function to register your
|
||||
// stub service in place of the default.
|
||||
|
||||
import { module, test } from 'qunit';
|
||||
import { setupRenderingTest } from 'ember-qunit';
|
||||
import { render } from '@ember/test-helpers';
|
||||
import hbs from 'htmlbars-inline-precompile';
|
||||
import Service from '@ember/service';
|
||||
|
||||
//Stub location service
|
||||
const locationStub = Service.extend({
|
||||
city: 'New York',
|
||||
country: 'USA',
|
||||
currentLocation: {
|
||||
x: 1234,
|
||||
y: 5678
|
||||
},
|
||||
|
||||
getCurrentCity() {
|
||||
return this.get('city');
|
||||
},
|
||||
getCurrentCountry() {
|
||||
return this.get('country');
|
||||
}
|
||||
});
|
||||
|
||||
module('Integration | Component | location indicator', function(hooks) {
|
||||
setupRenderingTest(hooks);
|
||||
|
||||
hooks.beforeEach(function(assert) {
|
||||
this.owner.register('service:location-service', locationStub);
|
||||
});
|
||||
|
||||
test('should reveal current location', async function(assert) {
|
||||
await render(hbs`{{location-indicator}}`);
|
||||
assert.equal(this.element.textContent.trim(),
|
||||
'You currently are located in New York, USA');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
/*
|
||||
* Unit & container tests
|
||||
*
|
||||
* Unit tests (as well as container tests) are generally used to test a
|
||||
* small piece of code and ensure that it is doing what was intended.
|
||||
*/
|
||||
|
||||
// app/services/some-thing.js
|
||||
import Service from '@ember/service';
|
||||
|
||||
export default Service.extend({
|
||||
foo: 'bar',
|
||||
|
||||
testMethod() {
|
||||
this.set('foo', 'baz');
|
||||
}
|
||||
});
|
||||
|
||||
// tests/unit/services/some-thing-test.js
|
||||
import { module, test } from 'qunit';
|
||||
import { setupTest } from 'ember-qunit';
|
||||
|
||||
module('Unit | Service | some thing', function(hooks) {
|
||||
|
||||
// The `setupTest` helper provides us with some conveniences, such as the `this.owner` object,
|
||||
// that helps us to create or lookup objects which are needed to setup our test.
|
||||
// In this example, we use the `this.owner` object to lookup the service instance that
|
||||
// becomes our test subject: `someThing`. Note that in a unit test you can customize any
|
||||
// object under test by setting its properties accordingly. We can use the `set` method
|
||||
// of the test object to achieve this.
|
||||
setupTest(hooks);
|
||||
|
||||
test('should update foo on testMethod', function(assert) {
|
||||
const someThing = this.owner.lookup('service:some-thing');
|
||||
|
||||
someThing.testMethod();
|
||||
|
||||
assert.equal(someThing.get('foo'), 'baz');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
/*
|
||||
* Running tests
|
||||
*
|
||||
* Run your tests with `ember test` on the command-line. You can re-run your tests on
|
||||
* every file-change with `ember test --server`.
|
||||
*
|
||||
* Tests can also be executed when you are running a local development server
|
||||
* (started by running `ember server`), at the `/tests` URI which renders the `tests/index.html` template.
|
||||
*/
|
||||
|
||||
```
|
||||
ember test
|
||||
ember test --server
|
||||
ember test --filter="dashboard"
|
||||
run ember server then visit http://localhost:4200/tests
|
||||
```
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* 09 | Addons
|
||||
* --------------------------------------------------------------
|
||||
*
|
||||
* Ember has a rich ecosystem of addons that can be easily added to projects.
|
||||
* Addons provide a wide range of functionality to projects, often saving time and
|
||||
* letting you focus on your project.
|
||||
*
|
||||
* To browse addons, visit the [EmberObserver](https://emberobserver.com/) website. It catalogs and categorizes Ember
|
||||
* addons that have been published to NPM and assigns them a score based on a variety of criteria.
|
||||
*
|
||||
* > ember install <addont-name>
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* 10 | Configuration
|
||||
* --------------------------------------------------------------
|
||||
*
|
||||
* Ember CLI ships with support for managing your application's environment. Ember CLI
|
||||
* will setup a default environment config file at config/environment. Here, you can define
|
||||
* an ENV object for each environment, which are currently limited to three: development,
|
||||
* test, and production.
|
||||
*/
|
||||
|
||||
// The ENV object has three important keys:
|
||||
// - `EmberENV` can be used to define Ember feature flags (see the Feature Flags guide).
|
||||
// - `APP` can be used to pass flags/options to your application instance.
|
||||
// - `environment` contains the name of the current environment (development,production or test).
|
||||
|
||||
// You can access these environment variables in your application code by importing from `your-application-name/config/environment`.
|
||||
import ENV from 'your-application-name/config/environment';
|
||||
|
||||
if (ENV.environment === 'development') {
|
||||
// ...
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* 11 | Community
|
||||
* --------------------------------------------------------------
|
||||
*
|
||||
* Ember's secret sauce
|
||||
*
|
||||
* more at [Ember Community Page](https://emberjs.com/community/)
|
||||
*
|
||||
*/
|
||||
|
||||
// Ember Discussion Forum
|
||||
//
|
||||
// url: http://discuss.emberjs.com/
|
||||
//
|
||||
// A great venue for discussing things like features, architecture, and best practices
|
||||
// and a great place to ask questions (and get great answers from Ember Core Team members
|
||||
// and other members of the community)
|
||||
|
||||
// Ember Community Slack
|
||||
//
|
||||
// url: https://embercommunity.slack.com/
|
||||
//
|
||||
// Use the Slackin app to receive an invitation.
|
||||
|
||||
// Ember Times
|
||||
//
|
||||
// url: https://the-emberjs-times.ongoodbits.com/
|
||||
//
|
||||
// Follow the progress of new features in the Ember ecosystem, requests for community
|
||||
// input (RFCs), and calls for contributors
|
||||
|
||||
// Ember Weekly
|
||||
//
|
||||
// url: http://www.emberweekly.com/
|
||||
//
|
||||
// A curated list of Ember learning resources (podcasts, videos, blog posts, books, and more)
|
||||
|
||||
// Official Ember Blog
|
||||
//
|
||||
// url: https://emberjs.com/blog/
|
||||
//
|
||||
// Big announcements like new Ember.js version release notes or State of the Union information
|
||||
|
||||
// Ember Github
|
||||
//
|
||||
// url: https://github.com/emberjs/
|
||||
|
||||
// Ember Meetups
|
||||
//
|
||||
// url: https://emberjs.com/community/meetups/
|
||||
@@ -38,7 +38,7 @@
|
||||
|
||||
|
||||
<strong></strong> and <b></b> <!-- Makes text contained in the tag as bold -->
|
||||
<em></em> and <i></i> <!-- Alternative way to make the text contained in the tag as bold -->
|
||||
<em></em> and <i></i> <!-- Alternative way to make the text contained in the tag as italic -->
|
||||
<strike></strike> <!-- creates a strike through the text element -->
|
||||
<pre></pre> <!-- Preformatted monospace text block with some spacing intact -->
|
||||
<blockquote></blockquote> <!-- Contains long paragraphs of quotations often cited -->
|
||||
@@ -81,7 +81,7 @@
|
||||
|
||||
<!-- Supported attributes -->
|
||||
method="somefunction()" <!-- Contains the type of request (GET, POST... etc) which dictates how to send the data of the form -->
|
||||
enctype="" <!-- Dictates how the data is to be encrypted when the data is sent to the web server-->
|
||||
enctype="" <!-- Dictates how the data is to be encoded when the data is sent to the web server. -->
|
||||
autocomplete="" <!-- Specifies if the autocomplete functionality is enabled or not -->
|
||||
novalidate <!-- Dictates if the form will be validated or not -->
|
||||
accept-charset="" <!-- Identifies the character encoding upon form submission -->
|
||||
@@ -110,7 +110,7 @@ step="" <!-- Identifies the legal numb
|
||||
<!-- Supported attributes -->
|
||||
name="" <!-- The name for a dropdown combination box -->
|
||||
size="" <!-- Specifies the number of available options -->
|
||||
mupltiple <!-- Allows for multiple option selections -->
|
||||
multiple <!-- Allows for multiple option selections -->
|
||||
required <!-- Requires that a value is selected before submitting the form -->
|
||||
autofocus <!-- Specifies that the dropdown automatically comes to focus once the page loads -->
|
||||
<optgroup></optgroup> <!-- Specifies the entire grouping of available options -->
|
||||
|
||||
339
frontend/react.js
vendored
339
frontend/react.js
vendored
@@ -1,8 +1,339 @@
|
||||
/* *******************************************************************************************
|
||||
* GLOBAL CONFIG
|
||||
* Vue.config is an object containing Vue’s global configurations.
|
||||
* You can modify its properties listed below before bootstrapping your application.
|
||||
* https://vuejs.org/v2/api/#Global-Config
|
||||
* REACT.JS CHEATSHEET
|
||||
* DOCUMENTATION: https://reactjs.org/docs/
|
||||
* FILE STRUCTURE: https://reactjs.org/docs/faq-structure.html
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
```
|
||||
npm install --save react // declarative and flexible JavaScript library for building UI
|
||||
npm install --save react-dom // serves as the entry point of the DOM-related rendering paths
|
||||
npm install --save prop-types // runtime type checking for React props and similar objects
|
||||
```
|
||||
|
||||
// notes: don't forget the command lines
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* REACT
|
||||
* https://reactjs.org/docs/react-api.html
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
// Create and return a new React element of the given type.
|
||||
// Code written with JSX will be converted to use React.createElement().
|
||||
// You will not typically invoke React.createElement() directly if you are using JSX.
|
||||
React.createElement(
|
||||
type,
|
||||
[props],
|
||||
[...children]
|
||||
)
|
||||
|
||||
// Clone and return a new React element using element as the starting point.
|
||||
// The resulting element will have the original element’s props with the new props merged in shallowly.
|
||||
React.cloneElement(
|
||||
element,
|
||||
[props],
|
||||
[...children]
|
||||
)
|
||||
|
||||
// Verifies the object is a React element. Returns true or false.
|
||||
React.isValidElement(object)
|
||||
|
||||
React.Children // provides utilities for dealing with the this.props.children opaque data structure.
|
||||
|
||||
// Invokes a function on every immediate child contained within children with this set to thisArg.
|
||||
React.Children.map(children, function[(thisArg)])
|
||||
|
||||
// Like React.Children.map() but does not return an array.
|
||||
React.Children.forEach(children, function[(thisArg)])
|
||||
|
||||
// Returns the total number of components in children,
|
||||
// equal to the number of times that a callback passed to map or forEach would be invoked.
|
||||
React.Children.count(children)
|
||||
|
||||
// Verifies that children has only one child (a React element) and returns it.
|
||||
// Otherwise this method throws an error.
|
||||
React.Children.only(children)
|
||||
|
||||
// Returns the children opaque data structure as a flat array with keys assigned to each child.
|
||||
// Useful if you want to manipulate collections of children in your render methods,
|
||||
// especially if you want to reorder or slice this.props.children before passing it down.
|
||||
React.Children.toArray(children)
|
||||
|
||||
// The React.Fragment component lets you return multiple elements in a render() method without creating an additional DOM element
|
||||
// You can also use it with the shorthand <></> syntax.
|
||||
React.Fragment
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* REACT.COMPONENT
|
||||
* React.Component is an abstract base class, so it rarely makes sense to refer to React.Component
|
||||
* directly. Instead, you will typically subclass it, and define at least a render() method.
|
||||
* https://reactjs.org/docs/react-component.html
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
class Component extends React.Component {
|
||||
// Will be called before it is mounted
|
||||
constructor(props) {
|
||||
// Call this method before any other statement
|
||||
// or this.props will be undefined in the constructor
|
||||
super(props);
|
||||
|
||||
// The constructor is also often used to bind event handlers to the class instance.
|
||||
// Binding makes sure the method has access to component attributes like this.props and this.state
|
||||
this.method = this.method.bind(this);
|
||||
|
||||
// The constructor is the right place to initialize state.
|
||||
this.state = {
|
||||
active: true,
|
||||
|
||||
// In rare cases, it’s okay to initialize state based on props.
|
||||
// This effectively “forks” the props and sets the state with the initial props.
|
||||
// If you “fork” props by using them for state, you might also want to implement componentWillReceiveProps(nextProps)
|
||||
// to keep the state up-to-date with them. But lifting state up is often easier and less bug-prone.
|
||||
color: props.initialColor
|
||||
};
|
||||
}
|
||||
|
||||
// Enqueues changes to the component state and
|
||||
// tells React that this component and its children need to be re-rendered with the updated state.
|
||||
// setState() does not always immediately update the component. It may batch or defer the update until later.
|
||||
// This makes reading this.state right after calling setState() a potential pitfall.
|
||||
// Instead, use componentDidUpdate or a setState callback.
|
||||
// You may optionally pass an object as the first argument to setState() instead of a function.
|
||||
setState(updater[, callback]) { }
|
||||
|
||||
// Invoked just before mounting occurs (before render())
|
||||
// This is the only lifecycle hook called on server rendering.
|
||||
componentWillMount() { }
|
||||
|
||||
// Invoked immediately after a component is mounted.
|
||||
// Initialization that requires DOM nodes should go here.
|
||||
// If you need to load data from a remote endpoint, this is a good place to instantiate the network request.
|
||||
// This method is a good place to set up any subscriptions. If you do that, don’t forget to unsubscribe in componentWillUnmount().
|
||||
componentDidMount() { }
|
||||
|
||||
// Invoked before a mounted component receives new props.
|
||||
// If you need to update the state in response to prop changes (for example, to reset it),
|
||||
// you may compare this.props and nextProps and perform state transitions using this.setState() in this method.
|
||||
componentWillReceiveProps(nextProps) { }
|
||||
|
||||
// Let React know if a component’s output is not affected by the current change in state or props.
|
||||
// The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior.
|
||||
// shouldComponentUpdate() is invoked before rendering when new props or state are being received. Defaults to true.
|
||||
// This method is not called for the initial render or when forceUpdate() is used.
|
||||
// Returning false does not prevent child components from re-rendering when their state changes.
|
||||
shouldComponentUpdate(nextProps, nextState) { }
|
||||
|
||||
// Invoked just before rendering when new props or state are being received.
|
||||
// Use this as an opportunity to perform preparation before an update occurs. This method is not called for the initial render.
|
||||
// Note that you cannot call this.setState() here; nor should you do anything else
|
||||
// (e.g. dispatch a Redux action) that would trigger an update to a React component before componentWillUpdate() returns.
|
||||
// If you need to update state in response to props changes, use componentWillReceiveProps() instead.
|
||||
componentWillUpdate(nextProps, nextState) { }
|
||||
|
||||
// Invoked immediately after updating occurs. This method is not called for the initial render.
|
||||
// Use this as an opportunity to operate on the DOM when the component has been updated.
|
||||
// This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).
|
||||
componentDidUpdate(prevProps, prevState) { }
|
||||
|
||||
// Invoked immediately before a component is unmounted and destroyed.
|
||||
// Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests,
|
||||
// or cleaning up any subscriptions that were created in componentDidMount().
|
||||
componentWillUnmount() { }
|
||||
|
||||
// Error boundaries are React components that catch JavaScript errors anywhere in their child component tree,
|
||||
// log those errors, and display a fallback UI instead of the component tree that crashed.
|
||||
// Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.
|
||||
componentDidCatch() { }
|
||||
|
||||
// This method is required.
|
||||
// It should be pure, meaning that it does not modify component state,
|
||||
// it returns the same result each time it’s invoked, and
|
||||
// it does not directly interact with the browser (use lifecycle methods for this)
|
||||
// It must return one of the following types: react elements, string and numbers, portals, null or booleans.
|
||||
render() {
|
||||
// Contains the props that were defined by the caller of this component.
|
||||
console.log(this.props);
|
||||
|
||||
// Contains data specific to this component that may change over time.
|
||||
// The state is user-defined, and it should be a plain JavaScript object.
|
||||
// If you don’t use it in render(), it shouldn’t be in the state.
|
||||
// For example, you can put timer IDs directly on the instance.
|
||||
// Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made.
|
||||
// Treat this.state as if it were immutable.
|
||||
console.log(this.state);
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Comment goes here */}
|
||||
Hello, {this.props.name}!
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Can be defined as a property on the component class itself, to set the default props for the class.
|
||||
// This is used for undefined props, but not for null props.
|
||||
Component.defaultProps = {
|
||||
color: 'blue'
|
||||
};
|
||||
|
||||
component = new Component();
|
||||
|
||||
// By default, when your component’s state or props change, your component will re-render.
|
||||
// If your render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate().
|
||||
// Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render().
|
||||
component.forceUpdate(callback)
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* REACT.DOM
|
||||
* The react-dom package provides DOM-specific methods that can be used at the top level of
|
||||
* your app and as an escape hatch to get outside of the React model if you need to.
|
||||
* Most of your components should not need to use this module.
|
||||
* https://reactjs.org/docs/react-dom.html
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
// Render a React element into the DOM in the supplied container and return a reference
|
||||
// to the component (or returns null for stateless components).
|
||||
ReactDOM.render(element, container[, callback])
|
||||
|
||||
// Same as render(), but is used to hydrate a container whose HTML contents were rendered
|
||||
// by ReactDOMServer. React will attempt to attach event listeners to the existing markup.
|
||||
ReactDOM.hydrate(element, container[, callback])
|
||||
|
||||
// Remove a mounted React component from the DOM and clean up its event handlers and state.
|
||||
// If no component was mounted in the container, calling this function does nothing.
|
||||
// Returns true if a component was unmounted and false if there was no component to unmount.
|
||||
ReactDOM.unmountComponentAtNode(container)
|
||||
|
||||
// If this component has been mounted into the DOM, this returns the corresponding native browser
|
||||
// DOM element. This method is useful for reading values out of the DOM, such as form field values
|
||||
// and performing DOM measurements. In most cases, you can attach a ref to the DOM node and avoid
|
||||
// using findDOMNode at all.
|
||||
ReactDOM.findDOMNode(component)
|
||||
|
||||
// Creates a portal. Portals provide a way to render children into a DOM node that exists outside
|
||||
// the hierarchy of the DOM component.
|
||||
ReactDOM.createPortal(child, container)
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* REACTDOMSERVER
|
||||
* The ReactDOMServer object enables you to render components to static markup.
|
||||
* https://reactjs.org/docs/react-dom.html
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
// Render a React element to its initial HTML. React will return an HTML string.
|
||||
// You can use this method to generate HTML on the server and send the markup down on the initial
|
||||
// request for faster page loads and to allow search engines to crawl your pages for SEO purposes.
|
||||
ReactDOMServer.renderToString(element)
|
||||
|
||||
// Similar to renderToString, except this doesn’t create extra DOM attributes that React uses
|
||||
// internally, such as data-reactroot. This is useful if you want to use React as a simple static
|
||||
// page generator, as stripping away the extra attributes can save some bytes.
|
||||
ReactDOMServer.renderToStaticMarkup(element)
|
||||
|
||||
// Render a React element to its initial HTML. Returns a Readable stream that outputs an HTML string.
|
||||
// The HTML output by this stream is exactly equal to what ReactDOMServer.renderToString would return.
|
||||
// You can use this method to generate HTML on the server and send the markup down on the initial
|
||||
// request for faster page loads and to allow search engines to crawl your pages for SEO purposes.
|
||||
ReactDOMServer.renderToNodeStream(element)
|
||||
|
||||
// Similar to renderToNodeStream, except this doesn’t create extra DOM attributes that React uses
|
||||
// internally, such as data-reactroot. This is useful if you want to use React as a simple static
|
||||
// page generator, as stripping away the extra attributes can save some bytes.
|
||||
ReactDOMServer.renderToStaticNodeStream(element)
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* TYPECHECKING WITH PROPTYPES
|
||||
* https://reactjs.org/docs/typechecking-with-proptypes.html
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
MyComponent.propTypes = {
|
||||
// You can declare that a prop is a specific JS type. By default, these
|
||||
// are all optional.
|
||||
optionalArray: PropTypes.array,
|
||||
optionalBool: PropTypes.bool,
|
||||
optionalFunc: PropTypes.func,
|
||||
optionalNumber: PropTypes.number,
|
||||
optionalObject: PropTypes.object,
|
||||
optionalString: PropTypes.string,
|
||||
optionalSymbol: PropTypes.symbol,
|
||||
|
||||
// Anything that can be rendered: numbers, strings, elements or an array
|
||||
// (or fragment) containing these types.
|
||||
optionalNode: PropTypes.node,
|
||||
|
||||
// A React element.
|
||||
optionalElement: PropTypes.element,
|
||||
|
||||
// You can also declare that a prop is an instance of a class. This uses
|
||||
// JS's instanceof operator.
|
||||
optionalMessage: PropTypes.instanceOf(Message),
|
||||
|
||||
// You can ensure that your prop is limited to specific values by treating
|
||||
// it as an enum.
|
||||
optionalEnum: PropTypes.oneOf(['News', 'Photos']),
|
||||
|
||||
// An object that could be one of many types
|
||||
optionalUnion: PropTypes.oneOfType([
|
||||
PropTypes.string,
|
||||
PropTypes.number,
|
||||
PropTypes.instanceOf(Message)
|
||||
]),
|
||||
|
||||
// An array of a certain type
|
||||
optionalArrayOf: PropTypes.arrayOf(PropTypes.number),
|
||||
|
||||
// An object with property values of a certain type
|
||||
optionalObjectOf: PropTypes.objectOf(PropTypes.number),
|
||||
|
||||
// An object taking on a particular shape
|
||||
optionalObjectWithShape: PropTypes.shape({
|
||||
color: PropTypes.string,
|
||||
fontSize: PropTypes.number
|
||||
}),
|
||||
|
||||
// You can chain any of the above with `isRequired` to make sure a warning
|
||||
// is shown if the prop isn't provided.
|
||||
requiredFunc: PropTypes.func.isRequired,
|
||||
|
||||
// A value of any data type
|
||||
requiredAny: PropTypes.any.isRequired,
|
||||
|
||||
// You can also specify a custom validator. It should return an Error
|
||||
// object if the validation fails. Don't `console.warn` or throw, as this
|
||||
// won't work inside `oneOfType`.
|
||||
customProp: function(props, propName, componentName) {
|
||||
if (!/matchme/.test(props[propName])) {
|
||||
return new Error(
|
||||
'Invalid prop `' + propName + '` supplied to' +
|
||||
' `' + componentName + '`. Validation failed.'
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
// You can also supply a custom validator to `arrayOf` and `objectOf`.
|
||||
// It should return an Error object if the validation fails. The validator
|
||||
// will be called for each key in the array or object. The first two
|
||||
// arguments of the validator are the array or object itself, and the
|
||||
// current item's key.
|
||||
customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
|
||||
if (!/matchme/.test(propValue[key])) {
|
||||
return new Error(
|
||||
'Invalid prop `' + propFullName + '` supplied to' +
|
||||
' `' + componentName + '`. Validation failed.'
|
||||
);
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
@@ -1,9 +1,52 @@
|
||||
/* *******************************************************************************************
|
||||
* GLOBAL OBJECTS > OBJECT
|
||||
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
|
||||
* ******************************************************************************************* */
|
||||
|
||||
// Global object: properties
|
||||
Object.length // length is a property of a function object, and indicates how many arguments the function expects, i.e. the number of formal parameters. This number does not include the rest parameter. Has a value of 1.
|
||||
Object.prototype // Represents the Object prototype object and allows to add new properties and methods to all objects of type Object.
|
||||
|
||||
// Methods of the Object constructor
|
||||
Object.assign(target, ...sources) // Copies the values of all enumerable own properties from one or more source objects to a target object. method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object
|
||||
Object.create(MyObject) // Creates a new object with the specified prototype object and properties. The object which should be the prototype of the newly-created object.
|
||||
Object.defineProperty(obj, prop, descriptor) // Adds the named property described by a given descriptor to an object.
|
||||
Object.defineProperties(obj, props) // Adds the named properties described by the given descriptors to an object.
|
||||
Object.entries(obj) // Returns an array containing all of the [key, value] pairs of a given object's own enumerable string properties.
|
||||
Object.freeze(obj) // Freezes an object: other code can't delete or change any properties.
|
||||
Object.getOwnPropertyDescriptor(obj, prop) // Returns a property descriptor for a named property on an object.
|
||||
Object.getOwnPropertyDescriptors(obj) // Returns an object containing all own property descriptors for an object.
|
||||
Object.getOwnPropertyNames(obj) // Returns an array containing the names of all of the given object's own enumerable and non-enumerable properties.
|
||||
Object.getOwnPropertySymbols(obj) // Returns an array of all symbol properties found directly upon a given object.
|
||||
Object.getPrototypeOf(obj) // Returns the prototype of the specified object.
|
||||
Object.is(value1, value2); // Compares if two values are the same value. Equates all NaN values (which differs from both Abstract Equality Comparison and Strict Equality Comparison).
|
||||
Object.isExtensible(obj) // Determines if extending of an object is allowed.
|
||||
Object.isFrozen(obj) // Determines if an object was frozen.
|
||||
Object.isSealed(obj) // Determines if an object is sealed.
|
||||
Object.keys(obj) // Returns an array containing the names of all of the given object's own enumerable string properties.
|
||||
Object.preventExtensions(obj) // Prevents any extensions of an object.
|
||||
Object.seal(obj) // Prevents other code from deleting properties of an object.
|
||||
Object.setPrototypeOf(obj, prototype) // Sets the prototype (i.e., the internal [[Prototype]] property).
|
||||
Object.values(obj) // Returns an array containing the values that correspond to all of a given object's own enumerable string properties.
|
||||
|
||||
// Object instances and Object prototype object (Object.prototype.property or Object.prototype.method())
|
||||
// Properties
|
||||
obj.constructor // Specifies the function that creates an object's prototype.
|
||||
obj.__proto__ // Points to the object which was used as prototype when the object was instantiated.
|
||||
|
||||
// Methods
|
||||
obj.hasOwnProperty(prop) // Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain.
|
||||
prototypeObj.isPrototypeOf(object) // Returns a boolean indicating whether the object this method is called upon is in the prototype chain of the specified object.
|
||||
obj.propertyIsEnumerable(prop) // Returns a boolean indicating if the internal ECMAScript [[Enumerable]] attribute is set.
|
||||
obj.toLocaleString() // Calls toString().
|
||||
obj.toString() // Returns a string representation of the object.
|
||||
object.valueOf() // Returns the primitive value of the specified object.
|
||||
|
||||
/* *******************************************************************************************
|
||||
* GLOBAL OBJECTS > ARRAY
|
||||
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
// Global object: properties
|
||||
Array.length // Reflects the number of elements in an array.
|
||||
Array.prototype // Represents the prototype for the Array constructor and allows to add new properties and methods to all Array objects.
|
||||
|
||||
@@ -1,5 +1,75 @@
|
||||
<?php
|
||||
|
||||
// Exit the file, string inside get's echo'ed
|
||||
die("This file is not ment to be ran. ¯\_(ツ)_/¯");
|
||||
exit("This file is not ment to be ran. ¯\_(ツ)_/¯");
|
||||
|
||||
/**
|
||||
* Printing
|
||||
*/
|
||||
echo ""; // Print a string or type that can be made into a string(I.E int, float).
|
||||
print_r($arr); // Print anything, with type hints for array's and object's
|
||||
var_dump($arr); // Print anything, with type hints for any value and sizes
|
||||
|
||||
/**
|
||||
* Ways of looping
|
||||
*/
|
||||
continue; // Skip current iter
|
||||
break; // Exit loop
|
||||
|
||||
// Foreach
|
||||
foreach($arr as $key => $value) {
|
||||
$key = $key;
|
||||
$value = $value;
|
||||
}
|
||||
|
||||
// For
|
||||
for($i = 0; $i < count($arr) - 1; $i++) {
|
||||
$key = $i;
|
||||
$value = $arr[$i];
|
||||
}
|
||||
|
||||
// While
|
||||
$i = 0;
|
||||
while($i < count($arr) - 1) {
|
||||
$key = $i;
|
||||
$value = $arr[$i];
|
||||
}
|
||||
|
||||
// Do while
|
||||
$i = 0;
|
||||
do {
|
||||
$key = $i;
|
||||
$value = $arr[$i];
|
||||
} while($i < count($arr));
|
||||
|
||||
// Switch
|
||||
switch($arr) {
|
||||
case 1:
|
||||
break;
|
||||
case 2:
|
||||
break;
|
||||
case 3:
|
||||
break;
|
||||
default:
|
||||
}
|
||||
|
||||
/**
|
||||
* Global variables
|
||||
* http://php.net/manual/en/language.variables.superglobals.php
|
||||
*/
|
||||
$_SERVER; // SERVER variables
|
||||
$_GET; // Query params
|
||||
$_POST; // Post fields
|
||||
$_REQUEST; // GET and POST together
|
||||
$GLOBALS; // Array of global variables
|
||||
$_SESSION; // Browser session
|
||||
$_FILES; // Array of files that are sent in request
|
||||
$_COOKIE; // Array of cookies sent in request
|
||||
$_ENV; // php.ini options
|
||||
$argv; // Array of terminal arguments (filename included)
|
||||
$argc; // Number of arguments passed into terminal
|
||||
|
||||
/**
|
||||
* Class
|
||||
* http://php.net/manual/en/language.oop5.basic.php
|
||||
|
||||
@@ -20,6 +20,8 @@ docker login # Log in this CLI session using your
|
||||
docker tag <image> username/repository:tag # Tag <image> for upload to registry
|
||||
docker push username/repository:tag # Upload tagged image to registry
|
||||
docker run username/repository:tag # Run image from a registry
|
||||
docker system prune # Remove all unused containers, networks, images (both dangling and unreferenced), and optionally, volumes. (Docker 17.06.1-ce and superior)
|
||||
docker system prune -a # Remove all unused containers, networks, images not just dangling ones (Docker 17.06.1-ce and superior)
|
||||
|
||||
|
||||
##############################################################################
|
||||
@@ -69,17 +71,17 @@ docker stack rm <appname> # Tear down an application
|
||||
##############################################################################
|
||||
|
||||
|
||||
docker-machine create --driver virtualbox myvm1 # Create a VM (Mac, Win7, Linux)
|
||||
docker-machine create -d hyperv --hyperv-virtual-switch "myswitch" myvm1 # Win10
|
||||
docker-machine env myvm1 # View basic information about your node
|
||||
docker-machine ssh myvm1 "docker node ls" # List the nodes in your swarm
|
||||
docker-machine ssh myvm1 "docker node inspect <node ID>" # Inspect a node
|
||||
docker-machine ssh myvm1 "docker swarm join-token -q worker" # View join token
|
||||
docker-machine ssh myvm1 # Open an SSH session with the VM; type "exit" to end
|
||||
docker-machine ssh myvm2 "docker swarm leave" # Make the worker leave the swarm
|
||||
docker-machine ssh myvm1 "docker swarm leave -f" # Make master leave, kill swarm
|
||||
docker-machine start myvm1 # Start a VM that is currently not running
|
||||
docker-machine stop $(docker-machine ls -q) # Stop all running VMs
|
||||
docker-machine rm $(docker-machine ls -q) # Delete all VMs and their disk images
|
||||
docker-machine scp docker-compose.yml myvm1:~ # Copy file to node's home dir
|
||||
docker-machine ssh myvm1 "docker stack deploy -c <file> <app>" # Deploy an app
|
||||
docker-machine create --driver virtualbox myvm1 # Create a VM (Mac, Win7, Linux)
|
||||
docker-machine create -d hyperv --hyperv-virtual-switch "myswitch" myvm1 # Win10
|
||||
docker-machine env myvm1 # View basic information about your node
|
||||
docker-machine ssh myvm1 "docker node ls" # List the nodes in your swarm
|
||||
docker-machine ssh myvm1 "docker node inspect <node ID>" # Inspect a node
|
||||
docker-machine ssh myvm1 "docker swarm join-token -q worker" # View join token
|
||||
docker-machine ssh myvm1 # Open an SSH session with the VM; type "exit" to end
|
||||
docker-machine ssh myvm2 "docker swarm leave" # Make the worker leave the swarm
|
||||
docker-machine ssh myvm1 "docker swarm leave -f" # Make master leave, kill swarm
|
||||
docker-machine start myvm1 # Start a VM that is currently not running
|
||||
docker-machine stop $(docker-machine ls -q) # Stop all running VMs
|
||||
docker-machine rm $(docker-machine ls -q) # Delete all VMs and their disk images
|
||||
docker-machine scp docker-compose.yml myvm1:~ # Copy file to node's home dir
|
||||
docker-machine ssh myvm1 "docker stack deploy -c <file> <app>" # Deploy an app
|
||||
|
||||
@@ -184,6 +184,13 @@ y yank (copy) marked text
|
||||
d delete marked text
|
||||
~ switch case
|
||||
|
||||
VISUAL MODE SHORTCUTS
|
||||
---------------------
|
||||
|
||||
v% selects matching parenthesis
|
||||
vi{ selects matching curly brace
|
||||
vi" selects text between double quotes
|
||||
vi' selects text between single quotes
|
||||
|
||||
##############################################################################
|
||||
# SPELLING
|
||||
|
||||
@@ -1,51 +1,76 @@
|
||||
# Visual Studio CheatSheet
|
||||
|
||||
|
||||
## Useful Extensions
|
||||
|
||||
### HTML & CSS
|
||||
|
||||
* `CSScomb`: Codeing style formatter for CSS, Less, SCSS and Saas.
|
||||
- `CSScomb`: Codeing style formatter for CSS, Less, SCSS and Saas.
|
||||
|
||||
* `Puglint`: Linter and style checker for pug.
|
||||
- `Puglint`: Linter and style checker for pug.
|
||||
|
||||
* `SCSS IntelliSense`: Advanced autocompletion and refactoring support for SCSS.
|
||||
- `Sass`: Indented Sass syntax highlighting, autocomplete & snippets.
|
||||
|
||||
- `SCSS IntelliSense`: Advanced autocompletion and refactoring support for SCSS.
|
||||
|
||||
### JavaScript, Node & NPM
|
||||
|
||||
* `ESLint`: Integrates ESLint into VS Code
|
||||
- `Import Cost`: This extension will display inline in the editor the size of the imported package.
|
||||
|
||||
* `NPM`: NPM support for VS Code.
|
||||
- `ESLint`: Integrates ESLint into VS Code
|
||||
|
||||
* `NPM Intellisense`: Visual Studio Code plugin that autocompletes NPM modules in import statements.
|
||||
- `NPM`: NPM support for VS Code.
|
||||
|
||||
* `Version Lens`: Shows the latest version for each package using code lens.
|
||||
- `NPM Intellisense`: Visual Studio Code plugin that autocompletes NPM modules in import statements.
|
||||
|
||||
- `Version Lens`: Shows the latest version for each package using code lens.
|
||||
|
||||
### SPA
|
||||
- `Vetur`: Vue tooling for VS Code.
|
||||
|
||||
* `Vetur`: Vue tooling for VS Code.
|
||||
### Git
|
||||
|
||||
- `Git History`: View git log, file history, compare branches or commits.
|
||||
|
||||
### Miscellaneous
|
||||
- `Gitignore`: A extension for Visual Studio Code that assists you in working with .gitignore files.
|
||||
|
||||
`Final-Newline`: Inserts a final newline when saving the document.
|
||||
### Themes
|
||||
|
||||
`Open in Github/Bitbucket...`: Jump to a source code line in Github / Bitbucket, Gitlab, VisualStudio.com
|
||||
- `Material Icon Theme`: Material Design Icons for Visual Studio Code.
|
||||
|
||||
`OpenChrome`: Open file with Chrome.
|
||||
- `Palenight Theme`: An elegant and juicy material-like theme for Visual Studio Code.
|
||||
|
||||
`Output Colorizer`: Syntax Highlighting for log files.
|
||||
### Handy
|
||||
|
||||
`SVG Viewer`: SVG Viewer for Visual Studio Code.
|
||||
- `Debugger for Chrome`: Debug your JavaScript code in the Chrome browser.
|
||||
|
||||
`Terminal`: Terminal for Visual Studio Code.
|
||||
- `EditorConfig for VS Code`: EditorConfig Support for Visual Studio Code.
|
||||
|
||||
- `Final-Newline`: Inserts a final newline when saving the document.
|
||||
|
||||
- `Formatting Toggle`: A VS Code extension that allows you to toggle the formatter (Prettier, Beautify, …) ON and OFF with a simple click.
|
||||
|
||||
- `Open in Github/Bitbucket...`: Jump to a source code line in Github / Bitbucket, Gitlab, VisualStudio.com
|
||||
|
||||
- `OpenChrome`: Open file with Chrome.
|
||||
|
||||
- `Output Colorizer`: Syntax Highlighting for log files.
|
||||
|
||||
- `Prettier - Code formatter`: VS Code plugin for prettier/prettier.
|
||||
|
||||
- `REST Client`: REST Client for Visual Studio Code.
|
||||
|
||||
- `SVG Viewer`: SVG Viewer for Visual Studio Code.
|
||||
|
||||
- `Terminal`: Terminal for Visual Studio Code.
|
||||
|
||||
- `VS Live Share`: Real-time collaborative development from the comfort of your favorite tools.
|
||||
|
||||
- `Wrap Console Log`: Wrap to console.log by word or selection.
|
||||
|
||||
##############################################################################
|
||||
|
||||
# USER SETTINGS
|
||||
##############################################################################
|
||||
|
||||
##############################################################################
|
||||
|
||||
```javascript
|
||||
{
|
||||
@@ -81,7 +106,7 @@
|
||||
|
||||
// Controls auto save of dirty files
|
||||
"files.autoSave": "afterDelay",
|
||||
|
||||
|
||||
// Controls the delay in ms after which a dirty file is saved automatically
|
||||
"files.autoSaveDelay": 1000,
|
||||
|
||||
@@ -136,7 +161,7 @@
|
||||
|
||||
// Specifies the icon theme used in the workbench
|
||||
"workbench.iconTheme": "material-icon-theme",
|
||||
|
||||
|
||||
// Controls font aliasing method in the workbench
|
||||
"workbench.fontAliasing": "antialiased",
|
||||
"explorer.confirmDragAndDrop": false
|
||||
|
||||
Reference in New Issue
Block a user