0.0.6-dev • Published 3 years ago

abycompany.js v0.0.6-dev

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
3 years ago

About

abycompany.js is a package with simplified and ready-to-use functions for Discord Bot Developers to develop their own Discord Bots.

Aiming to be the easiest package to learn It's swift and flexible using functions.

Aby Company for the Community ❤️

Installation

Node.JS 12.0.0 or newer is required.

npm install abycompany.js

Example

const abycompanyjs = require("abycompany.js")

const bot = new abycompanyjs.Bot({
token: "TOKEN", //Discord Bot Token
prefix: "PREFIX" //Discord Bot Prefix
})
bot.onMessage() //Allows to execute Commands

bot.command({
name: "ping", //Trigger name (command name)
code: `Pong! $pingms` //Code inside of string
})

bot.readyCommand({
    channel: "", //Optional channnel ID
    code: `$log[Ready on $userTag[$clientID]]` //A ready on Client
})
#### Music Usage ####
bot.command({
name: "play",
code: `$playSong[Music Name;Something went wrong!]`
})

More Information in our Documentation

Links


Build Status Dependencies CSS gzip size JS gzip size Icons gzip size GitHub release npm version Nuget Website xscode License: MIT GitHub issues GitHub code size in bytes


License and Premium Features

This project licensed under the MIT license. In addition, SUPPORT PACK is available for an annual subscription on XS:CODE and for a Patreon Patrons.

SUPPORT PACK includes an Extra time for priority support by email and other options.

Donation on Patreon

Donations on Patreon Donations on Patreon

Community

Facebook Join the chat at https://discord.gg/NydRab3

Contributing

All contributions are welcome. Learn more about how you can contribute to this project here.

Important! Before you create Pull Request, you must sign CLA!

Docs

Please click here for Documentation and Demo.

Releases

Metro 4 releases frequently. I Am create release when there are significant bug fixes, new APIs or components. The usual frequency of release of the new version is one week on Sundays.

LTS

Long term support of older versions of Metro 4 does not currently exist. If your current version of Metro 4 works for you, you can stay on it for as long as you'd like. If you want to make use of new features as they come in you should upgrade to a newer version.

Browser Compatibility

ChromeFirefoxEdgeSafariOpera
Latest 2 ✔Latest 2 ✔Latest 2 ✔Latest 2 ✔Latest 2 ✔

Old version

Metro UI CSS 3.x you can find in a repo Metro-UI-CSS-3
Metro UI CSS 2.x you can find in a repo Metro-UI-CSS-2
Metro UI CSS 0.x you can find in a repo Metro-UI-CSS-095

Documentation and Demo for V3: metroui.org.ua/v3.
Documentation and Demo for V2: metroui.org.ua/v2.
Documentation and Demo for V0: metroui.org.ua/v0.

Thanks

Thanks to all. Special thanks to all those who financially supported the project.

Credits

You can read about credits here


2012-2020 © Copyright by Serhii Pimenov. All Rights Reserved. Created by Serhii Pimenov. ////////////////////////////////////////////////////////////////////////////////////////////////// chat on gitter npm version build status coverage status language grade

Mock components, services and more out of annoying dependencies for simplification of Angular testing

ng-mocks facilitates Angular testing and helps to:

  • mock Components, Directives, Pipes, Modules, Services and Tokens
  • reduce boilerplate in tests
  • access declarations via simple interface

The current version of the library has been tested and can be used with:

Angularng-mocksJasmineJestIvy
13latestyesyesyes
12latestyesyesyes
11latestyesyesyes
10latestyesyesyes
9latestyesyesyes
8latestyesyes
7latestyesyes
6latestyesyes
5latestyesyes

Important links

Very short introduction

Global configuration for mocks in src/test.ts. In case of jest, src/setupJest.ts should be used.

// All methods in mock declarations and providers
// will be automatically spied on their creation.
// https://ng-mocks.sudo.eu/extra/auto-spy
ngMocks.autoSpy('jasmine'); // or jest

// ngMocks.defaultMock helps to customize mocks
// globally. Therefore, we can avoid copy-pasting
// among tests.
// https://ng-mocks.sudo.eu/api/ngMocks/defaultMock
ngMocks.defaultMock(AuthService, () => ({
  isLoggedIn$: EMPTY,
  currentUser$: EMPTY,
}));

An example of a spec for a profile edit component.

