Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Release v2.3.0 #8

Merged
merged 13 commits into from
Nov 11, 2022
Prev Previous commit
Next Next commit
feat: start with jpg/png export
  • Loading branch information
sgratzl committed Sep 15, 2022
commit 0ae1b3128682fa4ce349014fe62398cb1c92eff0
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,5 +96,10 @@
"docs": "typedoc src/index.ts",
"prepare": "yarn run build"
},
"packageManager": "[email protected]"
"packageManager": "[email protected]",
"dependenciesMeta": {
"[email protected]": {
"unplugged": true
}
}
}
123 changes: 123 additions & 0 deletions src/LayersPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,23 @@ import {
ISVGLayerOptions,
ICanvasLayerOptions,
IPoint,
CytoscapeBaseLayer,
} from './layers';
import type { ILayerAdapter } from './layers/ABaseLayer';
import { renderPerEdge, renderPerNode } from './elements';
import { output } from './copied';

function isPoint(p: IPoint | cy.BoundingBox12): p is IPoint {
return (p as IPoint).x != null;
}

export interface LayerExportOptions {
ignoreUnsupportedLayers?: boolean;
ignoreUnsupportedLayerOrder?: boolean;
}

export class LayerExportException extends Error {}

export default class LayersPlugin {
readonly cy: cy.Core;

Expand Down Expand Up @@ -286,6 +295,120 @@ export default class LayersPlugin {
return layers[0] ?? null;
}

private toCanvas(
options: (cy.ExportJpgStringOptions | cy.ExportJpgBlobOptions | cy.ExportJpgBlobPromiseOptions) & LayerExportOptions
): HTMLCanvasElement {
const layers = this.layers;

if (layers.some((d) => !d.supportsRender) && !options.ignoreUnsupportedLayers) {
throw new LayerExportException(
`some layer doesn't support exporting, use {ignoreUnsupportedLayers: true} option to ignore`
);
}

const nodeIndex = layers.indexOf(this.nodeLayer as ILayer & ILayerImpl);
const dragIndex = layers.indexOf(this.dragLayer as ILayer & ILayerImpl);
const selectBoxIndex = layers.indexOf(this.selectBoxLayer as ILayer & ILayerImpl);

if ((nodeIndex !== dragIndex - 1 || dragIndex !== selectBoxIndex - 1) && !options.ignoreUnsupportedLayerOrder) {
throw new LayerExportException(
`cytoscape layers are not in order, use {ignoreUnsupportedLayerOrder: true} option to ignore`
);
}

const renderer = (
this.cy as unknown as {
renderer(): {
bufferCanvasImage(
options: cy.ExportJpgStringOptions | cy.ExportJpgBlobOptions | cy.ExportJpgBlobPromiseOptions
): HTMLCanvasElement;
};
}
).renderer();

const bg = options.bg;

const canvas = renderer.bufferCanvasImage({ ...options, bg: undefined });

const width = canvas.width;
const height = canvas.height;
const ctx = canvas.getContext('2d')!;

const before = layers
.slice(0, nodeIndex)
.reverse()
.filter((d) => d.supportsRender && d !== this.dragLayer && d !== this.selectBoxLayer);

const after = layers
.slice(nodeIndex + 1)
.filter((d) => d.supportsRender && d !== this.dragLayer && d !== this.selectBoxLayer);

const scale = options.scale ?? 1;

const hint = { scale, width, height, full: options.full ?? false };

ctx.globalCompositeOperation = 'destination-over';
for (const l of before) {
l.renderInto(ctx, hint);
}

ctx.globalCompositeOperation = 'source-over';
for (const l of after) {
l.renderInto(ctx, hint);
}

if (bg) {
ctx.globalCompositeOperation = 'destination-over';
ctx.fillStyle = bg;
ctx.rect(0, 0, width, height);
ctx.fill();
}

return canvas;
}

/**
* Export the current graph view as a PNG image in Base64 representation.
*/
png(options?: cy.ExportStringOptions & LayerExportOptions): string;
png(options?: cy.ExportBlobOptions & LayerExportOptions): Blob;
png(options?: cy.ExportBlobPromiseOptions & LayerExportOptions): Promise<Blob>;

png(
options?: (cy.ExportStringOptions | cy.ExportBlobOptions | cy.ExportBlobPromiseOptions) & LayerExportOptions
): any {
return output(options ?? {}, this.toCanvas(options ?? {}), 'image/png');
}

/**
* Export the current graph view as a JPG image in Base64 representation.
*/
jpg(options?: cy.ExportJpgStringOptions & LayerExportOptions): string;
jpg(options?: cy.ExportJpgBlobOptions & LayerExportOptions): Blob;
jpg(options?: cy.ExportJpgBlobPromiseOptions & LayerExportOptions): Promise<Blob>;

jpg(
options?: (cy.ExportJpgStringOptions | cy.ExportJpgBlobOptions | cy.ExportJpgBlobPromiseOptions) &
LayerExportOptions
): any {
const o = {
bg: '#fff',
...(options ?? {}),
};
return output(o, this.toCanvas(o), 'image/png');
}

/**
* Export the current graph view as a JPG image in Base64 representation.
*/
jpeg(options?: cy.ExportJpgStringOptions): string;
jpeg(options?: cy.ExportJpgBlobOptions): Blob;
jpeg(options?: cy.ExportJpgBlobPromiseOptions): Promise<Blob>;

jpeg(options?: cy.ExportJpgStringOptions | cy.ExportJpgBlobOptions | cy.ExportJpgBlobPromiseOptions): any {
return this.jpg(options as unknown as any);
}

readonly renderPerEdge = renderPerEdge;

readonly renderPerNode = renderPerNode;
Expand Down
82 changes: 82 additions & 0 deletions src/copied.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/**
* Copyright (c) 2016-2022, The Cytoscape Consortium.
*
* 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.
*/
import type cy from 'cytoscape';

function b64ToBlob(b64: string, mimeType: string): Blob {
const bytes = atob(b64);
const buff = new ArrayBuffer(bytes.length);
const buffUint8 = new Uint8Array(buff);

for (let i = 0; i < bytes.length; i++) {
buffUint8[i] = bytes.charCodeAt(i);
}

return new Blob([buff], {
type: mimeType,
});
}

function b64UriToB64(b64uri: string): string {
const i = b64uri.indexOf(',');
return b64uri.substring(i + 1);
}

export function output(
options: cy.ExportJpgStringOptions | cy.ExportJpgBlobOptions | cy.ExportJpgBlobPromiseOptions,
canvas: HTMLCanvasElement,
mimeType: string
) {
const getB64Uri = function getB64Uri() {
return canvas.toDataURL(mimeType, options.quality);
};

switch (options.output) {
case 'blob-promise':
return new Promise((resolve, reject) => {
try {
canvas.toBlob(
function (blob) {
if (blob != null) {
resolve(blob);
} else {
reject(new Error('`canvas.toBlob()` sent a null value in its callback'));
}
},
mimeType,
options.quality
);
} catch (err) {
reject(err);
}
});

case 'blob':
return b64ToBlob(b64UriToB64(getB64Uri()), mimeType);

case 'base64':
return b64UriToB64(getB64Uri());

case 'base64uri':
default:
return getB64Uri();
}
}
9 changes: 9 additions & 0 deletions src/layers/ABaseLayer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type {
IHTMLStaticLayer,
ISVGStaticLayer,
ICanvasStaticLayer,
IRenderHint,
} from './interfaces';
import type cy from 'cytoscape';
import type { ICanvasLayerOptions, ISVGLayerOptions, IHTMLLayerOptions } from './public';
Expand Down Expand Up @@ -34,6 +35,14 @@ export abstract class ABaseLayer implements IMoveAbleLayer {
return this.adapter.inVisibleBounds(p);
}

get supportsRender() {
return false;
}

renderInto(_ctx: CanvasRenderingContext2D, _hint: IRenderHint): void {
// dummy
}

get updateOnRender() {
return this.updateOnRenderEnabled;
}
Expand Down
31 changes: 23 additions & 8 deletions src/layers/CanvasLayer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import type { ICanvasLayer, ILayerElement, ILayerImpl, IRenderFunction, ICanvasStaticLayer } from './interfaces';
import type {
ICanvasLayer,
ILayerElement,
ILayerImpl,
IRenderFunction,
ICanvasStaticLayer,
IRenderHint,
} from './interfaces';
import { layerStyle, stopClicks } from './utils';
import { ABaseLayer, ILayerAdapter } from './ABaseLayer';
import type { ICanvasLayerOptions } from './public';
Expand Down Expand Up @@ -68,17 +75,25 @@ export class CanvasBaseLayer extends ABaseLayer implements ILayerImpl {

draw() {
this.clear();
this.ctx.save();
this.ctx.resetTransform();
this.ctx.scale(this.pixelRatio, this.pixelRatio);
this.ctx.translate(this.transform.tx, this.transform.ty);
this.ctx.scale(this.transform.zoom, this.transform.zoom);
this.drawImpl(this.ctx);
}

private drawImpl(ctx: CanvasRenderingContext2D, scale = 1) {
ctx.save();
ctx.resetTransform();
ctx.scale(this.pixelRatio, this.pixelRatio);
ctx.translate(this.transform.tx * scale, this.transform.ty * scale);
ctx.scale(this.transform.zoom * scale, this.transform.zoom * scale);

for (const r of this.callbacks) {
r(this.ctx);
r(ctx);
}

this.ctx.restore();
ctx.restore();
}

renderInto(ctx: CanvasRenderingContext2D, hint: IRenderHint): void {
this.drawImpl(ctx, hint.scale);
}

resize(width: number, height: number) {
Expand Down
4 changes: 4 additions & 0 deletions src/layers/CytoscapeLayer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ export class CytoscapeBaseLayer extends ABaseLayer implements ILayerImpl {
remove() {
// dummy
}

get supportsRender(): boolean {
return true;
}
}

export class CytoscapeNodeLayer extends CytoscapeBaseLayer implements ICytoscapeNodeLayer {
Expand Down
4 changes: 4 additions & 0 deletions src/layers/HTMLLayer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ export class HTMLLayer extends ADOMBaseLayer<HTMLElement> implements IHTMLLayer,
this.update();
}
}

renderInto(): boolean {
return false;
}
}

export class HTMLStaticLayer extends ADOMBaseLayer<HTMLElement> implements IHTMLStaticLayer, ILayerImpl {
Expand Down
10 changes: 10 additions & 0 deletions src/layers/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,19 @@ export interface ILayerElement {
__cy_layer: ILayer & ILayerImpl;
}

export interface IRenderHint {
scale: number;
width: number;
height: number;
full: boolean;
}

export interface ILayerImpl {
readonly root: HTMLElement | SVGElement;
resize(width: number, height: number): void;
remove(): void;
setViewport(tx: number, ty: number, zoom: number): void;

readonly supportsRender: boolean;
renderInto(ctx: CanvasRenderingContext2D, hint: IRenderHint): void;
}
3 changes: 3 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3449,6 +3449,9 @@ __metadata:
typescript: ^4.8.3
peerDependencies:
cytoscape: ^3.23.0
dependenciesMeta:
[email protected]:
unplugged: true
languageName: unknown
linkType: soft

Expand Down