canvas-compositor/index.js

1101 lines
41 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// modules are defined as an array
// [ module function, map of requires ]
//
// map of requires is short require name -> numeric require
//
// anything defined in a previous bundle is accessed via the
// orig method which is the require for previous bundles
(function (modules, entry, mainEntry, parcelRequireName, globalName) {
/* eslint-disable no-undef */
var globalObject =
typeof globalThis !== 'undefined'
? globalThis
: typeof self !== 'undefined'
? self
: typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: {};
/* eslint-enable no-undef */
// Save the require from previous bundle to this closure if any
var previousRequire =
typeof globalObject[parcelRequireName] === 'function' &&
globalObject[parcelRequireName];
var cache = previousRequire.cache || {};
// Do not use `require` to prevent Webpack from trying to bundle this call
var nodeRequire =
typeof module !== 'undefined' &&
typeof module.require === 'function' &&
module.require.bind(module);
function newRequire(name, jumped) {
if (!cache[name]) {
if (!modules[name]) {
// if we cannot find the module within our internal map or
// cache jump to the current global require ie. the last bundle
// that was added to the page.
var currentRequire =
typeof globalObject[parcelRequireName] === 'function' &&
globalObject[parcelRequireName];
if (!jumped && currentRequire) {
return currentRequire(name, true);
}
// If there are other bundles on this page the require from the
// previous one is saved to 'previousRequire'. Repeat this as
// many times as there are bundles until the module is found or
// we exhaust the require chain.
if (previousRequire) {
return previousRequire(name, true);
}
// Try the node require function if it exists.
if (nodeRequire && typeof name === 'string') {
return nodeRequire(name);
}
var err = new Error("Cannot find module '" + name + "'");
err.code = 'MODULE_NOT_FOUND';
throw err;
}
localRequire.resolve = resolve;
localRequire.cache = {};
var module = (cache[name] = new newRequire.Module(name));
modules[name][0].call(
module.exports,
localRequire,
module,
module.exports,
this
);
}
return cache[name].exports;
function localRequire(x) {
var res = localRequire.resolve(x);
return res === false ? {} : newRequire(res);
}
function resolve(x) {
var id = modules[name][1][x];
return id != null ? id : x;
}
}
function Module(moduleName) {
this.id = moduleName;
this.bundle = newRequire;
this.exports = {};
}
newRequire.isParcelRequire = true;
newRequire.Module = Module;
newRequire.modules = modules;
newRequire.cache = cache;
newRequire.parent = previousRequire;
newRequire.register = function (id, exports) {
modules[id] = [
function (require, module) {
module.exports = exports;
},
{},
];
};
Object.defineProperty(newRequire, 'root', {
get: function () {
return globalObject[parcelRequireName];
},
});
globalObject[parcelRequireName] = newRequire;
for (var i = 0; i < entry.length; i++) {
newRequire(entry[i]);
}
if (mainEntry) {
// Expose entry point to Node, AMD or browser globals
// Based on https://github.com/ForbesLindesay/umd/blob/master/template.js
var mainExports = newRequire(mainEntry);
// CommonJS
if (typeof exports === 'object' && typeof module !== 'undefined') {
module.exports = mainExports;
// RequireJS
} else if (typeof define === 'function' && define.amd) {
define(function () {
return mainExports;
});
// <script>
} else if (globalName) {
this[globalName] = mainExports;
}
}
})({"3beyG":[function(require,module,exports) {
var global = arguments[3];
var HMR_HOST = null;
var HMR_PORT = 1234;
var HMR_SECURE = false;
var HMR_ENV_HASH = "d6ea1d42532a7575";
module.bundle.HMR_BUNDLE_ID = "34812aa376ac5ddd";
"use strict";
/* global HMR_HOST, HMR_PORT, HMR_ENV_HASH, HMR_SECURE, chrome, browser, __parcel__import__, __parcel__importScripts__, ServiceWorkerGlobalScope */ /*::
import type {
HMRAsset,
HMRMessage,
} from '@parcel/reporter-dev-server/src/HMRServer.js';
interface ParcelRequire {
(string): mixed;
cache: {|[string]: ParcelModule|};
hotData: {|[string]: mixed|};
Module: any;
parent: ?ParcelRequire;
isParcelRequire: true;
modules: {|[string]: [Function, {|[string]: string|}]|};
HMR_BUNDLE_ID: string;
root: ParcelRequire;
}
interface ParcelModule {
hot: {|
data: mixed,
accept(cb: (Function) => void): void,
dispose(cb: (mixed) => void): void,
// accept(deps: Array<string> | string, cb: (Function) => void): void,
// decline(): void,
_acceptCallbacks: Array<(Function) => void>,
_disposeCallbacks: Array<(mixed) => void>,
|};
}
interface ExtensionContext {
runtime: {|
reload(): void,
getURL(url: string): string;
getManifest(): {manifest_version: number, ...};
|};
}
declare var module: {bundle: ParcelRequire, ...};
declare var HMR_HOST: string;
declare var HMR_PORT: string;
declare var HMR_ENV_HASH: string;
declare var HMR_SECURE: boolean;
declare var chrome: ExtensionContext;
declare var browser: ExtensionContext;
declare var __parcel__import__: (string) => Promise<void>;
declare var __parcel__importScripts__: (string) => Promise<void>;
declare var globalThis: typeof self;
declare var ServiceWorkerGlobalScope: Object;
*/ var OVERLAY_ID = "__parcel__error__overlay__";
var OldModule = module.bundle.Module;
function Module(moduleName) {
OldModule.call(this, moduleName);
this.hot = {
data: module.bundle.hotData[moduleName],
_acceptCallbacks: [],
_disposeCallbacks: [],
accept: function(fn) {
this._acceptCallbacks.push(fn || function() {});
},
dispose: function(fn) {
this._disposeCallbacks.push(fn);
}
};
module.bundle.hotData[moduleName] = undefined;
}
module.bundle.Module = Module;
module.bundle.hotData = {};
var checkedAssets /*: {|[string]: boolean|} */ , assetsToDispose /*: Array<[ParcelRequire, string]> */ , assetsToAccept /*: Array<[ParcelRequire, string]> */ ;
function getHostname() {
return HMR_HOST || (location.protocol.indexOf("http") === 0 ? location.hostname : "localhost");
}
function getPort() {
return HMR_PORT || location.port;
}
// eslint-disable-next-line no-redeclare
var parent = module.bundle.parent;
if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== "undefined") {
var hostname = getHostname();
var port = getPort();
var protocol = HMR_SECURE || location.protocol == "https:" && !/localhost|127.0.0.1|0.0.0.0/.test(hostname) ? "wss" : "ws";
var ws = new WebSocket(protocol + "://" + hostname + (port ? ":" + port : "") + "/");
// Web extension context
var extCtx = typeof chrome === "undefined" ? typeof browser === "undefined" ? null : browser : chrome;
// Safari doesn't support sourceURL in error stacks.
// eval may also be disabled via CSP, so do a quick check.
var supportsSourceURL = false;
try {
(0, eval)('throw new Error("test"); //# sourceURL=test.js');
} catch (err) {
supportsSourceURL = err.stack.includes("test.js");
}
// $FlowFixMe
ws.onmessage = async function(event /*: {data: string, ...} */ ) {
checkedAssets = {} /*: {|[string]: boolean|} */ ;
assetsToAccept = [];
assetsToDispose = [];
var data /*: HMRMessage */ = JSON.parse(event.data);
if (data.type === "update") {
// Remove error overlay if there is one
if (typeof document !== "undefined") removeErrorOverlay();
let assets = data.assets.filter((asset)=>asset.envHash === HMR_ENV_HASH);
// Handle HMR Update
let handled = assets.every((asset)=>{
return asset.type === "css" || asset.type === "js" && hmrAcceptCheck(module.bundle.root, asset.id, asset.depsByBundle);
});
if (handled) {
console.clear();
// Dispatch custom event so other runtimes (e.g React Refresh) are aware.
if (typeof window !== "undefined" && typeof CustomEvent !== "undefined") window.dispatchEvent(new CustomEvent("parcelhmraccept"));
await hmrApplyUpdates(assets);
// Dispose all old assets.
let processedAssets = {} /*: {|[string]: boolean|} */ ;
for(let i = 0; i < assetsToDispose.length; i++){
let id = assetsToDispose[i][1];
if (!processedAssets[id]) {
hmrDispose(assetsToDispose[i][0], id);
processedAssets[id] = true;
}
}
// Run accept callbacks. This will also re-execute other disposed assets in topological order.
processedAssets = {};
for(let i = 0; i < assetsToAccept.length; i++){
let id = assetsToAccept[i][1];
if (!processedAssets[id]) {
hmrAccept(assetsToAccept[i][0], id);
processedAssets[id] = true;
}
}
} else fullReload();
}
if (data.type === "error") {
// Log parcel errors to console
for (let ansiDiagnostic of data.diagnostics.ansi){
let stack = ansiDiagnostic.codeframe ? ansiDiagnostic.codeframe : ansiDiagnostic.stack;
console.error("\uD83D\uDEA8 [parcel]: " + ansiDiagnostic.message + "\n" + stack + "\n\n" + ansiDiagnostic.hints.join("\n"));
}
if (typeof document !== "undefined") {
// Render the fancy html overlay
removeErrorOverlay();
var overlay = createErrorOverlay(data.diagnostics.html);
// $FlowFixMe
document.body.appendChild(overlay);
}
}
};
ws.onerror = function(e) {
console.error(e.message);
};
ws.onclose = function() {
console.warn("[parcel] \uD83D\uDEA8 Connection to the HMR server was lost");
};
}
function removeErrorOverlay() {
var overlay = document.getElementById(OVERLAY_ID);
if (overlay) {
overlay.remove();
console.log("[parcel] ✨ Error resolved");
}
}
function createErrorOverlay(diagnostics) {
var overlay = document.createElement("div");
overlay.id = OVERLAY_ID;
let errorHTML = '<div style="background: black; opacity: 0.85; font-size: 16px; color: white; position: fixed; height: 100%; width: 100%; top: 0px; left: 0px; padding: 30px; font-family: Menlo, Consolas, monospace; z-index: 9999;">';
for (let diagnostic of diagnostics){
let stack = diagnostic.frames.length ? diagnostic.frames.reduce((p, frame)=>{
return `${p}
<a href="/__parcel_launch_editor?file=${encodeURIComponent(frame.location)}" style="text-decoration: underline; color: #888" onclick="fetch(this.href); return false">${frame.location}</a>
${frame.code}`;
}, "") : diagnostic.stack;
errorHTML += `
<div>
<div style="font-size: 18px; font-weight: bold; margin-top: 20px;">
🚨 ${diagnostic.message}
</div>
<pre>${stack}</pre>
<div>
${diagnostic.hints.map((hint)=>"<div>\uD83D\uDCA1 " + hint + "</div>").join("")}
</div>
${diagnostic.documentation ? `<div>📝 <a style="color: violet" href="${diagnostic.documentation}" target="_blank">Learn more</a></div>` : ""}
</div>
`;
}
errorHTML += "</div>";
overlay.innerHTML = errorHTML;
return overlay;
}
function fullReload() {
if ("reload" in location) location.reload();
else if (extCtx && extCtx.runtime && extCtx.runtime.reload) extCtx.runtime.reload();
}
function getParents(bundle, id) /*: Array<[ParcelRequire, string]> */ {
var modules = bundle.modules;
if (!modules) return [];
var parents = [];
var k, d, dep;
for(k in modules)for(d in modules[k][1]){
dep = modules[k][1][d];
if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) parents.push([
bundle,
k
]);
}
if (bundle.parent) parents = parents.concat(getParents(bundle.parent, id));
return parents;
}
function updateLink(link) {
var href = link.getAttribute("href");
if (!href) return;
var newLink = link.cloneNode();
newLink.onload = function() {
if (link.parentNode !== null) // $FlowFixMe
link.parentNode.removeChild(link);
};
newLink.setAttribute("href", // $FlowFixMe
href.split("?")[0] + "?" + Date.now());
// $FlowFixMe
link.parentNode.insertBefore(newLink, link.nextSibling);
}
var cssTimeout = null;
function reloadCSS() {
if (cssTimeout) return;
cssTimeout = setTimeout(function() {
var links = document.querySelectorAll('link[rel="stylesheet"]');
for(var i = 0; i < links.length; i++){
// $FlowFixMe[incompatible-type]
var href /*: string */ = links[i].getAttribute("href");
var hostname = getHostname();
var servedFromHMRServer = hostname === "localhost" ? new RegExp("^(https?:\\/\\/(0.0.0.0|127.0.0.1)|localhost):" + getPort()).test(href) : href.indexOf(hostname + ":" + getPort());
var absolute = /^https?:\/\//i.test(href) && href.indexOf(location.origin) !== 0 && !servedFromHMRServer;
if (!absolute) updateLink(links[i]);
}
cssTimeout = null;
}, 50);
}
function hmrDownload(asset) {
if (asset.type === "js") {
if (typeof document !== "undefined") {
let script = document.createElement("script");
script.src = asset.url + "?t=" + Date.now();
if (asset.outputFormat === "esmodule") script.type = "module";
return new Promise((resolve, reject)=>{
var _document$head;
script.onload = ()=>resolve(script);
script.onerror = reject;
(_document$head = document.head) === null || _document$head === void 0 || _document$head.appendChild(script);
});
} else if (typeof importScripts === "function") {
// Worker scripts
if (asset.outputFormat === "esmodule") return import(asset.url + "?t=" + Date.now());
else return new Promise((resolve, reject)=>{
try {
importScripts(asset.url + "?t=" + Date.now());
resolve();
} catch (err) {
reject(err);
}
});
}
}
}
async function hmrApplyUpdates(assets) {
global.parcelHotUpdate = Object.create(null);
let scriptsToRemove;
try {
// If sourceURL comments aren't supported in eval, we need to load
// the update from the dev server over HTTP so that stack traces
// are correct in errors/logs. This is much slower than eval, so
// we only do it if needed (currently just Safari).
// https://bugs.webkit.org/show_bug.cgi?id=137297
// This path is also taken if a CSP disallows eval.
if (!supportsSourceURL) {
let promises = assets.map((asset)=>{
var _hmrDownload;
return (_hmrDownload = hmrDownload(asset)) === null || _hmrDownload === void 0 ? void 0 : _hmrDownload.catch((err)=>{
// Web extension bugfix for Chromium
// https://bugs.chromium.org/p/chromium/issues/detail?id=1255412#c12
if (extCtx && extCtx.runtime && extCtx.runtime.getManifest().manifest_version == 3) {
if (typeof ServiceWorkerGlobalScope != "undefined" && global instanceof ServiceWorkerGlobalScope) {
extCtx.runtime.reload();
return;
}
asset.url = extCtx.runtime.getURL("/__parcel_hmr_proxy__?url=" + encodeURIComponent(asset.url + "?t=" + Date.now()));
return hmrDownload(asset);
}
throw err;
});
});
scriptsToRemove = await Promise.all(promises);
}
assets.forEach(function(asset) {
hmrApply(module.bundle.root, asset);
});
} finally{
delete global.parcelHotUpdate;
if (scriptsToRemove) scriptsToRemove.forEach((script)=>{
if (script) {
var _document$head2;
(_document$head2 = document.head) === null || _document$head2 === void 0 || _document$head2.removeChild(script);
}
});
}
}
function hmrApply(bundle /*: ParcelRequire */ , asset /*: HMRAsset */ ) {
var modules = bundle.modules;
if (!modules) return;
if (asset.type === "css") reloadCSS();
else if (asset.type === "js") {
let deps = asset.depsByBundle[bundle.HMR_BUNDLE_ID];
if (deps) {
if (modules[asset.id]) {
// Remove dependencies that are removed and will become orphaned.
// This is necessary so that if the asset is added back again, the cache is gone, and we prevent a full page reload.
let oldDeps = modules[asset.id][1];
for(let dep in oldDeps)if (!deps[dep] || deps[dep] !== oldDeps[dep]) {
let id = oldDeps[dep];
let parents = getParents(module.bundle.root, id);
if (parents.length === 1) hmrDelete(module.bundle.root, id);
}
}
if (supportsSourceURL) // Global eval. We would use `new Function` here but browser
// support for source maps is better with eval.
(0, eval)(asset.output);
// $FlowFixMe
let fn = global.parcelHotUpdate[asset.id];
modules[asset.id] = [
fn,
deps
];
} else if (bundle.parent) hmrApply(bundle.parent, asset);
}
}
function hmrDelete(bundle, id) {
let modules = bundle.modules;
if (!modules) return;
if (modules[id]) {
// Collect dependencies that will become orphaned when this module is deleted.
let deps = modules[id][1];
let orphans = [];
for(let dep in deps){
let parents = getParents(module.bundle.root, deps[dep]);
if (parents.length === 1) orphans.push(deps[dep]);
}
// Delete the module. This must be done before deleting dependencies in case of circular dependencies.
delete modules[id];
delete bundle.cache[id];
// Now delete the orphans.
orphans.forEach((id)=>{
hmrDelete(module.bundle.root, id);
});
} else if (bundle.parent) hmrDelete(bundle.parent, id);
}
function hmrAcceptCheck(bundle /*: ParcelRequire */ , id /*: string */ , depsByBundle /*: ?{ [string]: { [string]: string } }*/ ) {
if (hmrAcceptCheckOne(bundle, id, depsByBundle)) return true;
// Traverse parents breadth first. All possible ancestries must accept the HMR update, or we'll reload.
let parents = getParents(module.bundle.root, id);
let accepted = false;
while(parents.length > 0){
let v = parents.shift();
let a = hmrAcceptCheckOne(v[0], v[1], null);
if (a) // If this parent accepts, stop traversing upward, but still consider siblings.
accepted = true;
else {
// Otherwise, queue the parents in the next level upward.
let p = getParents(module.bundle.root, v[1]);
if (p.length === 0) {
// If there are no parents, then we've reached an entry without accepting. Reload.
accepted = false;
break;
}
parents.push(...p);
}
}
return accepted;
}
function hmrAcceptCheckOne(bundle /*: ParcelRequire */ , id /*: string */ , depsByBundle /*: ?{ [string]: { [string]: string } }*/ ) {
var modules = bundle.modules;
if (!modules) return;
if (depsByBundle && !depsByBundle[bundle.HMR_BUNDLE_ID]) {
// If we reached the root bundle without finding where the asset should go,
// there's nothing to do. Mark as "accepted" so we don't reload the page.
if (!bundle.parent) return true;
return hmrAcceptCheck(bundle.parent, id, depsByBundle);
}
if (checkedAssets[id]) return true;
checkedAssets[id] = true;
var cached = bundle.cache[id];
assetsToDispose.push([
bundle,
id
]);
if (!cached || cached.hot && cached.hot._acceptCallbacks.length) {
assetsToAccept.push([
bundle,
id
]);
return true;
}
}
function hmrDispose(bundle /*: ParcelRequire */ , id /*: string */ ) {
var cached = bundle.cache[id];
bundle.hotData[id] = {};
if (cached && cached.hot) cached.hot.data = bundle.hotData[id];
if (cached && cached.hot && cached.hot._disposeCallbacks.length) cached.hot._disposeCallbacks.forEach(function(cb) {
cb(bundle.hotData[id]);
});
delete bundle.cache[id];
}
function hmrAccept(bundle /*: ParcelRequire */ , id /*: string */ ) {
// Execute the module.
bundle(id);
// Run the accept callbacks in the new version of the module.
var cached = bundle.cache[id];
if (cached && cached.hot && cached.hot._acceptCallbacks.length) cached.hot._acceptCallbacks.forEach(function(cb) {
var assetsToAlsoAccept = cb(function() {
return getParents(module.bundle.root, id);
});
if (assetsToAlsoAccept && assetsToAccept.length) {
assetsToAlsoAccept.forEach(function(a) {
hmrDispose(a[0], a[1]);
});
// $FlowFixMe[method-unbinding]
assetsToAccept.push.apply(assetsToAccept, assetsToAlsoAccept);
}
});
}
},{}],"1jwFz":[function(require,module,exports) {
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
var _canvas = require("./Compositor/Canvas");
var _canvasDefault = parcelHelpers.interopDefault(_canvas);
var _textNode = require("./Compositor/TextNode");
var _textNodeDefault = parcelHelpers.interopDefault(_textNode);
let t = new (0, _canvasDefault.default)();
t.init();
let text = new (0, _textNodeDefault.default)("Merhaba arkadaşlar nasılsınız ?");
text.color = "black";
text.x = 0;
text.fontSize = 24;
text.y = 0;
t.addNode(text);
},{"./Compositor/Canvas":"lKBnk","@parcel/transformer-js/src/esmodule-helpers.js":"7Rzro","./Compositor/TextNode":"3dGtM"}],"lKBnk":[function(require,module,exports) {
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
parcelHelpers.defineInteropFlag(exports);
var _node = require("./Node");
var _nodeDefault = parcelHelpers.interopDefault(_node);
var _nodeEvent = require("./NodeEvent");
var _nodeEventDefault = parcelHelpers.interopDefault(_nodeEvent);
class Canvas {
constructor(){
this.rootNode = new (0, _nodeDefault.default)("Root");
this.nodes = [];
this.pool = new DrawPool();
this.canvas = document.createElement("canvas");
this.context = this.canvas.getContext("2d");
this.installMouseManager();
this.installKeyboardManager();
}
init() {
this.canvas.style.imageRendering = "pixelated";
window.document.body.appendChild(this.canvas);
this.recalculateSize();
window.addEventListener("resize", ()=>this.recalculateSize());
this.pool.trigger = ()=>this.drawContext();
}
installMouseManager() {
this.canvas.addEventListener("mousedown", (event)=>{
let mouseEvent = new (0, _nodeEventDefault.default)();
mouseEvent.x = event.offsetX;
mouseEvent.y = event.offsetY;
mouseEvent.type = "mouse:down";
this.rootNode.emit("mouse", mouseEvent);
});
this.canvas.addEventListener("mousemove", (event)=>{
let mouseEvent = new (0, _nodeEventDefault.default)();
mouseEvent.x = event.offsetX;
mouseEvent.y = event.offsetY;
mouseEvent.data = {
deltaX: event.movementX,
deltaY: event.movementY
};
mouseEvent.type = "mouse:move";
this.rootNode.emit("mouse", mouseEvent);
});
this.canvas.addEventListener("mouseup", (event)=>{
let mouseEvent = new (0, _nodeEventDefault.default)();
mouseEvent.x = event.offsetX;
mouseEvent.y = event.offsetY;
mouseEvent.type = "mouse:up";
this.rootNode.emit("mouse", mouseEvent);
});
this.canvas.addEventListener("click", (event)=>{
let mouseEvent = new (0, _nodeEventDefault.default)();
mouseEvent.x = event.offsetX;
mouseEvent.y = event.offsetY;
mouseEvent.type = "mouse:click";
this.rootNode.emit("mouse", mouseEvent);
});
this.canvas.addEventListener("wheel", (event)=>{
let mouseEvent = new (0, _nodeEventDefault.default)();
mouseEvent.x = event.offsetX;
mouseEvent.y = event.offsetY;
mouseEvent.data = {
xModulus: event.deltaX == 0 ? 0 : event.deltaX < 0 ? -1 : 1,
yModulus: event.deltaY == 0 ? 0 : event.deltaY < 0 ? -1 : 1,
xScroll: event.deltaX,
yScroll: event.deltaY
};
mouseEvent.type = "mouse:wheel";
this.rootNode.emit("mouse", mouseEvent);
});
}
installKeyboardManager() {}
recalculateSize() {
let { width , height } = document.body.getClientRects()[0];
this.canvas.setAttribute("width", width + "px");
this.canvas.setAttribute("height", height + "px");
this.canvas.style.width = width + "px";
this.canvas.style.height = height + "px";
this.width = width;
this.height = height;
this.pool.notify();
}
addNode(node, priority = 0) {
this.nodes.push([
node,
priority
]);
node.on("draw", ()=>{
this.pool.notify();
});
this.pool.notify();
}
drawContext() {
this.rootNode.width = this.width;
this.rootNode.height = this.height;
this.rootNode.ChildNodes = this.nodes.sort(([, n], [, k])=>n - k).map((e)=>e[0]);
this.context.clearRect(0, 0, this.width, this.height);
this.rootNode.context.resize(this.rootNode.width, this.rootNode.height);
this.rootNode.draw().writeTo(this.context, 0, 0, this.rootNode.width, this.rootNode.height, 0, 0, this.rootNode.width, this.rootNode.height);
}
}
exports.default = Canvas;
class DrawPool {
addPool(e) {
if (!this.busy) this.notify();
else this.trigger = e;
}
notify() {
this.busy = true;
this.inf = requestAnimationFrame(()=>{
if (this.trigger) this.trigger();
this.busy = false;
});
}
constructor(){
this.busy = true;
this.inf = -1;
}
}
},{"./Node":"a8tDl","./NodeEvent":"9Fl2V","@parcel/transformer-js/src/esmodule-helpers.js":"7Rzro"}],"a8tDl":[function(require,module,exports) {
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
parcelHelpers.defineInteropFlag(exports);
var _canvasBuffer = require("./CanvasBuffer");
var _canvasBufferDefault = parcelHelpers.interopDefault(_canvasBuffer);
var _nodeEvent = require("./NodeEvent");
var _nodeEventDefault = parcelHelpers.interopDefault(_nodeEvent);
class Node {
constructor(name){
this.name = "";
this.context = new (0, _canvasBufferDefault.default)();
this.buffered = false;
this.requiredRedraw = true;
this.ChildNodes = [];
this.width = 0;
this.height = 0;
this.x = 0;
this.y = 0;
this.scale = 1;
this.rotate = 0;
this.mouseHover = false;
this.padding = {
left: 0,
right: 0,
top: 0,
bottom: 0
};
this._events = new Map();
this.drawScope = new Map();
this.name = name || "";
}
update() {
this.requiredRedraw = true;
if (this.parentNode) this.parentNode.update();
else this.emit("draw", new (0, _nodeEventDefault.default)(), false);
}
draw(maxWidth, maxHeight) {
this.context.clear();
let drawableAreaWidth = this.width;
let drawableAreaHeight = this.height;
if (maxWidth) drawableAreaWidth = Math.min(drawableAreaWidth, maxWidth);
if (maxHeight) drawableAreaHeight = Math.min(drawableAreaHeight, maxHeight);
if (this.hasEvent("draw")) {
let cancelDraw = false;
this.handleEvent("draw:before", (callback)=>{
return callback.call(this, {
drawableAreaWidth,
drawableAreaHeight
});
});
let frame = this.handleEvent("draw", (event)=>{
let offscreen = new (0, _canvasBufferDefault.default)(drawableAreaWidth, drawableAreaHeight);
cancelDraw = event.apply(this, [
offscreen,
{
width: drawableAreaWidth,
height: drawableAreaHeight
}
]);
return offscreen;
});
this.context = frame;
this.buffered = true;
this.handleEvent("draw:after", (callback)=>{
return callback.call(this, {
drawableAreaWidth,
drawableAreaHeight
});
});
if (!cancelDraw) return frame;
}
let width = drawableAreaWidth - (this.padding.right + this.padding.left);
let height = drawableAreaHeight - (this.padding.bottom + this.padding.top);
this.buffered = true;
let offscreen = new (0, _canvasBufferDefault.default)(width, height);
for (const node of this.ChildNodes)this.DrawChild(offscreen, node, width, height);
offscreen.writeTo(this.context, 0, 0, offscreen.width, offscreen.height, this.padding.left, this.padding.top, offscreen.width, offscreen.height);
return this.context;
}
getContextArea() {
return {
width: Math.min(this.width, this.parentNode?.width || Infinity) - (this.padding.right + this.padding.left),
height: Math.min(this.height, this.parentNode?.height || Infinity) - (this.padding.bottom + this.padding.top)
};
}
DrawChild(canvas, node, maxWidth, maxHeight) {
let canvasWidth = Math.min(node.width, maxWidth);
let canvasHeight = Math.min(node.height, maxHeight);
let x = 0;
let y = 0;
node.handleEvent("draw:before", (callback)=>{
return callback.call(node, {
canvasWidth,
canvasHeight
});
});
if (node.width == 0 || node.height == 0) return;
canvasWidth = Math.min(node.width, maxWidth);
canvasHeight = Math.min(node.height, maxHeight);
x += node.x;
y += node.y;
let frame;
if (!node.buffered) frame = node.draw(canvasWidth, canvasHeight);
else if (node.requiredRedraw) frame = node.draw(canvasWidth, canvasHeight);
else frame = node.context;
let context = canvas.context;
context.save();
if (node.rotate != 0) {
let translateX = canvasWidth / 2;
let translateY = canvasHeight / 2;
translateX += x;
translateY += y;
context.translate(translateX, translateY);
context.rotate(node.rotate);
context.translate(-translateX, -translateY);
}
canvas.writeFrom(frame.offscreen, 0, 0, frame.offscreen.width, frame.offscreen.height, x, y, canvasWidth * node.scale, canvasHeight * node.scale);
node.requiredRedraw = false;
context.restore();
node.handleEvent("draw:after", (callback)=>{
return callback.call(this, {
canvasWidth,
canvasHeight
});
});
}
isMatchPoint(x, y) {
let { x: realX , y: realY , width: realWidth , height: realheight } = this.realOffset();
let top = realY;
let left = realX;
let right = realX + realWidth;
let bottom = realY + realheight;
if (top < y && bottom > y && left < x && right > x) return true;
return false;
}
on(eventName, callback) {
if (this._events.has(eventName)) this._events.get(eventName)?.push(callback);
else this._events.set(eventName, [
callback
]);
}
realOffset() {
let { width , height } = this.getContextArea();
if (this.parentNode) {
let current = this;
let x = 0;
let y = 0;
while(true){
x += current.x;
y += current.y;
if (current.parentNode) {
x += current.parentNode.padding.left;
y += current.parentNode.padding.top;
current = current.parentNode;
} else break;
}
return {
x,
y,
width,
height
};
} else {
let x = this.x;
let y = this.y;
return {
x,
y,
width,
height
};
}
}
emit(eventName, args, notifyChild = true) {
let eventList = this._events.get(eventName);
if (notifyChild) this.ChildNodes.filter((node)=>{
if (node.isMatchPoint(args.x, args.y)) {
if (!node.mouseHover) {
node.mouseHover = true;
let event = args.clone();
event.type = "mouse:enter";
node.emit("mouse", event, false);
}
return true;
} else {
if (node.mouseHover) {
node.mouseHover = false;
let event = args.clone();
event.type = "mouse:leave";
node.emit("mouse", event);
}
return false;
}
}).some((node)=>{
node.emit(eventName, args);
return args.prevented != false;
});
if (args.stoppedBubbling == false) {
if (eventList) for (const event of eventList){
event.apply(this, [
args
]);
if (args.prevented) break;
}
}
}
hasEvent(eventName) {
return this.drawScope.has(eventName);
}
handleEvent(eventName, onCallback) {
let func = this.drawScope.get(eventName);
if (func) {
if (onCallback) return onCallback(func);
else return func.call(this);
}
}
handleDraw(e) {
this.drawScope.set("draw", e);
}
handleDrawBefore(e) {
this.drawScope.set("draw:before", e);
}
handleDrawAfter(e) {
this.drawScope.set("draw:after", e);
}
addNode(node) {
let { width , height } = this.getContextArea();
node.width = node.width || width;
node.height = node.height || height;
node.parentNode = this;
this.ChildNodes.push(node);
}
}
exports.default = Node;
},{"./CanvasBuffer":"jI6Ug","./NodeEvent":"9Fl2V","@parcel/transformer-js/src/esmodule-helpers.js":"7Rzro"}],"jI6Ug":[function(require,module,exports) {
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
parcelHelpers.defineInteropFlag(exports);
class CanvasBuffer {
constructor(width, height){
this.width = 0;
this.height = 0;
this.offscreen = new OffscreenCanvas(width || 0, height || 0);
this.context = this.offscreen.getContext("2d");
this.width = width || 0;
this.height = height || 0;
}
resize(width, height) {
if (this.width != width) {
this.offscreen.width = width;
this.width = width || 0;
}
if (this.height != height) {
this.offscreen.height = height;
this.height = height || 0;
}
}
clear() {
this.context.clearRect(0, 0, this.offscreen.width, this.offscreen.height);
}
writeFrom(canvas, x, y, width, height, dx, dy, dwidth, dheight) {
let args = [
x,
y,
width,
height,
dx,
dy,
dwidth,
dheight
];
if (canvas instanceof OffscreenCanvas || canvas instanceof HTMLCanvasElement) _draw_content_to_canvas(this.context, canvas, ...args);
if (canvas instanceof OffscreenCanvasRenderingContext2D || canvas instanceof CanvasRenderingContext2D) _draw_content_to_canvas(this.context, canvas.canvas, ...args);
if (canvas instanceof CanvasBuffer) _draw_content_to_canvas(this.context, canvas.offscreen, ...args);
}
writeTo(canvas, x, y, width, height, dx, dy, dwidth, dheight) {
let args = [
x,
y,
width,
height,
dx,
dy,
dwidth,
dheight
];
if (canvas instanceof OffscreenCanvas || canvas instanceof HTMLCanvasElement) {
let content = canvas.getContext("2d");
_draw_content_to_canvas(content, this.offscreen, ...args);
}
if (canvas instanceof OffscreenCanvasRenderingContext2D || canvas instanceof CanvasRenderingContext2D) _draw_content_to_canvas(canvas, this.offscreen, ...args);
if (canvas instanceof CanvasBuffer) _draw_content_to_canvas(canvas.context, this.offscreen, ...args);
}
}
exports.default = CanvasBuffer;
function _draw_content_to_canvas(context, canvas, x, y, width, height, dx, dy, dwidth, dheight) {
if (canvas.width != 0 && canvas.height != 0 && context.canvas.width != 0 && context.canvas.height != 0) context.drawImage(canvas, x || 0, y || 0, width || canvas.width, height || canvas.height, dx || 0, dy || 0, dwidth || canvas.width, dheight || canvas.height);
}
},{"@parcel/transformer-js/src/esmodule-helpers.js":"7Rzro"}],"7Rzro":[function(require,module,exports) {
exports.interopDefault = function(a) {
return a && a.__esModule ? a : {
default: a
};
};
exports.defineInteropFlag = function(a) {
Object.defineProperty(a, "__esModule", {
value: true
});
};
exports.exportAll = function(source, dest) {
Object.keys(source).forEach(function(key) {
if (key === "default" || key === "__esModule" || dest.hasOwnProperty(key)) return;
Object.defineProperty(dest, key, {
enumerable: true,
get: function() {
return source[key];
}
});
});
return dest;
};
exports.export = function(dest, destName, get) {
Object.defineProperty(dest, destName, {
enumerable: true,
get: get
});
};
},{}],"9Fl2V":[function(require,module,exports) {
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
parcelHelpers.defineInteropFlag(exports);
class NodeEvent {
clone() {
let u = new NodeEvent();
u.type = this.type;
u.prevented = this.prevented;
u.stoppedBubbling = this.stoppedBubbling;
u.data = this.data;
u.keyCode = this.keyCode;
u.key = this.key;
u.x = this.x;
u.y = this.y;
return u;
}
constructor(){
this.type = "";
this.prevented = false;
this.stoppedBubbling = false;
this.data = {};
}
}
exports.default = NodeEvent;
},{"@parcel/transformer-js/src/esmodule-helpers.js":"7Rzro"}],"3dGtM":[function(require,module,exports) {
var parcelHelpers = require("@parcel/transformer-js/src/esmodule-helpers.js");
parcelHelpers.defineInteropFlag(exports);
var _node = require("./Node");
var _nodeDefault = parcelHelpers.interopDefault(_node);
class TextNode extends (0, _nodeDefault.default) {
constructor(text){
super();
this.color = "#000000";
this.fontSize = 18;
this.text = text;
this.handleDrawBefore(function() {
this.height = this.fontSize;
this.context.context.save();
this.context.context.font = this.fontSize + "px system-ui";
this.width = this.context.context.measureText(this.text).width;
this.context.context.restore();
console.log(this.width);
});
this.handleDraw(function(canvasBuffer, area) {
let ctx = canvasBuffer.context;
ctx.font = this.fontSize + "px system-ui";
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText(this.text, 0, 0);
ctx.closePath();
});
}
}
exports.default = TextNode;
},{"./Node":"a8tDl","@parcel/transformer-js/src/esmodule-helpers.js":"7Rzro"}]},["3beyG","1jwFz"], "1jwFz", "parcelRequire94c2")
//# sourceMappingURL=index.js.map