// Let's imagine that there is a ProfileComponent
// and it has 3 text fields: email, firstName,
// lastName, and a user can edit them.
// In the following test suite, we would like to
// cover behavior of the component.
describe('profile', () => {
  // First of all, we would like to reuse the same
  // TestBed in every test.
  // ngMocks.faster suppresses reset of TestBed
  // after each test and allows to use TestBed,
  // MockBuilder and MockRender in beforeAll.
  // https://ng-mocks.sudo.eu/api/ngMocks/faster
  ngMocks.faster();

  // Let's declare TestBed in beforeAll
  // instead of beforeEach.
  // The code mocks everything in SharedModule
  // and provides a mock AuthService.
  beforeAll(() => {
    return TestBed.configureTestingModule({
      imports: [
        MockModule(SharedModule), // mock
        ReactiveFormsModule, // real
      ],
      declarations: [
        MockComponent(AvatarComponent), // mock
        ProfileComponent, // real
      ],
      providers: [
        MockProvider(AuthService), // mock
      ],
    }).compileComponents();
  });

  // A test to ensure that ProfileComponent
  // can be created.
  it('should be created', () => {
    // MockRender is an advanced version of
    // TestBed.createComponent.
    // It respects all lifecycle hooks,
    // onPush change detection, and creates a
    // wrapper component with a template like
    // <app-root ...allInputs></profile>
    // https://ng-mocks.sudo.eu/api/MockRender
    const fixture = MockRender(ProfileComponent);

    expect(
      fixture.point.componentInstance,
    ).toEqual(jasmine.any(ProfileComponent));
  });

  // A test to ensure that the component listens
  // on ctrl+s hotkey.
  it('saves on ctrl+s hot key', () => {
    // A fake profile.
    const profile = {
      email: 'test2@email.com',
      firstName: 'testFirst2',
      lastName: 'testLast2',
    };

    // A spy to track save calls.
    // MockInstance helps to configure mock
    // providers, declarations and modules
    // before their initialization and usage.
    // https://ng-mocks.sudo.eu/api/MockInstance
    const spySave = MockInstance(
      StorageService,
      'save',
      jasmine.createSpy('StorageService.save'),
    );

    // Renders <profile [profile]="params.profile">
    // </profile>.
    // https://ng-mocks.sudo.eu/api/MockRender
    const { point } = MockRender(
      ProfileComponent,
      { profile }, // bindings
    );

    // Let's change the value of the form control
    // for email addresses with a random value.
    // ngMocks.change finds a related control
    // value accessor and updates it properly.
    // https://ng-mocks.sudo.eu/api/ngMocks/change
    ngMocks.change(
      '[name=email]', // css selector
      'test3@em.ail', // an email address
    );

    // Let's ensure that nothing has been called.
    expect(spySave).not.toHaveBeenCalled();

    // Let's assume that there is a host listener
    // for a keyboard combination of ctrl+s,
    // and we want to trigger it.
    // ngMocks.trigger helps to emit events via
    // simple interface.
    // https://ng-mocks.sudo.eu/api/ngMocks/trigger
    ngMocks.trigger(point, 'keyup.control.s');

    // The spy should be called with the user
    // and the random email address.
    expect(spySave).toHaveBeenCalledWith({
      email: 'test3@em.ail',
      firstName: profile.firstName,
      lastName: profile.lastName,
    });
  });
});

Profit.

Extra

If you like ng-mocks, please support it:

Thank you!

P.S. Feel free to contact us if you need help. //////////////////////////////////////////////////////////////////////////////////////////////////

Cropper.js

Downloads Version Gzip Size Dependencies

JavaScript image cropper.

Table of contents

Features

  • Supports 39 options
  • Supports 27 methods
  • Supports 6 events
  • Supports touch (mobile)
  • Supports zooming
  • Supports rotating
  • Supports scaling (flipping)
  • Supports multiple croppers
  • Supports to crop on a canvas
  • Supports to crop an image in the browser-side by canvas
  • Supports to translate Exif Orientation information
  • Cross-browser support

Main

dist/
├── cropper.css
├── cropper.min.css   (compressed)
├── cropper.js        (UMD)
├── cropper.min.js    (UMD, compressed)
├── cropper.common.js (CommonJS, default)
└── cropper.esm.js    (ES Module)

Getting started

Installation

npm install cropperjs

In browser:

<link  href="/path/to/cropper.css" rel="stylesheet">
<script src="/path/to/cropper.js"></script>

cdnjs provides CDN support for Cropper.js's CSS and JavaScript. You can find the links here.

Usage

Syntax

new Cropper(element[, options])
  • element

    • Type: HTMLImageElement or HTMLCanvasElement
    • The target image or canvas element for cropping.
  • options (optional)

    • Type: Object
    • The options for cropping. Check out the available options.

Example

<!-- Wrap the image or canvas element with a block element (container) -->
<div>
  <img id="image" src="picture.jpg">
</div>
/* Ensure the size of the image fit the container perfectly */
img {
  display: block;

  /* This rule is very important, please don't ignore this */
  max-width: 100%;
}
// import 'cropperjs/dist/cropper.css';
import Cropper from 'cropperjs';

const image = document.getElementById('image');
const cropper = new Cropper(image, {
  aspectRatio: 16 / 9,
  crop(event) {
    console.log(event.detail.x);
    console.log(event.detail.y);
    console.log(event.detail.width);
    console.log(event.detail.height);
    console.log(event.detail.rotate);
    console.log(event.detail.scaleX);
    console.log(event.detail.scaleY);
  },
});

FAQ

How to crop a new area after zoom in or zoom out?

Just double-click your mouse to enter crop mode.

How to move the image after cropping an area?

Just double-click your mouse to enter move mode.

How to fix aspect ratio in free ratio mode?

Just hold the Shift key when you resize the crop box.

How to crop a square area in free ratio mode?

Just hold the Shift key when you crop on the image.

Notes

  • The size of the cropper inherits from the size of the image's parent element (wrapper), so be sure to wrap the image with a visible block element.

    If you are using cropper in a modal, you should initialize the cropper after the modal is shown completely. Otherwise, you will not get the correct cropper.

  • The outputted cropped data is based on the original image size, so you can use them to crop the image directly.

  • If you try to start cropper on a cross-origin image, please make sure that your browser supports HTML5 CORS settings attributes, and your image server supports the Access-Control-Allow-Origin option (see the HTTP access control (CORS)).

Known issues

  • Known iOS resource limits: As iOS devices limit memory, the browser may crash when you are cropping a large image (iPhone camera resolution). To avoid this, you may resize the image first (preferably below 1024 pixels) before starting a cropper.

  • Known image size increase: When exporting the cropped image on the browser side with the HTMLCanvasElement.toDataURL method, the size of the exported image may be greater than the original image's. This is because the type of the exported image is not the same as the original image. So just pass the original image's type as the first parameter to toDataURL to fix this. For example, if the original type is JPEG, then use cropper.getCroppedCanvas().toDataURL('image/jpeg') to export image.

⬆ back to top

Options

You may set cropper options with new Cropper(image, options). If you want to change the global default options, You may use Cropper.setDefaults(options).

viewMode

  • Type: Number
  • Default: 0
  • Options:
    • 0: no restrictions
    • 1: restrict the crop box not to exceed the size of the canvas.
    • 2: restrict the minimum canvas size to fit within the container. If the proportions of the canvas and the container differ, the minimum canvas will be surrounded by extra space in one of the dimensions.
    • 3: restrict the minimum canvas size to fill fit the container. If the proportions of the canvas and the container are different, the container will not be able to fit the whole canvas in one of the dimensions.

Define the view mode of the cropper. If you set viewMode to 0, the crop box can extend outside the canvas, while a value of 1, 2, or 3 will restrict the crop box to the size of the canvas. viewMode of 2 or 3 will additionally restrict the canvas to the container. There is no difference between 2 and 3 when the proportions of the canvas and the container are the same.

dragMode

  • Type: String
  • Default: 'crop'
  • Options:
    • 'crop': create a new crop box
    • 'move': move the canvas
    • 'none': do nothing

Define the dragging mode of the cropper.

initialAspectRatio

  • Type: Number
  • Default: NaN

Define the initial aspect ratio of the crop box. By default, it is the same as the aspect ratio of the canvas (image wrapper).

Only available when the aspectRatio option is set to NaN.

aspectRatio

  • Type: Number
  • Default: NaN

Define the fixed aspect ratio of the crop box. By default, the crop box has a free ratio.

data

  • Type: Object
  • Default: null

The previous cropped data you stored will be passed to the setData method automatically when initialized.

Only available when the autoCrop option had set to the true.

preview

  • Type: Element, Array (elements), NodeList or String (selector)
  • Default: ''
  • An element or an array of elements or a node list object or a valid selector for Document.querySelectorAll

Add extra elements (containers) for preview.

Notes:

  • The maximum width is the initial width of the preview container.
  • The maximum height is the initial height of the preview container.
  • If you set an aspectRatio option, be sure to set the same aspect ratio to the preview container.
  • If the preview does not display correctly, set the overflow: hidden style to the preview container.

responsive

  • Type: Boolean
  • Default: true

Re-render the cropper when resizing the window.

restore

  • Type: Boolean
  • Default: true

Restore the cropped area after resizing the window.

checkCrossOrigin

  • Type: Boolean
  • Default: true

Check if the current image is a cross-origin image.

If so, a crossOrigin attribute will be added to the cloned image element, and a timestamp parameter will be added to the src attribute to reload the source image to avoid browser cache error.

Adding a crossOrigin attribute to the image element will stop adding a timestamp to the image URL and stop reloading the image. But the request (XMLHttpRequest) to read the image data for orientation checking will require a timestamp to bust cache to avoid browser cache error. You can set the checkOrientation option to false to cancel this request.

If the value of the image's crossOrigin attribute is "use-credentials", then the withCredentials attribute will set to true when read the image data by XMLHttpRequest.

checkOrientation

  • Type: Boolean
  • Default: true

Check the current image's Exif Orientation information. Note that only a JPEG image may contain Exif Orientation information.

Exactly, read the Orientation value for rotating or flipping the image, and then override the Orientation value with 1 (the default value) to avoid some issues (1, 2) on iOS devices.

Requires to set both the rotatable and scalable options to true at the same time.

Note: Do not trust this all the time as some JPG images may have incorrect (non-standard) Orientation values

Requires Typed Arrays support (IE 10+).

modal

  • Type: Boolean
  • Default: true

Show the black modal above the image and under the crop box.

guides

  • Type: Boolean
  • Default: true

Show the dashed lines above the crop box.

center

  • Type: Boolean
  • Default: true

Show the center indicator above the crop box.

highlight

  • Type: Boolean
  • Default: true

Show the white modal above the crop box (highlight the crop box).

background

  • Type: Boolean
  • Default: true

Show the grid background of the container.

autoCrop

  • Type: Boolean
  • Default: true

Enable to crop the image automatically when initialized.

autoCropArea

  • Type: Number
  • Default: 0.8 (80% of the image)

It should be a number between 0 and 1. Define the automatic cropping area size (percentage).

movable

  • Type: Boolean
  • Default: true

Enable to move the image.

rotatable

  • Type: Boolean
  • Default: true

Enable to rotate the image.

scalable

  • Type: `Boolean
  • Default: true

Enable to scale the image.

zoomable

  • Type: Boolean
  • Default: true

Enable to zoom the image.

zoomOnTouch

  • Type: Boolean
  • Default: true

Enable to zoom the image by dragging touch.

zoomOnWheel

  • Type: Boolean
  • Default: true

Enable to zoom the image by mouse wheeling.

wheelZoomRatio

  • Type: Number
  • Default: 0.1

Define zoom ratio when zooming the image by mouse wheeling.

cropBoxMovable

  • Type: Boolean
  • Default: true

Enable to move the crop box by dragging.

cropBoxResizable

  • Type: Boolean
  • Default: true

Enable to resize the crop box by dragging.

toggleDragModeOnDblclick

  • Type: Boolean
  • Default: true

Enable to toggle drag mode between "crop" and "move" when clicking twice on the cropper.

Requires dblclick event support.

minContainerWidth

  • Type: Number
  • Default: 200

The minimum width of the container.

minContainerHeight

  • Type: Number
  • Default: 100

The minimum height of the container.

minCanvasWidth

  • Type: Number
  • Default: 0

The minimum width of the canvas (image wrapper).

minCanvasHeight

  • Type: Number
  • Default: 0

The minimum height of the canvas (image wrapper).

minCropBoxWidth

  • Type: Number
  • Default: 0

The minimum width of the crop box.

Note: This size is relative to the page, not the image.

minCropBoxHeight

  • Type: Number
  • Default: 0

The minimum height of the crop box.

Note: This size is relative to the page, not the image.

ready

  • Type: Function
  • Default: null

A shortcut of the ready event.

cropstart

  • Type: Function
  • Default: null

A shortcut of the cropstart event.

cropmove

  • Type: Function
  • Default: null

A shortcut of the cropmove event.

cropend

  • Type: Function
  • Default: null

A shortcut of the cropend event.

crop

  • Type: Function
  • Default: null

A shortcut of the crop event.

zoom

  • Type: Function
  • Default: null

A shortcut of the zoom event.

⬆ back to top

Methods

As there is an asynchronous process when loading the image, you should call most of the methods after ready, except setAspectRatio, replace and destroy.

If a method doesn't need to return any value, it will return the cropper instance (this) for chain composition.

new Cropper(image, {
  ready() {
    // this.cropper[method](argument1, , argument2, ..., argumentN);
    this.cropper.move(1, -1);

    // Allows chain composition
    this.cropper.move(1, -1).rotate(45).scale(1, -1);
  },
});

crop()

Show the crop box manually.

new Cropper(image, {
  autoCrop: false,
  ready() {
    // Do something here
    // ...

    // And then
    this.cropper.crop();
  },
});

reset()

Reset the image and crop box to its initial states.

clear()

Clear the crop box.

replace(url, hasSameSize)

  • url:

    • Type: String
    • A new image url.
  • hasSameSize (optional):

    • Type: Boolean
    • Default: false
    • If the new image has the same size as the old one, then it will not rebuild the cropper and only update the URLs of all related images. This can be used for applying filters.

Replace the image's src and rebuild the cropper.

enable()

Enable (unfreeze) the cropper.

disable()

Disable (freeze) the cropper.

destroy()

Destroy the cropper and remove the instance from the image.

move(offsetX, offsetY)

  • offsetX:

    • Type: Number
    • Moving size (px) in the horizontal direction.
  • offsetY (optional):

    • Type: Number
    • Moving size (px) in the vertical direction.
    • If not present, its default value is offsetX.

Move the canvas (image wrapper) with relative offsets.

cropper.move(1);
cropper.move(1, 0);
cropper.move(0, -1);

moveTo(x, y)

  • x:

    • Type: Number
    • The left value of the canvas
  • y (optional):

    • Type: Number
    • The top value of the canvas
    • If not present, its default value is x.

Move the canvas (image wrapper) to an absolute point.

zoom(ratio)

  • ratio:
    • Type: Number
    • Zoom in: requires a positive number (ratio > 0)
    • Zoom out: requires a negative number (ratio < 0)

Zoom the canvas (image wrapper) with a relative ratio.

cropper.zoom(0.1);
cropper.zoom(-0.1);

zoomTo(ratio, pivot)

  • ratio:

    • Type: Number
    • Requires a positive number (ratio > 0)
  • pivot (optional):

    • Type: Object
    • Schema: { x: Number, y: Number }
    • The coordinate of the center point for zooming, base on the top left corner of the cropper container.

Zoom the canvas (image wrapper) to an absolute ratio.

cropper.zoomTo(1); // 1:1 (canvasData.width === canvasData.naturalWidth)

const containerData = cropper.getContainerData();

// Zoom to 50% from the center of the container.
cropper.zoomTo(.5, {
  x: containerData.width / 2,
  y: containerData.height / 2,
});

rotate(degree)

  • degree:
    • Type: Number
    • Rotate right: requires a positive number (degree > 0)
    • Rotate left: requires a negative number (degree < 0)

Rotate the image with a relative degree.

Requires CSS3 2D Transforms support (IE 9+).

cropper.rotate(90);
cropper.rotate(-90);

rotateTo(degree)

  • degree:
    • Type: Number

Rotate the image to an absolute degree.

scale(scaleX, scaleY)

  • scaleX:

    • Type: Number
    • Default: 1
    • The scaling factor to apply to the abscissa of the image.
    • When equal to 1 it does nothing.
  • scaleY (optional):

    • Type: Number
    • The scaling factor to apply on the ordinate of the image.
    • If not present, its default value is scaleX.

Scale the image.

Requires CSS3 2D Transforms support (IE 9+).

cropper.scale(-1); // Flip both horizontal and vertical
cropper.scale(-1, 1); // Flip horizontal
cropper.scale(1, -1); // Flip vertical

scaleX(scaleX)

  • scaleX:
    • Type: Number
    • Default: 1
    • The scaling factor to apply to the abscissa of the image.
    • When equal to 1 it does nothing.

Scale the abscissa of the image.

scaleY(scaleY)

  • scaleY:
    • Type: Number
    • Default: 1
    • The scaling factor to apply on the ordinate of the image.
    • When equal to 1 it does nothing.

Scale the ordinate of the image.

getData(rounded)

  • rounded (optional):

    • Type: Boolean
    • Default: false
    • Set true to get rounded values.
  • (return value):

    • Type: Object
    • Properties:
      • x: the offset left of the cropped area
      • y: the offset top of the cropped area
      • width: the width of the cropped area
      • height: the height of the cropped area
      • rotate: the rotated degrees of the image
      • scaleX: the scaling factor to apply on the abscissa of the image
      • scaleY: the scaling factor to apply on the ordinate of the image

Output the final cropped area position and size data (base on the natural size of the original image).

You can send the data to the server-side to crop the image directly:

  1. Rotate the image with the rotate property.
  2. Scale the image with the scaleX and scaleY properties.
  3. Crop the image with the x, y, width, and height properties.

A schematic diagram for data's properties

setData(data)

  • data:
    • Type: Object
    • Properties: See the getData method.
    • You may need to round the data properties before passing them in.

Change the cropped area position and size with new data (base on the original image).

Note: This method only available when the value of the viewMode option is greater than or equal to 1.

getContainerData()

  • (return value):
    • Type: Object
    • Properties:
      • width: the current width of the container
      • height: the current height of the container

Output the container size data.

A schematic diagram for cropper's layers

getImageData()

  • (return value):
    • Type: Object
    • Properties:
      • left: the offset left of the image
      • top: the offset top of the image
      • width: the width of the image
      • height: the height of the image
      • naturalWidth: the natural width of the image
      • naturalHeight: the natural height of the image
      • aspectRatio: the aspect ratio of the image
      • rotate: the rotated degrees of the image if it is rotated
      • scaleX: the scaling factor to apply on the abscissa of the image if scaled
      • scaleY: the scaling factor to apply on the ordinate of the image if scaled

Output the image position, size, and other related data.

getCanvasData()

  • (return value):
    • Type: Object
    • Properties:
      • left: the offset left of the canvas
      • top: the offset top of the canvas
      • width: the width of the canvas
      • height: the height of the canvas
      • naturalWidth: the natural width of the canvas (read only)
      • naturalHeight: the natural height of the canvas (read only)

Output the canvas (image wrapper) position and size data.

const imageData = cropper.getImageData();
const canvasData = cropper.getCanvasData();

if (imageData.rotate % 180 === 0) {
  console.log(canvasData.naturalWidth === imageData.naturalWidth);
  // > true
}

setCanvasData(data)

  • data:
    • Type: Object
    • Properties:
      • left: the new offset left of the canvas
      • top: the new offset top of the canvas
      • width: the new width of the canvas
      • height: the new height of the canvas

Change the canvas (image wrapper) position and size with new data.

getCropBoxData()

  • (return value):
    • Type: Object
    • Properties:
      • left: the offset left of the crop box
      • top: the offset top of the crop box
      • width: the width of the crop box
      • height: the height of the crop box

Output the crop box position and size data.

setCropBoxData(data)

  • data:
    • Type: Object
    • Properties:
      • left: the new offset left of the crop box
      • top: the new offset top of the crop box
      • width: the new width of the crop box
      • height: the new height of the crop box

Change the crop box position and size with new data.

getCroppedCanvas(options)

  • options (optional):

    • Type: Object
    • Properties:
      • width: the destination width of the output canvas.
      • height: the destination height of the output canvas.
      • minWidth: the minimum destination width of the output canvas, the default value is 0.
      • minHeight: the minimum destination height of the output canvas, the default value is 0.
      • maxWidth: the maximum destination width of the output canvas, the default value is Infinity.
      • maxHeight: the maximum destination height of the output canvas, the default value is Infinity.
      • fillColor: a color to fill any alpha values in the output canvas, the default value is the transparent.
      • imageSmoothingEnabled: set to change if images are smoothed (true, default) or not (false).
      • imageSmoothingQuality: set the quality of image smoothing, one of "low" (default), "medium", or "high".
  • (return value):

    • Type: HTMLCanvasElement
    • A canvas drawn the cropped image.
  • Notes:

    • The aspect ratio of the output canvas will be fitted to the aspect ratio of the crop box automatically.
    • If you intend to get a JPEG image from the output canvas, you should set the fillColor option first, if not, the transparent part in the JPEG image will become black by default.
    • Uses the Browser's native canvas.toBlob API to do the compression work, which means it is lossy compression. For better image quality, you can upload the original image and the cropped data to a server and do the crop work on the server.
  • Browser support:

Get a canvas drawn from the cropped image (lossy compression). If it is not cropped, then returns a canvas drawn the whole image.

After then, you can display the canvas as an image directly, or use HTMLCanvasElement.toDataURL to get a Data URL, or use HTMLCanvasElement.toBlob to get a blob and upload it to server with FormData if the browser supports these APIs.

Avoid get a blank (or black) output image, you might need to set the maxWidth and maxHeight properties to limited numbers, because of the size limits of a canvas element. Also, you should limit the maximum zoom ratio (in the zoom event) for the same reason.

cropper.getCroppedCanvas();

cropper.getCroppedCanvas({
  width: 160,
  height: 90,
  minWidth: 256,
  minHeight: 256,
  maxWidth: 4096,
  maxHeight: 4096,
  fillColor: '#fff',
  imageSmoothingEnabled: false,
  imageSmoothingQuality: 'high',
});

// Upload cropped image to server if the browser supports `HTMLCanvasElement.toBlob`.
// The default value for the second parameter of `toBlob` is 'image/png', change it if necessary.
cropper.getCroppedCanvas().toBlob((blob) => {
  const formData = new FormData();

  // Pass the image file name as the third parameter if necessary.
  formData.append('croppedImage', blob/*, 'example.png' */);

  // Use `jQuery.ajax` method for example
  $.ajax('/path/to/upload', {
    method: 'POST',
    data: formData,
    processData: false,
    contentType: false,
    success() {
      console.log('Upload success');
    },
    error() {
      console.log('Upload error');
    },
  });
}/*, 'image/png' */);

setAspectRatio(aspectRatio)

  • aspectRatio:
    • Type: Number
    • Requires a positive number.

Change the aspect ratio of the crop box.

setDragMode(mode)

  • mode (optional):
    • Type: String
    • Default: 'none'
    • Options: 'none', 'crop', 'move'

Change the drag mode.

Tips: You can toggle the "crop" and "move" mode by double click on the cropper.

⬆ back to top

Events

ready

This event fires when the target image has been loaded and the cropper instance is ready for operating.

let cropper;

image.addEventListener('ready', function () {
  console.log(this.cropper === cropper);
  // > true
});

cropper = new Cropper(image);

cropstart

  • event.detail.originalEvent:

    • Type: Event
    • Options: pointerdown, touchstart, and mousedown
  • event.detail.action:

    • Type: String
    • Options:
      • 'crop': create a new crop box
      • 'move': move the canvas (image wrapper)
      • 'zoom': zoom in / out the canvas (image wrapper) by touch.
      • 'e': resize the east side of the crop box
      • 'w': resize the west side of the crop box
      • 's': resize the south side of the crop box
      • 'n': resize the north side of the crop box
      • 'se': resize the southeast side of the crop box
      • 'sw': resize the southwest side of the crop box
      • 'ne': resize the northeast side of the crop box
      • 'nw': resize the northwest side of the crop box
      • 'all': move the crop box (all directions)

This event fires when the canvas (image wrapper) or the crop box starts to change.

image.addEventListener('cropstart', (event) => {
  console.log(event.detail.originalEvent);
  console.log(event.detail.action);
});

cropmove

  • event.detail.originalEvent:

    • Type: Event
    • Options: pointermove, touchmove, and mousemove.
  • event.detail.action: the same as "cropstart".

This event fires when the canvas (image wrapper) or the crop box is changing.

cropend

  • event.detail.originalEvent:

    • Type: Event
    • Options: pointerup, pointercancel, touchend, touchcancel, and mouseup.
  • event.detail.action: the same as "cropstart".

This event fires when the canvas (image wrapper) or the crop box stops to change.

crop

  • event.detail.x
  • event.detail.y
  • event.detail.width
  • event.detail.height
  • event.detail.rotate
  • event.detail.scaleX
  • event.detail.scaleY

About these properties, see the getData method.

This event fires when the canvas (image wrapper) or the crop box changed.

Notes:

  • When the autoCrop option is set to the true, a crop event will be triggered before the ready event.
  • When the data option is set, another crop event will be triggered before the ready event.

zoom

  • event.detail.originalEvent:

    • Type: Event
    • Options: wheel, pointermove, touchmove, and mousemove.
  • event.detail.oldRatio:

    • Type: Number
    • The old (current) ratio of the canvas
  • event.detail.ratio:

    • Type: Number
    • The new (next) ratio of the canvas (canvasData.width / canvasData.naturalWidth)

This event fires when a cropper instance starts to zoom in or zoom out its canvas (image wrapper).

image.addEventListener('zoom', (event) => {
  // Zoom in
  if (event.detail.ratio > event.detail.oldRatio) {
    event.preventDefault(); // Prevent zoom in
  }

  // Zoom out
  // ...
});

⬆ back to top

No conflict

If you have to use another cropper with the same namespace, just call the Cropper.noConflict static method to revert to it.

<script src="other-cropper.js"></script>
<script src="cropper.js"></script>
<script>
  Cropper.noConflict();
  // Code that uses other `Cropper` can follow here.
</script>

Browser support

  • Chrome (latest)
  • Firefox (latest)
  • Safari (latest)
  • Opera (latest)
  • Edge (latest)
  • Internet Explorer 9+

Contributing

Please read through our contributing guidelines.

Versioning

Maintained under the Semantic Versioning guidelines.

License

MIT © Chen Fengyuan

Related projects

⬆ back to top ////////////////////////////////////////////////////////////////////////////////////////////////// view on npm npm module downloads per month build status

Live Server

This is a little development server with live reload capability. Use it for hacking your HTML/JavaScript/CSS files, but not for deploying the final site.

There are two reasons for using this:

  1. AJAX requests don't work with the file:// protocol due to security restrictions, i.e. you need a server if your site fetches content through JavaScript.
  2. Having the page reload automatically after changes to files can accelerate development.

You don't need to install any browser plugins or manually add code snippets to your pages for the reload functionality to work, see "How it works" section below for more information. If you don't want/need the live reload, you should probably use something even simpler, like the following Python-based one-liner:

python -m SimpleHTTPServer

Installation

You need node.js and npm. You should probably install this globally.

Npm way

npm install -g live-server

Manual way

git clone https://github.com/tapio/live-server
cd live-server
npm install # Local dependencies if you want to hack
npm install -g # Install globally

Usage from command line

Issue the command live-server in your project's directory. Alternatively you can add the path to serve as a command line parameter.

This will automatically launch the default browser. When you make a change to any file, the browser will reload the page - unless it was a CSS file in which case the changes are applied without a reload.

Command line parameters:

  • --port=NUMBER - select port to use, default: PORT env var or 8080
  • --host=ADDRESS - select host address to bind to, default: IP env var or 0.0.0.0 ("any address")
  • --no-browser - suppress automatic web browser launching
  • --browser=BROWSER - specify browser to use instead of system default
  • --quiet | -q - suppress logging
  • --verbose | -V - more logging (logs all requests, shows all listening IPv4 interfaces, etc.)
  • --open=PATH - launch browser to PATH instead of server root
  • --watch=PATH - comma-separated string of paths to exclusively watch for changes (default: watch everything)
  • --ignore=PATH - comma-separated string of paths to ignore (anymatch-compatible definition)
  • --ignorePattern=RGXP - Regular expression of files to ignore (ie .*\.jade) (DEPRECATED in favor of --ignore)
  • --no-css-inject - reload page on CSS change, rather than injecting changed CSS
  • --middleware=PATH - path to .js file exporting a middleware function to add; can be a name without path nor extension to reference bundled middlewares in middleware folder
  • --entry-file=PATH - serve this file (server root relative) in place of missing files (useful for single page apps)
  • --mount=ROUTE:PATH - serve the paths contents under the defined route (multiple definitions possible)
  • --spa - translate requests from /abc to /#/abc (handy for Single Page Apps)
  • --wait=MILLISECONDS - (default 100ms) wait for all changes, before reloading
  • --htpasswd=PATH - Enables http-auth expecting htpasswd file located at PATH
  • --cors - Enables CORS for any origin (reflects request origin, requests with credentials are supported)
  • --https=PATH - PATH to a HTTPS configuration module
  • --https-module=MODULE_NAME - Custom HTTPS module (e.g. spdy)
  • --proxy=ROUTE:URL - proxy all requests for ROUTE to URL
  • --help | -h - display terse usage hint and exit
  • --version | -v - display version and exit

Default options:

If a file ~/.live-server.json exists it will be loaded and used as default options for live-server on the command line. See "Usage from node" for option names.

Usage from node

var liveServer = require("live-server");

var params = {
	port: 8181, // Set the server port. Defaults to 8080.
	host: "0.0.0.0", // Set the address to bind to. Defaults to 0.0.0.0 or process.env.IP.
	root: "/public", // Set root directory that's being served. Defaults to cwd.
	open: false, // When false, it won't load your browser by default.
	ignore: 'scss,my/templates', // comma-separated string for paths to ignore
	file: "index.html", // When set, serve this file (server root relative) for every 404 (useful for single-page applications)
	wait: 1000, // Waits for all changes, before reloading. Defaults to 0 sec.
	mount: [['/components', './node_modules']], // Mount a directory to a route.
	logLevel: 2, // 0 = errors only, 1 = some, 2 = lots
	middleware: [function(req, res, next) { next(); }] // Takes an array of Connect-compatible middleware that are injected into the server middleware stack
};
liveServer.start(params);

HTTPS

In order to enable HTTPS support, you'll need to create a configuration module. The module must export an object that will be used to configure a HTTPS server. The keys are the same as the keys in options for tls.createServer.

For example:

var fs = require("fs");

module.exports = {
	cert: fs.readFileSync(__dirname + "/server.cert"),
	key: fs.readFileSync(__dirname + "/server.key"),
	passphrase: "12345"
};

If using the node API, you can also directly pass a configuration object instead of a path to the module.

HTTP/2

To get HTTP/2 support one can provide a custom HTTPS module via --https-module CLI parameter (httpsModule option for Node.js script). Be sure to install the module first. HTTP/2 unencrypted mode is not supported by browsers, thus not supported by live-server. See this question and can I use page on HTTP/2 for more details.

For example from CLI(bash):

live-server \
	--https=path/to/https.conf.js \
	--https-module=spdy \
	my-app-folder/

Troubleshooting

  • No reload on changes * Open your browser's console: there should be a message at the top stating that live reload is enabled. Note that you will need a browser that supports WebSockets. If there are errors, deal with them. If it's still not working, file an issue.
  • Error: watch ENOSPC * See this suggested solution.
  • Reload works but changes are missing or outdated * Try using --wait=MS option. Where MS is time in milliseconds to wait before issuing a reload.

How it works

The server is a simple node app that serves the working directory and its subdirectories. It also watches the files for changes and when that happens, it sends a message through a web socket connection to the browser instructing it to reload. In order for the client side to support this, the server injects a small piece of JavaScript code to each requested html file. This script establishes the web socket connection and listens to the reload requests. CSS files can be refreshed without a full page reload by finding the referenced stylesheets from the DOM and tricking the browser to fetch and parse them again.

Contributing

We welcome contributions! See CONTRIBUTING.md for details.

Version history

  • v1.2.1 - --https-module=MODULE_NAME to specify custom HTTPS module (e.g. spdy) (@pavel) - --no-css-inject to reload page on css change instead of injecting the changes (@kylecordes) - Dependencies updated to get rid of vulnerabilities in deps
  • v1.2.0 - Add --middleware parameter to use external middlewares - middleware API parameter now also accepts strings similar to --middleware - Changed file watcher to improve speed (@pavel) - --ignore now accepts regexps and globs, --ignorePattern deprecated (@pavel) - Added --verbose cli option (logLevel 3) (@pavel) - Logs all requests, displays warning when can't inject html file, displays all listening IPv4 interfaces... - HTTPS configuration now also accepts a plain object (@pavel) - Move --spa to a bundled middleware file - New bundled spa-no-assets middleware that works like spa but ignores requests with extension - Allow multiple --open arguments (@PirtleShell) - Inject to head if body not found (@pmd1991) - Update dependencies
  • v1.1.0 - Proxy support (@pavel) - Middleware support (@achandrasekar) - Dependency updates (@tapio, @rahatarmanahmed) - Using Travis CI
  • v1.0.0 - HTTPS support (@pavel) - HTTP Basic authentication support (@hey-johnnypark) - CORS support (@pavel) - Support mounting single files (@pavel) - --spa cli option for single page apps, translates requests from /abc to /#/abc (@evanplaice) - Check IP env var for default host (@dotnetCarpenter) - Fix ignorePattern from config file (@cyfersystems) - Fix test running for Windows (@peterhull90)
  • v0.9.2 - Updated most dependencies to latest versions - --quiet now silences warning about injection failure - Giving explicit --watch paths now disables adding mounted paths to watching
  • v0.9.1 - --ignorePattern=RGXP exclude files from watching by regexp (@psi-4ward) - --watch=PATH cli option to only watch given paths
  • v0.9.0 - --mount=ROUTE:PATH cli option to specify alternative routes to paths (@pmentz) - --browser=BROWSER cli option to specify browser to use (@sakiv) - Improved error reporting - Basic support for injecting the reload code to SVG files (@dotnetCarpenter, @tapio) - LiveServer.shutdown() function to close down the server and file watchers - If host parameter is given, use it for browser URL instead of resolved IP - Initial testing framework (@harrytruong, @evanplaice, @tapio)
  • v0.8.2 - Load initial settings from ~/.live-server.json if exists (@mikker) - Allow --port=0 to select random port (@viqueen) - Fix injecting when file extension is not lower case (@gusgard) - Fail gracefully if browser does not support WebSockets (@mattymaloney) - Switched to a more maintained browser opening library
  • v0.8.1 - Add --version / -v command line flags to display version - Add --host cli option to mirror the API parameter - Once again use 127.0.0.1 instead of 0.0.0.0 as the browser URL
  • v0.8.0 - Support multiple clients simultaneously (@dvv) - Pick a random available port if the default is in use (@oliverzy, @harrytruong) - Fix Chrome sometimes not applying CSS changes (@harrytruong) - --ignore=PATH cli option to not watch given server root relative paths (@richardgoater) - --entry-file=PATH cli option to specify file to use when request is not found (@izeau) - --wait=MSECS cli option to wait specified time before reloading (@leolower, @harrytruong)
  • v0.7.1 - Fix hang caused by trying to inject into fragment html files without </body> - logLevel parameter in library to control amount of console spam - --quiet cli option to suppress console spam - --open=PATH cli option to launch browser in specified path instead of root (@richardgoater) - Library's noBrowser: true option is deprecated in favor of open: false
  • v0.7.0 - API BREAKAGE: LiveServer library now takes parameters in an object - Add possibility to specify host to the lib - Only inject to host page when working with web components (e.g. Polymer) (@davej) - Open browser to 127.0.0.1, as 0.0.0.0 has issues - --no-browser command line flag to suppress browser launch - --help command line flag to display usage
  • v0.6.4 - Allow specifying port from the command line: live-server --port=3000 (@Pomax) - Don't inject script as the first thing so that DOCTYPE remains valid (@wmira) - Be more explicit with listening to all interfaces (@inadarei)
  • v0.6.3 - Fix multiple _cacheOverride parameters polluting css requests - Don't create global variables in the injected script
  • v0.6.2 - Fix a deprecation warning from send
  • v0.6.1 - Republish to fix npm troubles
  • v0.6.0 - Support for using as node library (@dpgraham)
  • v0.5.0 - Watching was broken with new versions of watchr > 2.3.3 - Added some logging to console
  • v0.4.0 - Allow specifying directory to serve from command line
  • v0.3.0 - Directory listings
  • v0.2.0 - On-the-fly CSS refresh (no page reload) - Refactoring
  • v0.1.1 - Documentation and meta tweaks
  • v0.1.0 - Initial release

License

Uses MIT licensed code from Connect and Roots.

(MIT License)

Copyright (c) 2012 Tapio Vierros

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ////////////////////////////////////////////////////////////////////////////////////////////////// alt text

Introducing Skeletonic CSS

Skeletonic CSS - A lightweight, intuitive, accessible and ultra-responsive cascading style sheets framework to streamline your Digital and Mobile Web development needs.

Download Skeletonic CSS v1.2.1

NPM

npm version Build Status Packagist FOSSA Status

Table of contents

Getting Started

Skeletonic is constantly in development. Try it out now!

Local Setup

Several quick start options are available:

  • Download the latest release
  • Install with Npm to get the pre-built CSS and sourcemaps. This is recommended when using Skeletonic for a typical web project: npm install skeletonic
  • Install with Yarn to get the pre-built CSS and sourcemaps. This is recommended when using Skeletonic for a typical web project: yarn add skeletonic
  • Clone the main repository to get all source files including build scripts: git clone https://github.com/sebastienrousseau/skeletonic.git

What's included

Within the download you'll find all the source files, compiled and minified CSS bundles as well as the CSS sourcemaps grouped into the dist folder.

You'll see something like this:

skeletonic-1.2.1
├── skeletonic-animations.css
├── skeletonic-animations.css.map
├── skeletonic-animations.min.css
├── skeletonic-colours.css
├── skeletonic-colours.css.map
├── skeletonic-colours.min.css
├── skeletonic-fonts.css
├── skeletonic-fonts.css.map
├── skeletonic-fonts.min.css
├── skeletonic-pattern.css
├── skeletonic-pattern.css.map
├── skeletonic-pattern.min.css
├── skeletonic.css
├── skeletonic.css.map
└── skeletonic.min.css

Now simply link one of these CSS in your HTML document. In that case, the quickest and easiest way to start using skeletonic is to include a reference to the minified CSS file.

<link rel="stylesheet" type="text/css" href="skeletonic.min.css" />

The link consists of just a simple line of HTML code that you will need to put in the <head> section of your HTML document.

We also provide production-ready versions and use unpkg as our preferred CDN to link to the latest production version. unpkg is a fast, global content delivery network for everything on npm.

Please feel free to grab the latest:

<link rel="stylesheet" type="text/css" href="https://unpkg.com/skeletonic/dist/skeletonic.min.css" />

You can also specify a specific version as per below. The latest version as of today is 1.2.1.

<link rel="stylesheet" type="text/css" href="https://unpkg.com/skeletonic@1.2.1/dist/skeletonic.min.css" />

Extend

We provide a growing library of extensible CSS module files, utilities, themes and components ready to use as is to fit your web needs.

CSS Responsive Grid-View

<link rel="stylesheet" type="text/css" href="skeletonic-pattern.min.css" />

CSS Colours

<link rel="stylesheet" type="text/css" href="skeletonic-colours.min.css" />

CSS Animations

<link rel="stylesheet" type="text/css" href="skeletonic-animations.min.css" />

Alternate CDN locations

The following table lists alternate CDN locations where Skeletonic is hosted.

CDNURLHTTPSCombo
unpkghttps://unpkg.com/skeletonic@1.2.1/dist/skeletonic.min.cssYesNo
jsDelivrhttps://cdn.jsdelivr.net/npm/skeletonic/dist/skeletonic.min.cssYesYes

Versioning

For transparency into our release cycle and in striving to maintain backward compatibility, Skeletonic is maintained under the Semantic Versioning guidelines.

Built With

  • Gulp - The streaming build system
  • Stylus - Expressive, robust, feature-rich CSS language built for nodejs
  • CSScomb - CSS coding style formatter

Contributing

Please read carefully through our Contributing Guidelines for further details on the process for submitting pull requests to us.

Code of Conduct

We are committed to preserving and fostering a diverse, welcoming community. Please read our Code of Conduct.

Our Values

  1. We believe perfection must consider everything.
  2. We take our passion beyond Code into our daily practices.
  3. We are just obsessed about creating and delivering exceptional solutions.

History

License

This project is licensed under the MIT License - see the LICENSE(https://github.com/sebastienrousseau/skeletonic/blob/master/L