Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@cosmograph/cosmograph

Package Overview
Dependencies
Maintainers
0
Versions
36
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@cosmograph/cosmograph - npm Package Compare versions

Comparing version 2.0.0-beta.5 to 2.0.0-beta.6

modules/legend/color/type/config.d.ts

2

duckdb/duckdb-wasm.js

@@ -1,2 +0,2 @@

import*as t from"@duckdb/duckdb-wasm";import{DuckDBDataProtocol as e}from"@duckdb/duckdb-wasm";import{Table as a,tableToIPC as n,tableFromJSON as r,tableFromIPC as i}from"apache-arrow";import{checkDevEnv as o,convertArrowToObject as s}from"../utils/utils.js";import{Format as c}from"../enum.js";const l=o(),u=t.getJsDelivrBundles();class w{constructor(){this.logTable=async(t,e=!1)=>{var a;if(!l)return;const n=`SELECT COUNT(*) as count FROM ${t}`,r=await this.query(n);if(!r)return;const i=null===(a=r.getChild("count"))||void 0===a?void 0:a.get(0),o=`SELECT * FROM ${t} ${e?"":"LIMIT 10"}`,c=await this.query(o);if(!c)return;const u=s(c);console.groupCollapsed(`Table: ${t} | ${i} rows ${e?"":"(showing first 10)"}`),console.table(u),console.groupEnd()}}static async getInstance(){return w._initPromise=(async()=>{const t=new w;return await t._init(),t})(),w._instance=await w._initPromise,w._instance}async _init(){const e=await t.selectBundle(u),a=URL.createObjectURL(new Blob([`importScripts("${e.mainWorker}");`],{type:"text/javascript"})),n=new Worker(a),r=new t.VoidLogger;this._db=new t.AsyncDuckDB(r,n),await this._db.instantiate(e.mainModule,e.pthreadWorker),this._connection=await this._db.connect(),await this._connection.query("\n SET max_expression_depth TO 20000000;\n SET memory_limit = '10GB';\n ".trim()),URL.revokeObjectURL(a)}get connection(){if(!this._connection)throw new Error("Cosmograph: DuckDB-Wasm connection is not initialized");return this._connection}get db(){if(!this._db)throw new Error("Cosmograph: DuckDB-Wasm is not initialized");return this._db}async destroy(){await this.connection.close(),await this.db.terminate()}async dropTable(t){await this.query(`DROP TABLE IF EXISTS "${t}"`)}async query(t){let e;l&&(console.log("%cExecuted query:","color: #a6a6a6;",{sql:t}),e=performance.now());try{return await this.connection.query(t)}catch(t){console.warn(`Couldn't query internal DuckDB instance: ${t}`)}finally{if(l&&void 0!==e){const a=performance.now()-e;console.log("%cFinished query:","color: #a6a6a6;",{sql:t,duration:+a.toFixed(1)})}}}async exec(t){this.query(t)}async send(t,e){l&&console.log(t),l&&console.time("query");try{const a=await this.connection.send(t);let n;for(;!(n=await a.next()).done;){const t=n.value;for(let a=0;a<t.numRows;a++){const n=t.getChildAt(a);e&&e(n)}}}catch(t){console.warn(`Couldn't query internal DuckDB instance: ${t}`)}l&&console.timeEnd("query")}async uploadData(t,e,n=!1,r,i){if(Array.isArray(t)&&t.length>0&&t[0]&&"object"==typeof t[0])return await this.uploadObject(t,e,n);if(t instanceof Uint8Array||t instanceof ArrayBuffer||t instanceof a)return await this._uploadArrow(t,e,n);if("string"==typeof t||t instanceof File){const a=t=>t.endsWith(".arrow")?c.Arrow:t.endsWith(".parquet")||t.endsWith(".pq")?c.Parquet:t.endsWith(".csv")||t.endsWith(".tsv")?c.CSV:t.endsWith(".json")?c.JSON:"unknown",o=t instanceof File?t.name:t,s=a(o);"unknown"===s&&console.warn(`Unknown file type: ${o}`);try{switch(s){case c.Arrow:return await this._uploadArrow(t,e,n);case c.Parquet:return await this._uploadParquet(t,e,n);case c.CSV:return await this._uploadCSV(t,e,n,r,i);case c.JSON:return await this._uploadJSON(t,e,n);default:throw new Error("Unsupported file type")}}catch(t){return{error:t}}}return{}}async uploadArrow(t,e){return await this._uploadArrow(t,e)}async exportTableToArrow(t){try{const e=await this.connection.query(`SELECT * FROM ${t}`);return e.numRows?e:void console.warn(`No data exported from table "${t}"`)}catch(e){throw console.warn(`exportTableToArrow: Failed to export table "${t}":`,e),e}}async exportTableToArrowBuffer(t){const e=await this.exportTableToArrow(t);return e?n(e):void 0}async exportTableToPq(t){var e,a;const n=`${t}.${c.Parquet}`;try{return await this.connection.query(`COPY ${t} TO '${n}' (FORMAT PARQUET)`),await(null===(e=this._db)||void 0===e?void 0:e.copyFileToBuffer(n))}catch(e){throw console.error(`Failed to export table "${t}" to file "${n}":`,e),e}finally{await(null===(a=this._db)||void 0===a?void 0:a.registerEmptyFileBuffer(n))}}async exportTableToCSV(t){var e,a;const n=`${t}.${c.CSV}`;try{return await this.connection.query(`COPY ${t} TO '${n}' (HEADER, DELIMITER ',')`),await(null===(e=this._db)||void 0===e?void 0:e.copyFileToBuffer(n))}catch(e){throw console.error(`Failed to export table "${t}" to file "${n}":`,e),e}finally{await(null===(a=this._db)||void 0===a?void 0:a.registerEmptyFileBuffer(n))}}async uploadObject(t,e,a=!1){if(0===t.length)return{};try{const n=`t_${e}`;await this.query(`DROP TABLE IF EXISTS "${n}"`);const i=r(t);return await this.connection.insertArrowTable(i,{name:n}),await this._handleTableInsertion(n,e,a),await this.logTable(e),{}}catch(t){return{error:t}}}async _uploadCSV(t,e,a=!1,n,r){const i=`t_${e}`;let o=null;try{let s;if(t instanceof File){const e=await t.text();o=t.name,await this.db.registerFileText(o,e),s=o}else s=t;const c=`\n CREATE TABLE ${i} AS SELECT * FROM read_csv_auto(\n '${s}',\n SAMPLE_SIZE=-1,\n allow_quoted_nulls=true,\n ignore_errors=true,\n auto_type_candidates=['NULL', 'BOOLEAN', 'INT', 'DOUBLE', 'TIME', 'DATE', 'TIMESTAMP', 'VARCHAR']\n ${n?`, timestampformat='${n}'`:""}\n ${r?`, types=${JSON.stringify(r)}`:""}\n )`.trim();return await this.query(c),await this._handleTableInsertion(i,e,a),await this.logTable(e),{}}catch(t){return{error:t}}finally{o&&await this.db.dropFile(o)}}async _uploadParquet(t,a,n=!1){const r=`t_${a}`;let i=null;try{let o;t instanceof File?(i=t.name,await this.db.registerFileHandle(i,t,e.BROWSER_FILEREADER,!0),o=i):o=t;const s=`CREATE TABLE ${r} AS SELECT * FROM read_parquet('${o}')`;return await this.query(s),await this._handleTableInsertion(r,a,n),await this.logTable(a),{}}catch(t){return{error:t}}finally{i&&await this.db.dropFile(i)}}async _uploadArrow(t,e,n=!1){try{let r;const o=`t_${e}`;if(await this.query(`DROP TABLE IF EXISTS "${o}"`),t instanceof File)r=await t.arrayBuffer(),r=new Uint8Array(r);else if("string"==typeof t){const e=await fetch(t);e.ok||console.warn(`Error while fetching file: ${e.statusText}`),r=await e.arrayBuffer(),r=new Uint8Array(r)}else r=t;try{const s=t instanceof a?t:i(r);await this.connection.insertArrowTable(s,{name:o}),await this._handleTableInsertion(o,e,n)}catch(t){console.warn("_uploadArrow:",t)}return await this.logTable(e),{}}catch(t){return{error:t}}}async _uploadJSON(t,e,a=!1){const n=`t_${e}`;await this.query(`DROP TABLE IF EXISTS "${n}"`);try{if(t instanceof File){const e=await t.text();await this.db.registerFileText("json",e)}else{const e=await fetch(t);e.ok||console.warn(`Error while fetching file: ${e.statusText}`);const a=await e.text();await this.db.registerFileText("json",a)}try{await this.connection.insertJSONFromPath("json",{name:n})}catch(t){console.warn("_uploadJSON:",t)}return await this._handleTableInsertion(n,e,a),await this.logTable(e),{}}catch(t){return{error:t}}finally{await this.db.dropFile("json")}}async _handleTableInsertion(t,e,a){a?(await this.query(`INSERT INTO "${e}" SELECT * FROM "${t}"`),await this.query(`DROP TABLE IF EXISTS "${t}"`)):(await this.query(`DROP TABLE IF EXISTS "${e}"`),await this.query(`ALTER TABLE "${t}" RENAME TO "${e}"`))}}export{w as DuckDBInstance};
import*as t from"@duckdb/duckdb-wasm";import{DuckDBDataProtocol as e}from"@duckdb/duckdb-wasm";import{Table as a,tableToIPC as r,tableFromJSON as n,tableFromIPC as i}from"apache-arrow";import{checkDevEnv as o,convertArrowToObject as s}from"../utils/utils.js";import{Format as c}from"../enum.js";const l=o(),u=t.getJsDelivrBundles();class w{constructor(){this.logTable=async(t,e=!1)=>{var a;if(!l)return;const r=`SELECT COUNT(*) as count FROM ${t}`,n=await this.query(r);if(!n)return;const i=null===(a=n.getChild("count"))||void 0===a?void 0:a.get(0),o=`SELECT * FROM ${t} ${e?"":"LIMIT 10"}`,c=await this.query(o);if(!c)return;const u=s(c);console.groupCollapsed(`Table: ${t} | ${i} rows ${e?"":"(showing first 10)"}`),console.table(u),console.groupEnd()}}static async getInstance(){return w._initPromise=(async()=>{const t=new w;return await t._init(),t})(),w._instance=await w._initPromise,w._instance}async _init(){const e=await t.selectBundle(u),a=URL.createObjectURL(new Blob([`importScripts("${e.mainWorker}");`],{type:"text/javascript"})),r=new Worker(a),n=new t.VoidLogger;this._db=new t.AsyncDuckDB(n,r),await this._db.instantiate(e.mainModule,e.pthreadWorker),this._connection=await this._db.connect(),await this._connection.query("\n SET max_expression_depth TO 20000000;\n SET memory_limit = '10GB';\n ".trim()),URL.revokeObjectURL(a)}get connection(){if(!this._connection)throw new Error("Cosmograph: DuckDB-Wasm connection is not initialized");return this._connection}get db(){if(!this._db)throw new Error("Cosmograph: DuckDB-Wasm is not initialized");return this._db}async destroy(){await this.connection.close(),await this.db.terminate()}async dropTable(t){await this.query(`DROP TABLE IF EXISTS "${t}"`)}async query(t){let e;l&&(console.log("%cExecuted query:","color: #a6a6a6;",{sql:t}),e=performance.now());try{return await this.connection.query(t)}catch(t){console.warn(`Couldn't query internal DuckDB instance: ${t}`)}finally{if(l&&void 0!==e){const a=performance.now()-e;console.log("%cFinished query:","color: #a6a6a6;",{sql:t,duration:+a.toFixed(1)})}}}async exec(t){this.query(t)}async send(t,e){l&&console.log(t),l&&console.time("query");try{const a=await this.connection.send(t);let r;for(;!(r=await a.next()).done;){const t=r.value;for(let a=0;a<t.numRows;a++){const r=t.getChildAt(a);e&&e(r)}}}catch(t){console.warn(`Couldn't query internal DuckDB instance: ${t}`)}l&&console.timeEnd("query")}async uploadData(t,e,r=!1,n,i){if(Array.isArray(t)&&t.length>0&&t[0]&&"object"==typeof t[0])return await this.uploadObject(t,e,r);if(t instanceof Uint8Array||t instanceof ArrayBuffer||t instanceof a)return await this._uploadArrow(t,e,r);if("string"==typeof t||t instanceof File){const a=t=>t.endsWith(".arrow")?c.Arrow:t.endsWith(".parquet")||t.endsWith(".pq")?c.Parquet:t.endsWith(".csv")||t.endsWith(".tsv")?c.CSV:t.endsWith(".json")?c.JSON:"unknown",o=t instanceof File?t.name:t,s=a(o);"unknown"===s&&console.warn(`Unknown file type: ${o}`);try{switch(s){case c.Arrow:return await this._uploadArrow(t,e,r);case c.Parquet:return await this._uploadParquet(t,e,r);case c.CSV:return await this._uploadCSV(t,e,r,n,i);case c.JSON:return await this._uploadJSON(t,e,r);default:throw new Error("Unsupported file type")}}catch(t){return{error:t}}}return{error:"Could not upload data"}}async uploadArrow(t,e){return await this._uploadArrow(t,e)}async exportTableToArrow(t){try{const e=await this.connection.query(`SELECT * FROM ${t}`);return e.numRows?e:void console.warn(`No data exported from table "${t}"`)}catch(e){throw console.warn(`exportTableToArrow: Failed to export table "${t}":`,e),e}}async exportTableToArrowBuffer(t){const e=await this.exportTableToArrow(t);return e?r(e):void 0}async exportTableToPq(t){var e,a;const r=`${t}.${c.Parquet}`;try{return await this.connection.query(`COPY ${t} TO '${r}' (FORMAT PARQUET)`),await(null===(e=this._db)||void 0===e?void 0:e.copyFileToBuffer(r))}catch(e){console.error(`Failed to export table "${t}" to file "${r}":`,e)}finally{await(null===(a=this._db)||void 0===a?void 0:a.registerEmptyFileBuffer(r))}}async exportTableToCSV(t){var e,a;const r=`${t}.${c.CSV}`;try{return await this.connection.query(`COPY ${t} TO '${r}' (HEADER, DELIMITER ',')`),await(null===(e=this._db)||void 0===e?void 0:e.copyFileToBuffer(r))}catch(e){console.error(`Failed to export table "${t}" to file "${r}":`,e)}finally{await(null===(a=this._db)||void 0===a?void 0:a.registerEmptyFileBuffer(r))}}async uploadObject(t,e,a=!1){if(0===t.length)return{};try{const r=`t_${e}`;await this.query(`DROP TABLE IF EXISTS "${r}"`);const i=n(t);return await this.connection.insertArrowTable(i,{name:r}),await this._handleTableInsertion(r,e,a),await this.logTable(e),{}}catch(t){return{error:t}}}async _uploadCSV(t,e,a=!1,r,n){const i=`t_${e}`;let o=null;try{let s;if(t instanceof File){const e=await t.text();o=t.name,await this.db.registerFileText(o,e),s=o}else s=t;const c=`\n CREATE TABLE ${i} AS SELECT * FROM read_csv_auto(\n '${s}',\n SAMPLE_SIZE=-1,\n allow_quoted_nulls=true,\n ignore_errors=true,\n auto_type_candidates=['NULL', 'BOOLEAN', 'INT', 'DOUBLE', 'TIME', 'DATE', 'TIMESTAMP', 'VARCHAR']\n ${r?`, timestampformat='${r}'`:""}\n ${n?`, types=${JSON.stringify(n)}`:""}\n )`.trim();return await this.query(c),await this._handleTableInsertion(i,e,a),await this.logTable(e),{}}catch(t){return{error:t}}finally{o&&await this.db.dropFile(o)}}async _uploadParquet(t,a,r=!1){const n=`t_${a}`;let i=null;try{let o;t instanceof File?(i=t.name,await this.db.registerFileHandle(i,t,e.BROWSER_FILEREADER,!0),o=i):o=t;const s=`CREATE TABLE ${n} AS SELECT * FROM read_parquet('${o}')`;return await this.query(s),await this._handleTableInsertion(n,a,r),await this.logTable(a),{}}catch(t){return{error:t}}finally{i&&await this.db.dropFile(i)}}async _uploadArrow(t,e,r=!1){try{let n;const o=`t_${e}`;if(await this.query(`DROP TABLE IF EXISTS "${o}"`),t instanceof File)n=await t.arrayBuffer(),n=new Uint8Array(n);else if("string"==typeof t){const e=await fetch(t);e.ok||console.warn(`Error while fetching file: ${e.statusText}`),n=await e.arrayBuffer(),n=new Uint8Array(n)}else n=t;try{const s=t instanceof a?t:i(n);await this.connection.insertArrowTable(s,{name:o}),await this._handleTableInsertion(o,e,r)}catch(t){return{error:t}}return await this.logTable(e),{}}catch(t){return{error:t}}}async _uploadJSON(t,e,a=!1){const r=`t_${e}`;await this.query(`DROP TABLE IF EXISTS "${r}"`);try{if(t instanceof File){const e=await t.text();await this.db.registerFileText("json",e)}else{const e=await fetch(t);e.ok||console.warn(`Error while fetching file: ${e.statusText}`);const a=await e.text();await this.db.registerFileText("json",a)}try{await this.connection.insertJSONFromPath("json",{name:r})}catch(t){return console.warn("_uploadJSON:",t),{error:t}}return await this._handleTableInsertion(r,e,a),await this.logTable(e),{}}catch(t){return{error:t}}finally{await this.db.dropFile("json")}}async _handleTableInsertion(t,e,a){a?(await this.query(`INSERT INTO "${e}" SELECT * FROM "${t}"`),await this.query(`DROP TABLE IF EXISTS "${t}"`)):(await this.query(`DROP TABLE IF EXISTS "${e}"`),await this.query(`ALTER TABLE "${t}" RENAME TO "${e}"`))}}export{w as DuckDBInstance};
//# sourceMappingURL=duckdb-wasm.js.map

@@ -1,3 +0,3 @@

import { Table, Vector } from 'apache-arrow';
import { wasmConnector, restConnector, MosaicClient } from '@uwdata/mosaic-core';
import { Table } from 'apache-arrow';
import { DuckDBInstance, WasmDuckDBConnection } from './duckdb-wasm';

@@ -28,3 +28,2 @@ /**

destroy(): Promise<void>;
send(query: string, callback: (result: Vector) => void): Promise<void>;
}

@@ -1,2 +0,2 @@

import{wasmConnector as o,restConnector as t,Coordinator as n,Priority as r}from"@uwdata/mosaic-core";import{DuckDBInstance as i}from"./duckdb-wasm.js";import{cosmographLog as a}from"../utils/log.js";import{checkDevEnv as e}from"../utils/utils.js";const c=e();class s extends n{constructor(){super()}async updateClient(o,t,n=r.Normal){if(!o._preventQuerying&&null!==t.sql){o.queryPending();try{const r=await this.query(t,{priority:n});o.queryResult(r).update()}catch(t){this._logger.error("Custom error handling:",t),o.queryError(t)}}}}class l{constructor(o,t){if(!o)return;const n=new s;n.databaseConnector(o),c?n.manager.logQueries(!0):n.logger(null),this._coordinator=n,this._internalDB=t}static async create(n){let r,e;try{if(n)"string"==typeof n?(r=await t(n),a("Connected to remote DuckDB instance","","ok")):(r=await o(n),a("Connected to configured duckdb-wasm instance","","ok"));else{const t=Date.now();e=await i.getInstance(),r=await o({duckdb:e.db,connection:e.connection});const n=Date.now();a(`Initialized local duckdb-wasm instance in ${(n-t).toFixed()}ms`,"","ok")}}catch(o){return void a(`Couldn't create MosaicDBCoordinator: ${o}`,"","error")}return new l(r,e)}get internalDB(){return this._internalDB}connect(o){var t,n;(null===(t=this._coordinator)||void 0===t?void 0:t.clients.has(o))||null===(n=this._coordinator)||void 0===n||n.connect(o)}disconnect(o){var t,n;(null===(t=this._coordinator)||void 0===t?void 0:t.clients.has(o))&&(null===(n=this._coordinator)||void 0===n||n.disconnect(o))}async exec(o,t){var n;let r;try{r=await(null===(n=this._coordinator)||void 0===n?void 0:n.exec(o,{priority:null!=t?t:0}))}catch(o){console.warn(`Couldn't call exec in MosaicDBCoordinator: ${o}`)}return r}async query(o,t=!1){var n;let r;try{r=await(null===(n=this._coordinator)||void 0===n?void 0:n.query(o,{cache:t}))}catch(o){console.warn(`Couldn't call query in MosaicDBCoordinator: ${o}`)}return r}clearCache(){var o;null===(o=this._coordinator)||void 0===o||o.clear({cache:!0,catalog:!0,clients:!1})}async destroy(){var o,t;await(null===(o=this._internalDB)||void 0===o?void 0:o.destroy()),null===(t=this._coordinator)||void 0===t||t.clear()}async send(o,t){var n;try{await(null===(n=this._internalDB)||void 0===n?void 0:n.send(o,t))}catch(o){console.warn(`Couldn't call send in MosaicDBCoordinator: ${o}`)}}}export{l as MosaicDBCoordinator};
import{wasmConnector as o,restConnector as t,Coordinator as r,Priority as n}from"@uwdata/mosaic-core";import{DuckDBInstance as i}from"./duckdb-wasm.js";import{cosmographLog as e}from"../utils/log.js";import{checkDevEnv as a}from"../utils/utils.js";const c=a();class s extends r{constructor(){super()}async updateClient(o,t,r=n.Normal){if(!o._preventQuerying&&null!==t.sql){o.queryPending();try{const n=await this.query(t,{priority:r});o.queryResult(n).update()}catch(t){this._logger.error("Custom error handling:",t),o.queryError(t)}}}}class l{constructor(o,t){if(!o)return;const r=new s;r.databaseConnector(o),c?r.manager.logQueries(!0):r.logger(null),this._coordinator=r,this._internalDB=t}static async create(r){let n,a;try{if(r)"string"==typeof r?(n=await t(r),e("Connected to remote DuckDB instance","","ok")):(n=await o(r),e("Connected to configured duckdb-wasm instance","","ok"));else{const t=Date.now();a=await i.getInstance(),n=await o({duckdb:a.db,connection:a.connection});const r=Date.now();e(`Initialized local duckdb-wasm instance in ${(r-t).toFixed()}ms`,"","ok")}}catch(o){return void e(`Couldn't create MosaicDBCoordinator: ${o}`,"","error")}return new l(n,a)}get internalDB(){return this._internalDB}connect(o){var t,r;(null===(t=this._coordinator)||void 0===t?void 0:t.clients.has(o))||null===(r=this._coordinator)||void 0===r||r.connect(o)}disconnect(o){var t,r;(null===(t=this._coordinator)||void 0===t?void 0:t.clients.has(o))&&(null===(r=this._coordinator)||void 0===r||r.disconnect(o))}async exec(o,t){var r;let n;try{n=await(null===(r=this._coordinator)||void 0===r?void 0:r.exec(o,{priority:null!=t?t:0}))}catch(o){console.warn(`Couldn't call exec in MosaicDBCoordinator: ${o}`)}return n}async query(o,t=!1){var r;let n;try{n=await(null===(r=this._coordinator)||void 0===r?void 0:r.query(o,{cache:t}))}catch(o){console.warn(`Couldn't call query in MosaicDBCoordinator: ${o}`)}return n}clearCache(){var o;null===(o=this._coordinator)||void 0===o||o.clear({cache:!0,catalog:!0,clients:!1})}async destroy(){var o,t;await(null===(o=this._internalDB)||void 0===o?void 0:o.destroy()),null===(t=this._coordinator)||void 0===t||t.clear()}}export{l as MosaicDBCoordinator};
//# sourceMappingURL=mosaic-coordinator.js.map

@@ -6,2 +6,3 @@ export * from './modules/cosmograph';

export * from './modules/legend/color/range';
export * from './modules/legend/color/type';
export * from './modules/data-kit/data-kit';

@@ -1,2 +0,2 @@

export{Cosmograph}from"./modules/cosmograph/index.js";export{CosmographTimeline}from"./modules/timeline/index.js";export{CosmographHistogram}from"./modules/histogram/index.js";export{CosmographSizeLegend}from"./modules/legend/size/index.js";export{CosmographRangeColorLegend}from"./modules/legend/color/range/index.js";export{downloadCosmographData,prepareCosmographData,prepareCosmographDataArrow}from"./modules/data-kit/data-kit.js";
export{Cosmograph}from"./modules/cosmograph/index.js";export{CosmographTimeline}from"./modules/timeline/index.js";export{CosmographHistogram}from"./modules/histogram/index.js";export{CosmographSizeLegend}from"./modules/legend/size/index.js";export{CosmographRangeColorLegend}from"./modules/legend/color/range/index.js";export{CosmographTypeColorLegend}from"./modules/legend/color/type/index.js";export{downloadCosmographData,prepareCosmographData,prepareCosmographDataArrow}from"./modules/data-kit/data-kit.js";
//# sourceMappingURL=index.js.map

@@ -1,2 +0,2 @@

const e={disableSimulation:null,showTopLabelsLimit:100,showHoveredPointLabel:!1,staticLabelWeight:.8,dynamicLabelWeight:.7,labelPadding:5};export{e as defaultCosmographConfig};
const t={disableSimulation:null,showTopLabelsLimit:100,showHoveredPointLabel:!1,staticLabelWeight:.8,dynamicLabelWeight:.7,labelMargin:5,labelPadding:{left:7,top:4,right:7,bottom:4}};export{t as defaultCosmographConfig};
//# sourceMappingURL=config.js.map

@@ -188,3 +188,3 @@ import { Table } from 'apache-arrow';

export declare const requiredProps: (keyof CosmographConfig)[];
export declare const unrequiredProps: ("points" | "pointId" | "pointIndex" | "pointColor" | "pointColorFn" | "pointSize" | "pointSizeFn" | "pointLabel" | "pointLabelWeight" | "pointX" | "pointY" | "links" | "linkSource" | "linkSourceIndex" | "linkTarget" | "linkTargetIndex" | "linkColor" | "linkColorFn" | "linkWidth" | "linkWidthFn" | "linkArrow" | "linkArrowFn" | "linkStrength" | "linkStrengthFn" | "disableSimulation" | "backgroundColor" | "spaceSize" | "defaultPointColor" | "pointGreyoutOpacity" | "defaultPointSize" | "pointSizeScale" | "hoveredPointCursor" | "renderHoveredPointRing" | "hoveredPointRingColor" | "focusedPointRingColor" | "focusedPointIndex" | "renderLinks" | "defaultLinkColor" | "linkGreyoutOpacity" | "defaultLinkWidth" | "linkWidthScale" | "curvedLinks" | "curvedLinkSegments" | "curvedLinkWeight" | "curvedLinkControlPointDistance" | "defaultLinkArrows" | "linkArrowsSizeScale" | "linkVisibilityDistanceRange" | "linkVisibilityMinTransparency" | "useQuadtree" | "showFPSMonitor" | "pixelRatio" | "scalePointsOnZoom" | "initialZoomLevel" | "disableZoom" | "enableDrag" | "fitViewOnInit" | "fitViewDelay" | "fitViewPadding" | "fitViewDuration" | "fitViewByPointsInRect" | "randomSeed" | "pointSamplingDistance" | "showDynamicLabels" | "showLabelsFor" | "showTopLabels" | "showTopLabelsLimit" | "showTopLabelsBy" | "pointLabelClassName" | "pointLabelFn" | "pointLabelWeightFn" | "staticLabelWeight" | "dynamicLabelWeight" | "labelPadding" | "showHoveredPointLabel" | "hoveredPointLabelClassName" | "rectangularSelectorClassName" | "onPointsFiltered" | "onLinksFiltered" | "onLabelClick" | "onDataUpdated" | "onAreaSelected" | "simulationDecay" | "simulationGravity" | "simulationCenter" | "simulationRepulsion" | "simulationRepulsionTheta" | "simulationRepulsionQuadtreeLevels" | "simulationLinkSpring" | "simulationLinkDistance" | "simulationLinkDistRandomVariationRange" | "simulationRepulsionFromMouse" | "simulationFriction" | "onSimulationStart" | "onSimulationEnd" | "onSimulationPause" | "onSimulationRestart" | "onSimulationTick" | "onClick" | "onMouseMove" | "onPointMouseOver" | "onPointMouseOut" | "onZoomStart" | "onZoom" | "onZoomEnd" | "onDragStart" | "onDrag" | "onDragEnd")[];
export declare const unrequiredProps: ("points" | "pointId" | "pointIndex" | "pointColor" | "pointColorFn" | "pointSize" | "pointSizeFn" | "pointLabel" | "pointLabelWeight" | "pointX" | "pointY" | "links" | "linkSource" | "linkSourceIndex" | "linkTarget" | "linkTargetIndex" | "linkColor" | "linkColorFn" | "linkWidth" | "linkWidthFn" | "linkArrow" | "linkArrowFn" | "linkStrength" | "linkStrengthFn" | "disableSimulation" | "backgroundColor" | "spaceSize" | "defaultPointColor" | "pointGreyoutOpacity" | "defaultPointSize" | "pointSizeScale" | "hoveredPointCursor" | "renderHoveredPointRing" | "hoveredPointRingColor" | "focusedPointRingColor" | "focusedPointIndex" | "renderLinks" | "defaultLinkColor" | "linkGreyoutOpacity" | "defaultLinkWidth" | "linkWidthScale" | "curvedLinks" | "curvedLinkSegments" | "curvedLinkWeight" | "curvedLinkControlPointDistance" | "defaultLinkArrows" | "linkArrowsSizeScale" | "linkVisibilityDistanceRange" | "linkVisibilityMinTransparency" | "useQuadtree" | "showFPSMonitor" | "pixelRatio" | "scalePointsOnZoom" | "initialZoomLevel" | "disableZoom" | "enableDrag" | "fitViewOnInit" | "fitViewDelay" | "fitViewPadding" | "fitViewDuration" | "fitViewByPointsInRect" | "randomSeed" | "pointSamplingDistance" | "showDynamicLabels" | "showLabelsFor" | "showTopLabels" | "showTopLabelsLimit" | "showTopLabelsBy" | "pointLabelClassName" | "pointLabelFn" | "pointLabelWeightFn" | "staticLabelWeight" | "dynamicLabelWeight" | "labelMargin" | "labelPadding" | "showHoveredPointLabel" | "hoveredPointLabelClassName" | "rectangularSelectorClassName" | "onPointsFiltered" | "onLinksFiltered" | "onLabelClick" | "onDataUpdated" | "onAreaSelected" | "simulationDecay" | "simulationGravity" | "simulationCenter" | "simulationRepulsion" | "simulationRepulsionTheta" | "simulationRepulsionQuadtreeLevels" | "simulationLinkSpring" | "simulationLinkDistance" | "simulationLinkDistRandomVariationRange" | "simulationRepulsionFromMouse" | "simulationFriction" | "simulationImpulse" | "onSimulationStart" | "onSimulationEnd" | "onSimulationPause" | "onSimulationRestart" | "onSimulationTick" | "onClick" | "onMouseMove" | "onPointMouseOver" | "onPointMouseOut" | "onZoomStart" | "onZoom" | "onZoomEnd" | "onDragStart" | "onDrag" | "onDragEnd")[];
/**

@@ -191,0 +191,0 @@ * Represents the input data for Cosmograph points or links.

@@ -14,2 +14,3 @@ import { CosmographConfig } from './config';

readonly DynamicLabelWeight: "dynamicLabelWeight";
readonly LabelMargin: "labelMargin";
readonly LabelPadding: "labelPadding";

@@ -95,7 +96,17 @@ };

/**
* Specifies the padding between the label and the point.
* Specifies the margin between the label and the point.
* Default: `5`
*/
[LabelsKeys.LabelPadding]?: number;
[LabelsKeys.LabelMargin]?: number;
/**
* Specifies the padding of the label element.
* Default: `{ left: 7, top: 4, right: 7, bottom: 4 }`
*/
[LabelsKeys.LabelPadding]?: {
top: number;
left: number;
right: number;
bottom: number;
};
/**
* Whether to show a hovered point label.

@@ -102,0 +113,0 @@ * Default: `false`

@@ -1,2 +0,2 @@

import{BasePointsConfigKeys as a}from"./data.js";const e={ShowDynamicLabels:"showDynamicLabels",ShowLabelsFor:"showLabelsFor",ShowTopLabels:"showTopLabels",ShowTopLabelsLimit:"showTopLabelsLimit",ShowTopLabelsBy:"showTopLabelsBy",PointLabelClassName:"pointLabelClassName",PointLabelFn:"pointLabelFn",PointLabelWeightFn:"pointLabelWeightFn",StaticLabelWeight:"staticLabelWeight",DynamicLabelWeight:"dynamicLabelWeight",LabelPadding:"labelPadding"},o=[...Object.values(e),a.PointLabel,a.PointLabelWeight];export{e as LabelsKeys,o as labelsUpdateKeys};
import{BasePointsConfigKeys as a}from"./data.js";const e={ShowDynamicLabels:"showDynamicLabels",ShowLabelsFor:"showLabelsFor",ShowTopLabels:"showTopLabels",ShowTopLabelsLimit:"showTopLabelsLimit",ShowTopLabelsBy:"showTopLabelsBy",PointLabelClassName:"pointLabelClassName",PointLabelFn:"pointLabelFn",PointLabelWeightFn:"pointLabelWeightFn",StaticLabelWeight:"staticLabelWeight",DynamicLabelWeight:"dynamicLabelWeight",LabelMargin:"labelMargin",LabelPadding:"labelPadding"},l=[...Object.values(e),a.PointLabel,a.PointLabelWeight];export{e as LabelsKeys,l as labelsUpdateKeys};
//# sourceMappingURL=labels.js.map

@@ -61,2 +61,7 @@ import { GraphSimulationSettings } from '@cosmograph/cosmos';

simulationFriction?: GraphSimulationSettings['friction'];
/**
* Coefficient of simulation impulse from 0 to 1. If `undefined`, the graph will not apply a new impulse to the renders during adding or removing data items, but instead will use the current simulation impulse value from the graph. Has no impact if `disableSimulation` is `true`.
* Default value: `undefined`.
*/
simulationImpulse?: number;
}

@@ -63,0 +68,0 @@ export interface SimulationEventConfig {

@@ -1,2 +0,2 @@

const n=async(n,e,t)=>{var r;return await n.query(`SELECT ${null!==(r=null==t?void 0:t.join(", "))&&void 0!==r?r:"*"} FROM ${e}`)},e=(n,e)=>{if(!e.linkSourceIndex||!e.linkTargetIndex)return[];const t=n.getChild(e.linkSourceIndex),r=n.getChild(e.linkTargetIndex),i=n.numRows,l=new Array(2*i);for(let n=0,e=0;n<i;n++,e+=2)l[e]=null==t?void 0:t.get(n),l[e+1]=null==r?void 0:r.get(n);return l},t=(n,e)=>{if(!e.linkSourceIndex||!e.linkTargetIndex)return new Set;const t=n.getChild(e.linkSourceIndex),r=n.getChild(e.linkTargetIndex),i=t.concat(r),l=2*n.numRows,o=new Set;for(let n=0;n<l;n++){const e=i.get(n);null!==e&&o.add(e)}return o},r=async(n,e,t,r,i)=>{var l,o,u,d;const a=i.map((n=>"string"==typeof n?`'${n}'`:n)),c=`SELECT ${t.linkSourceIndex}, ${t.linkTargetIndex} FROM ${e} WHERE ${r} IN (${a.join(", ")})`,$=await n.query(c);if(!$)return;const g=null!==(o=null===(l=$.getChildAt(0))||void 0===l?void 0:l.toArray())&&void 0!==o?o:[],I=null!==(d=null===(u=$.getChildAt(1))||void 0===u?void 0:u.toArray())&&void 0!==d?d:[];return[...new Set([...g,...I])]},i=async(n,e,t,r)=>{const i=r.map((n=>`'${n}'`)).join(", ");return await n.query(`SELECT * FROM ${e} WHERE ${t.linkSource} IN (${i}) OR ${t.linkTarget} IN (${i})`)},l=async(n,e,t,r)=>{const i=r.join(", ");return await n.query(`SELECT * FROM ${e} WHERE ${t.linkSourceIndex} IN (${i}) OR ${t.linkTargetIndex} IN (${i})`)};export{n as getAllLinks,i as getLinksByPointIds,l as getLinksByPointIndices,r as getPointIndicesByLinksColumnValues,t as getPointIndicesFromLinks,e as mergeLinkPositions};
const n=async(n,e,r)=>{var t;return await n.query(`SELECT ${null!==(t=null==r?void 0:r.map((n=>`"${n}"`)).join(", "))&&void 0!==t?t:"*"} FROM ${e}`)},e=(n,e)=>{if(!e.linkSourceIndex||!e.linkTargetIndex)return[];const r=n.getChild(e.linkSourceIndex),t=n.getChild(e.linkTargetIndex),i=n.numRows,l=new Array(2*i);for(let n=0,e=0;n<i;n++,e+=2)l[e]=null==r?void 0:r.get(n),l[e+1]=null==t?void 0:t.get(n);return l},r=(n,e)=>{var r,t;if(!e.linkSourceIndex||!e.linkTargetIndex)return new Set;const i=null===(r=n.getChild(e.linkSourceIndex))||void 0===r?void 0:r.toArray(),l=null===(t=n.getChild(e.linkTargetIndex))||void 0===t?void 0:t.toArray();return new Set([...i,...l])},t=async(n,e,r,t,i)=>{var l,o,d,u;const a=i.map((n=>"string"==typeof n?`'${n}'`:n)),$=`SELECT "${r.linkSourceIndex}", "${r.linkTargetIndex}" FROM ${e} WHERE "${t}" IN (${a.join(", ")})`,c=await n.query($);if(!c)return;const v=null!==(o=null===(l=c.getChildAt(0))||void 0===l?void 0:l.toArray())&&void 0!==o?o:[],I=null!==(u=null===(d=c.getChildAt(1))||void 0===d?void 0:d.toArray())&&void 0!==u?u:[];return[...new Set([...v,...I])]},i=async(n,e,r,t)=>{const i=t.map((n=>`'${n}'`)).join(", ");return await n.query(`SELECT * FROM ${e} WHERE "${r.linkSource}" IN (${i}) OR "${r.linkTarget}" IN (${i})`)},l=async(n,e,r,t)=>{const i=t.join(", ");return await n.query(`SELECT * FROM ${e} WHERE "${r.linkSourceIndex}" IN (${i}) OR "${r.linkTargetIndex}" IN (${i})`)};export{n as getAllLinks,i as getLinksByPointIds,l as getLinksByPointIndices,t as getPointIndicesByLinksColumnValues,r as getPointIndicesFromLinks,e as mergeLinkPositions};
//# sourceMappingURL=links.js.map

@@ -1,4 +0,2 @@

import { Table, DataType } from 'apache-arrow';
import { MosaicDBCoordinator } from '../../../duckdb/mosaic-coordinator';
import { AccessorFunction } from './vectors';
export declare const summarize: (db: MosaicDBCoordinator, tableName: string) => Promise<Record<string, unknown>[]>;

@@ -8,15 +6,2 @@ export declare const getColumnNames: (db: MosaicDBCoordinator, tableName: string) => Promise<string[]>;

export declare const isTableExists: (db: MosaicDBCoordinator, tableName: string) => Promise<boolean>;
/**
* Converts an Apache Arrow row to a human-readable object by accessor value.
* @param table - The Apache Arrow table.
* @param accessor - The accessor function to identify the row.
* @returns The human-readable object representing the row, or null if not found.
*/
export declare const getRowByAccessor: (table: Table, accessor: AccessorFunction<DataType, boolean>) => Record<string, any> | null;
/**
* Filters rows from an Apache Arrow table based on an accessor function.
* @param table - The Apache Arrow table.
* @param condition - The accessor function to identify the rows to be filtered.
* @returns An array of human-readable objects representing the filtered rows.
*/
export declare const filterRowsByCondition: (table: Table, condition: AccessorFunction<DataType, boolean>) => Record<string, any>[];
export declare const filterCosmosArray: (indices: number[], arr: number[], stride?: number) => number[];

@@ -1,2 +0,2 @@

import{convertArrowToObject as n}from"../../../utils/utils.js";const t=async(t,a)=>{const r=await t.query(`SUMMARIZE ${a}`);return n(r)},a=async(n,t)=>{const a=await n.query(`PRAGMA table_info(${t})`);return a?a.toArray().map((n=>n.name)):[]},r=async(n,t,a,r)=>{const e=await n.query(`PRAGMA table_info(${t})`);if(!e)return null==r||r.push(...a),!1;const s=new Set(e.toArray().map((n=>n.name))),i=a.filter((n=>!s.has(n)));return null==r||r.push(...i),0===i.length},e=async(t,a)=>{const r=await t.query("SHOW ALL TABLES"),[e,s]=a.includes(".")?a.split("."):["main",a];return void 0!==n(r).find((n=>n.name===s&&n.schema===e))};export{r as checkColumnsExist,a as getColumnNames,e as isTableExists,t as summarize};
import{convertArrowToObject as t}from"../../../utils/utils.js";const n=async(n,e)=>{const a=await n.query(`SUMMARIZE ${e}`);return t(a)},e=async(t,n)=>{const e=await t.query(`PRAGMA table_info(${n})`);return e?e.toArray().map((t=>t.name)):[]},a=async(t,n,e,a)=>{const r=await t.query(`PRAGMA table_info(${n})`);if(!r)return null==a||a.push(...e),!1;const s=new Set(r.toArray().map((t=>t.name))),u=e.filter((t=>!s.has(t)));return null==a||a.push(...u),0===u.length},r=async(n,e)=>{const a=await n.query("SHOW ALL TABLES"),[r,s]=e.includes(".")?e.split("."):["main",e];return void 0!==t(a).find((t=>t.name===s&&t.schema===r))},s=(t,n,e=4)=>{const a=new Set(t),r=[];for(let t=0;t<n.length;t+=e)a.has(t/e)||r.push(...n.slice(t,t+e));return r};export{a as checkColumnsExist,s as filterCosmosArray,e as getColumnNames,r as isTableExists,n as summarize};
//# sourceMappingURL=misc.js.map

@@ -6,3 +6,3 @@ import { Table } from 'apache-arrow';

export declare const havePointsLayout: (db: MosaicDBCoordinator, tableName: string, config: CosmographConfig) => Promise<boolean>;
export declare const mergePointsPositions: (points: Table, config: CosmographConfig) => number[];
export declare const getPointPositionsFromTable: (points: Table, config: CosmographConfig) => number[];
export declare const getPointPositionsExtent: (db: MosaicDBCoordinator, tableName: string, config: CosmographConfig) => Promise<Table>;

@@ -12,3 +12,3 @@ export declare const getPointsByIndices: (db: MosaicDBCoordinator, tableName: string, idxColumn: string, indices: number[]) => Promise<Table>;

export declare const getPointIdsByIndices: (db: MosaicDBCoordinator, tableName: string, config: CosmographConfig, indices: number[]) => Promise<string[] | undefined>;
export declare const getPointIndiciesByColumnValues: (db: MosaicDBCoordinator, tableName: string, config: CosmographConfig, key: string, values: (number | string)[]) => Promise<number[] | undefined>;
export declare const getPointIndicesByColumnValues: (db: MosaicDBCoordinator, tableName: string, config: CosmographConfig, key: string, values: (number | string)[]) => Promise<number[] | undefined>;
export declare const getRandomPointPositions: (pointsCount: number, spaceSize?: number, mu?: number, sigma?: number) => number[];

@@ -1,2 +0,2 @@

import{getColumnNames as n}from"./misc.js";const t=async(n,t,o)=>{var i;return await n.query(`SELECT ${null!==(i=null==o?void 0:o.join(", "))&&void 0!==i?i:"*"} FROM ${t}`)},o=async(t,o,i)=>{if(!(null==i?void 0:i.pointX)||!(null==i?void 0:i.pointY))return!1;const r=await n(t,o);return r.includes(i.pointX)&&r.includes(i.pointY)},i=(n,t)=>{if(!(null==t?void 0:t.pointX)||!(null==t?void 0:t.pointY))return[];const o=n.getChild(t.pointX),i=n.getChild(t.pointY),r=n.numRows,a=new Array(2*r);for(let n=0;n<r;n++)a[2*n]=null==o?void 0:o.get(n),a[2*n+1]=null==i?void 0:i.get(n);return a},r=async(n,t,o,i)=>{const r=i.join(", ");return await n.query(`SELECT * FROM ${t} WHERE ${o} IN (${r})`)},a=async(n,t,o,i)=>{var r,a;const l=i.map((n=>`'${n}'`)).join(", "),d=`SELECT ${o.pointIndex} FROM ${t} WHERE ${o.pointId} IN (${l})`,e=await n.query(d);return e?null!==(a=null===(r=e.getChildAt(0))||void 0===r?void 0:r.toArray())&&void 0!==a?a:[]:void 0},l=async(n,t,o,i)=>{var r,a;const l=i.join(", "),d=`SELECT ${o.pointId} FROM ${t} WHERE ${o.pointIndex} IN (${l})`,e=await n.query(d);return e?null!==(a=null===(r=e.getChildAt(0))||void 0===r?void 0:r.toArray())&&void 0!==a?a:[]:void 0},d=async(n,t,o,i,r)=>{var a,l;const d=r.map((n=>"string"==typeof n?`'${n}'`:n)),e=`SELECT ${o.pointIndex} FROM ${t} WHERE ${i} IN (${d.join(", ")})`,u=await n.query(e);return u?null!==(l=null===(a=u.getChildAt(0))||void 0===a?void 0:a.toArray())&&void 0!==l?l:[]:void 0},e=(n,t=4096,o=t/2,i=t/8)=>Array.from({length:2*n},(()=>{const n=o+i*Math.sqrt(-2*Math.log(Math.random()))*Math.cos(2*Math.PI*Math.random());return Math.max(1,Math.min(t-1,n))}));export{t as getAllPoints,l as getPointIdsByIndices,a as getPointIndicesByIds,d as getPointIndiciesByColumnValues,r as getPointsByIndices,e as getRandomPointPositions,o as havePointsLayout,i as mergePointsPositions};
import{getColumnNames as n}from"./misc.js";const t=async(n,t,o)=>{var i;return await n.query(`SELECT ${null!==(i=null==o?void 0:o.map((n=>`"${n}"`)).join(", "))&&void 0!==i?i:"*"} FROM ${t}`)},o=async(t,o,i)=>{if(!(null==i?void 0:i.pointX)||!(null==i?void 0:i.pointY))return!1;const r=await n(t,o);return r.includes(i.pointX)&&r.includes(i.pointY)},i=(n,t)=>{if(!(null==t?void 0:t.pointX)||!(null==t?void 0:t.pointY))return[];const o=n.getChild(t.pointX),i=n.getChild(t.pointY),r=n.numRows,a=new Array(2*r);for(let n=0;n<r;n++)a[2*n]=null==o?void 0:o.get(n),a[2*n+1]=null==i?void 0:i.get(n);return a},r=async(n,t,o,i)=>{const r=i.join(", ");return await n.query(`SELECT * FROM ${t} WHERE "${o}" IN (${r})`)},a=async(n,t,o,i)=>{var r,a;const l=i.map((n=>`'${n}'`)).join(", "),d=`SELECT "${o.pointIndex}" FROM ${t} WHERE "${o.pointId}" IN (${l})`,e=await n.query(d);return e?null!==(a=null===(r=e.getChildAt(0))||void 0===r?void 0:r.toArray())&&void 0!==a?a:[]:void 0},l=async(n,t,o,i)=>{var r,a;const l=i.join(", "),d=`SELECT "${o.pointId}" FROM ${t} WHERE "${o.pointIndex}" IN (${l})`,e=await n.query(d);return e?null!==(a=null===(r=e.getChildAt(0))||void 0===r?void 0:r.toArray())&&void 0!==a?a:[]:void 0},d=async(n,t,o,i,r)=>{var a,l;const d=r.map((n=>"string"==typeof n?`'${n}'`:n)),e=`SELECT "${o.pointIndex}" FROM ${t} WHERE "${i}" IN (${d.join(", ")})`,u=await n.query(e);return u?null!==(l=null===(a=u.getChildAt(0))||void 0===a?void 0:a.toArray())&&void 0!==l?l:[]:void 0},e=(n,t=4096,o=t/2,i=t/8)=>Array.from({length:2*n},(()=>{const n=o+i*Math.sqrt(-2*Math.log(Math.random()))*Math.cos(2*Math.PI*Math.random());return Math.max(1,Math.min(t-1,n))}));export{t as getAllPoints,l as getPointIdsByIndices,d as getPointIndicesByColumnValues,a as getPointIndicesByIds,i as getPointPositionsFromTable,r as getPointsByIndices,e as getRandomPointPositions,o as havePointsLayout};
//# sourceMappingURL=points.js.map

@@ -21,8 +21,7 @@ import { Graph } from '@cosmograph/cosmos';

private _cosmos?;
private _dbReadinessPromise;
private _dataReadinessPromise;
private _resolveDataReady;
private _graphReadinessPromise;
private _resolveGraphReady;
private _isDataUploading;
private _dbReadinessPromise;
private _dataUploadPromise;
private _graphReadyPromise;
private _crossfilter;

@@ -56,3 +55,8 @@ private _pointsSelection;

/**
* Waits for the graph to be ready.
* Waits for the database and data to be ready. It also awaits for `dbReady` to be resolved.
* @returns `Promise<void>` A promise that resolves when the data is ready.
*/
dataReady(): Promise<void>;
/**
* Waits for the graph to be ready with actual statistics of rendered items. It also awaits for `dataReady` to be resolved.
* @returns `Promise<void>` A promise that resolves when the graph is ready.

@@ -62,7 +66,2 @@ */

/**
* Waits for the data to be ready.
* @returns `Promise<void>` A promise that resolves when the data is ready.
*/
dataReady(): Promise<void>;
/**
* Gets the name of the links table.

@@ -170,8 +169,9 @@ * @returns `string` The name of the links table.

/**
* Adds a set of points to the current graph.
* Adds a set of points/links to existing graph. Does not work with external instances of DuckDB-Wasm.
*
* @param points - The points to add, represented as CosmographInputData.
* @param links - The points to add, represented as CosmographInputData.
* @returns A Promise that resolves when the points have been added.
*/
addPoints(points: CosmographInputData): Promise<void>;
addData(points?: CosmographInputData, links?: CosmographInputData): Promise<void>;
/**

@@ -181,7 +181,13 @@ * Removes the points specified by the given indices from the current graph.

* @param indices - The indices of the points to remove.
* @param removeAttachedLinks - Whether to also remove any links attached to the removed points. Defaults to `true`.
* @returns A Promise that resolves when the points have been removed.
*/
removePointsByIndices(indices: number[]): Promise<void>;
removePointsByIndices(indices: number[], removeAttachedLinks?: boolean): Promise<void>;
removeLinksByPointIdPairs(pairs: [string, string][]): Promise<void>;
removeLinksByPointIndicesPairs(pairs: [number, number][]): Promise<void>;
private _removeCosmosPoints;
private _removeLinks;
private _triggerDataUpdated;
private _updateStats;
private _setCosmosData;
private _removeCosmosPoints;
private _getDataForProperty;

@@ -350,3 +356,3 @@ private _handlePropertyUpdate;

*/
reset(): Promise<void>;
reset(total?: boolean): Promise<void>;
/**

@@ -374,3 +380,3 @@ * Returns an array of points with their degree values in the order they were sent to Cosmograph.

getPointsByIndices(indices: number[]): Promise<CosmographData | undefined>;
getPointIndiciesByColumnValues(column: string, values: (number | string)[]): Promise<number[] | undefined>;
getPointIndicesByColumnValues(column: string, values: (number | string)[]): Promise<number[] | undefined>;
getPointIndicesByLinksColumnValues(column: string, values: (number | string)[]): Promise<number[] | undefined>;

@@ -377,0 +383,0 @@ /**

@@ -1,2 +0,2 @@

import{Graph as i}from"@cosmograph/cosmos";import{debounce as t}from"throttle-debounce";import{Selection as o}from"@uwdata/mosaic-core";import{merge as s}from"@cosmograph/ui";import{color as n}from"d3-color";import{watermark as e}from"./watermark.js";import{MosaicDBCoordinator as a}from"../../duckdb/mosaic-coordinator.js";import{SelectionClient as r}from"./selection/selection-client.js";import{hexToBrightness as l,isEqual as d,convertArrowToObject as h}from"../../utils/utils.js";import{cosmographLog as c}from"../../utils/log.js";import{defaultCosmographConfig as u}from"./config/config.js";import{Tables as m}from"../../enum.js";import{Labels as _}from"./labels/index.js";import{RectangularSelect as v}from"./area-select/rectangular/index.js";import{getPointIndicesByIds as p,getPointIdsByIndices as g,getAllPoints as f,mergePointsPositions as C,getRandomPointPositions as b,havePointsLayout as k,getPointsByIndices as P,getPointIndiciesByColumnValues as w}from"./data-ops/points.js";import{isTableExists as y,checkColumnsExist as S,summarize as L}from"./data-ops/misc.js";import{getArrows as E,getSizes as D,getColors as T}from"./data-ops/vectors.js";import{getPointIndicesFromLinks as R,getAllLinks as B,mergeLinkPositions as M,getPointIndicesByLinksColumnValues as N,getLinksByPointIds as $,getLinksByPointIndices as I}from"./data-ops/links.js";import{requiredPointsConfigKeys as F,requiredLinksConfigKeys as U,unrequiredProps as z,BasePointsConfigKeys as x,BaseLinksConfigKeys as q}from"./config/data.js";import{labelsUpdateKeys as j}from"./config/labels.js";import O from"./style.module.css.js";class A extends EventTarget{constructor(i,t,s){var e;super(),this._stats={pointsCount:0,linksCount:0,pointsSummary:void 0,linksSummary:void 0},this._cosmographConfig={},this._cosmosConfig={},this._svgParser=new DOMParser,this._isDataUploading=!1,this._crossfilter={links:new Set,points:new Set,intersection:new Set},this._pointsSelection=o.crossfilter(),this._linksSelection=o.crossfilter(),this._initializeClients=()=>{var i;this._selectionClient=new r(this,this._pointsSelection,this._onPointsFiltered),null===(i=this._dbCoordinator)||void 0===i||i.connect(this._selectionClient)},this._handleCrossfiltering=(i,t)=>{var o,s,n,e,a,r;this._getSetForCrossfilter(i,t),this._getIntersection(),this.isFilteringActive?null===(o=this._cosmos)||void 0===o||o.selectPointsByIndices(Array.from(this._crossfilter.intersection)):null===(s=this._cosmos)||void 0===s||s.unselectPoints(),"points"===t&&(null===(e=(n=this.config).onPointsFiltered)||void 0===e||e.call(n,i)),"links"===t&&(null===(r=(a=this.config).onLinksFiltered)||void 0===r||r.call(a,i)),this._labels.render(),this.dispatchEvent(new CustomEvent("dataFiltered"))},this._getSetForCrossfilter=(i,t)=>{var o;const s="links"===t?R(i,this.config):new Set(null===(o=i.getChild(this.config.pointIndex))||void 0===o?void 0:o.toArray());this._crossfilter[t]=s},this._controlBackgroundColor=(i,t)=>{var o,s,e,a;const r="#222222";if(t.backgroundColor&&(null==i?void 0:i.backgroundColor)!==t.backgroundColor||!i){let i;if("string"==typeof t.backgroundColor)i=null===(o=n(t.backgroundColor))||void 0===o?void 0:o.formatHex();else if(Array.isArray(t.backgroundColor)){const[o,e,a,r]=t.backgroundColor;i=null===(s=n(`rgba(${o}, ${e}, ${a}, ${r})`))||void 0===s?void 0:s.formatHex()}if(i){const t=l(i)>.65?"#000000":"#ffffff";null===(e=this._containerElement)||void 0===e||e.style.setProperty("--cosmograph-watermark-color",t),this._canvasElement.style.backgroundColor=i}else null===(a=this._containerElement)||void 0===a||a.style.setProperty("--cosmograph-watermark-color","#ffffff"),this._canvasElement.style.backgroundColor=r}else(null==t?void 0:t.backgroundColor)||(this._canvasElement.style.backgroundColor=r)},this._dropLocalTables=async i=>{var t,o;this._dbCoordinator&&(i||await(null===(t=this._dbCoordinator.internalDB)||void 0===t?void 0:t.dropTable(m.Points)),await(null===(o=this._dbCoordinator.internalDB)||void 0===o?void 0:o.dropTable(m.Links)))},this._onClick=(...i)=>{var t,o;null===(o=(t=this.config).onClick)||void 0===o||o.call(t,...i)},this._onLabelClick=async(i,t)=>{var o,s;if(!this._dbCoordinator)return;const n=await p(this._dbCoordinator,this.pointsTableName,this.config,[t.id]);n&&n[0]&&(null===(s=(o=this.config).onLabelClick)||void 0===s||s.call(o,n[0],t.id,i))},this._onHoveredLabelClick=async i=>{var t,o;if(void 0===this._hoveredPointIndex||void 0===this._dbCoordinator)return;const s=await g(this._dbCoordinator,this.pointsTableName,this.config,[this._hoveredPointIndex]);s&&s[0]&&(null===(o=(t=this.config).onLabelClick)||void 0===o||o.call(t,this._hoveredPointIndex,s[0],i))},this._onAreaSelect=i=>{var t,o;this.selectPointsInRect(i),null===(o=(t=this.config).onAreaSelected)||void 0===o||o.call(t,i)},this._onPointMouseOver=(...i)=>{var t,o;null===(o=(t=this.config).onPointMouseOver)||void 0===o||o.call(t,...i);const[s,n]=i;this._hoveredPointIndex=s,this._labels.renderHoveredLabel(s,n)},this._onPointMouseOut=(...i)=>{var t,o;null===(o=(t=this.config).onPointMouseOut)||void 0===o||o.call(t,...i),this._labels.renderHoveredLabel()},this._onMouseMove=(...i)=>{var t,o;null===(o=(t=this.config).onMouseMove)||void 0===o||o.call(t,...i);const[s,n]=i;this._labels.renderHoveredLabel(s,n)},this._onZoomStart=(...i)=>{var t,o;null===(o=(t=this.config).onZoomStart)||void 0===o||o.call(t,...i)},this._onZoom=async(...i)=>{var t,o;null===(o=(t=this.config).onZoom)||void 0===o||o.call(t,...i),this._labels.render(),this._labels.renderHoveredLabel(),this.dispatchEvent(new CustomEvent("pointSizeScaleUpdated")),this.dispatchEvent(new CustomEvent("linkWidthScaleUpdated"))},this._onZoomEnd=(...i)=>{var t,o;null===(o=(t=this.config).onZoomEnd)||void 0===o||o.call(t,...i)},this._onStart=(...i)=>{var t,o;null===(o=(t=this.config).onSimulationStart)||void 0===o||o.call(t,...i)},this._onTick=(...i)=>{var t,o;null===(o=(t=this.config).onSimulationTick)||void 0===o||o.call(t,...i),this._labels.render()},this._onEnd=(...i)=>{var t,o;null===(o=(t=this.config).onSimulationEnd)||void 0===o||o.call(t,...i)},this._onPause=(...i)=>{var t,o;null===(o=(t=this.config).onSimulationPause)||void 0===o||o.call(t,...i)},this._onRestart=(...i)=>{var t,o;null===(o=(t=this.config).onSimulationRestart)||void 0===o||o.call(t,...i)},c("Initialization..."),this._dataReadinessPromise=new Promise((i=>{this._resolveDataReady=i})),this._graphReadinessPromise=new Promise((i=>{this._resolveGraphReady=i})),this._dbReadinessPromise=a.create(s).then((i=>{this._dbCoordinator=i,i?(this._initializeFilters(),this._initializeClients(),this._messageDivElement.innerText="👩🏻‍🚀 Cosmograph is ready, load your data!"):this._messageDivElement.innerText=s?"🚨 Couldn't create coordinator for specified duckDB connection. Please check your external duckDB instance configuration and try to initialize Cosmograph again.":"🚨 Failed to fetch DuckDB-Wasm bundles. Please try to initialize Cosmograph again."})),this._disableSimulation=null!==(e=t.disableSimulation)&&void 0!==e?e:null,this._containerElement=i,this._containerElement.classList.add(O.cosmograph),this._initializeHTMLElements(),this._controlBackgroundColor(void 0,t),this.setConfig(t),this._labels=new _(this,this._containerElement,this._canvasElement,{onLabelClick:this._onLabelClick.bind(this),onHoveredLabelClick:this._onHoveredLabelClick.bind(this)}),this._rectSelect=new v(this,this._containerElement,this._onAreaSelect)}_initializeHTMLElements(){this._canvasElement=document.createElement("canvas"),this._canvasElement.style.width="100%",this._canvasElement.style.height="100%",this._containerElement.appendChild(this._canvasElement),this._addWatermark(),this._addMessageElement()}_addWatermark(){var i;this._watermarkDivElement=document.createElement("div"),this._watermarkDivElement.classList.add(O.watermark),this._watermarkDivElement.onclick=()=>{var i;return null===(i=window.open("https://cosmograph.app/","_blank"))||void 0===i?void 0:i.focus()};const t=this._svgParser.parseFromString(e,"image/svg+xml").firstChild;null===(i=this._watermarkDivElement)||void 0===i||i.appendChild(t),this._containerElement.appendChild(this._watermarkDivElement)}_addMessageElement(){this._messageDivElement=document.createElement("div"),this._messageDivElement.classList.add(O.message),this._messageDivElement.innerText="🚀 Initializing Cosmograph...",this._containerElement.appendChild(this._messageDivElement)}_updateMessage(i,t=!1){this._messageDivElement&&(null===i?this._messageDivElement.style.display="none":(this._messageDivElement.style.display="block",this._messageDivElement.innerText=i),this._isDataUploading=t)}_initializeFilters(){this._onLinksFiltered=t(10,(i=>this._handleCrossfiltering(i,"links"))),this._onPointsFiltered=t(10,(i=>this._handleCrossfiltering(i,"points")))}async _initializeCosmos(){this._cosmos?this._disableSimulation!==this._cosmos.config.disableSimulation&&c(`The \`disableSimulation\` was initialized to \`${this._cosmos.config.disableSimulation}\` during initialization and will not be modified.`,"initializeCosmos","info"):this._cosmos=new i(this._canvasElement,this._cosmosConfig)}async dbReady(){return await this._dbReadinessPromise}async graphReady(){return this._graphReadinessPromise}async dataReady(){return this._dataReadinessPromise}get linksTableName(){var i;return(null===(i=this.dbCoordinator)||void 0===i?void 0:i.internalDB)||"string"!=typeof this.config.links?m.Links:this.config.links}get pointsTableName(){var i;return(null===(i=this.dbCoordinator)||void 0===i?void 0:i.internalDB)||"string"!=typeof this.config.points?m.Points:this.config.points}get config(){return this._cosmographConfig}get stats(){return this._stats}get isFilteringActive(){return this._linksSelection.clauses.length||this._pointsSelection.clauses.length}get dbCoordinator(){return this._dbCoordinator}get selectionClient(){return this._selectionClient}get crossfilter(){return this._crossfilter}get pointsSelection(){return this._pointsSelection}get linksSelection(){return this._linksSelection}get onLinksFiltered(){return this._onLinksFiltered}get onPointsFiltered(){return this._onPointsFiltered}get cosmos(){return this._cosmos}get progress(){var i;return null===(i=this._cosmos)||void 0===i?void 0:i.progress}get isSimulationRunning(){var i;return null===(i=this._cosmos)||void 0===i?void 0:i.isSimulationRunning}get maxPointSize(){var i;return null===(i=this._cosmos)||void 0===i?void 0:i.maxPointSize}async setConfig(i){var t;const o=this.config;this._cosmographConfig=s(u,null!=i?i:{}),i&&void 0===i.points&&void 0===o.points||(i&&void 0===i.points&&void 0!==o.points?this.reset():(this._cosmosConfig=this._createCosmosConfig(this.config),this._checkScalesChanged(o,this.config),null===(t=this._cosmos)||void 0===t||t.setConfig(this._cosmosConfig),this._controlBackgroundColor(o,this.config),await this._controlData(o,this.config),this._rectSelect.updateSelectionClassName()))}_checkScalesChanged(i,t){var o;i.pointSizeScale!==t.pointSizeScale&&(null===(o=this._labels)||void 0===o||o.render(),this.dispatchEvent(new CustomEvent("pointSizeScaleUpdated"))),i.linkWidthScale!==t.linkWidthScale&&this.dispatchEvent(new CustomEvent("linkWidthScaleUpdated"))}_hasConfigChanged(i,t,o){return o.some((o=>!d(i[o],t[o])))}async _controlData(i,t){var o,s,n,e;if(await this._dbReadinessPromise,!this._dbCoordinator)return void c("No MosaicDBCoordinator instance found.","_controlData","warn");let a=!0,r=!0;const l=this._hasConfigChanged(i,t,F),d=this._hasConfigChanged(i,t,U);if(l||d){if(this.isSimulationRunning&&this.pause(),null===(o=this._cosmos)||void 0===o||o.unselectPoints(),this._crossfilter.intersection=new Set,this._dbCoordinator.clearCache(),l||0===this.stats.pointsCount){this._clearCosmosBuffers();const{pointsOk:i,linksOk:o}=await this._updateRequiredProps(t);a=o,r=i,i?await this._createAndPrepareGraph(a,void 0,t):null===(s=this.cosmos)||void 0===s||s.render()}else this._clearCosmosBuffers(!0),a=await this._updateRequiredLinkProps(t,(null==i?void 0:i.links)!==t.links),a||await this._dropLocalTables(!0),await this._createAndPrepareGraph(a,i,t);this._dbCoordinator.internalDB||null===(n=this._resolveDataReady)||void 0===n||n.call(this)}else this.stats.pointsCount&&this._hasConfigChanged(i,t,z)&&(await this._updateUnrequiredPointProps(i,t),a&&await this._updateUnrequiredLinkProps(i,t),null===(e=this.cosmos)||void 0===e||e.render());if(r){(this.stats.pointsCount&&this._hasConfigChanged(i,t,j)||l)&&this._labels.update()}else this._labels.clear()}async _updateRequiredProps(i){var t;if(!this._dbCoordinator)return{pointsOk:!1,linksOk:!1};if(!i.points){this._dropLocalTables();const i="Points source data is not provided in `points`.";return c(i,"_updateRequiredProps","error"),this._updateMessage(`🚨 ${i}`),{pointsOk:!1,linksOk:!1}}(null===(t=this._dbCoordinator)||void 0===t?void 0:t.internalDB)?await this._uploadData(i.points,i.links):this._updateMessage(null);const o=await this._checkUpdatedRequiredPointsProps(i);if(!o)return this._dropLocalTables(),{pointsOk:!1,linksOk:!1};const s=await this._updateRequiredLinkProps(i);return this.dispatchEvent(new CustomEvent("dataUpdated")),{pointsOk:o,linksOk:s}}async _checkUpdatedRequiredPointsProps(i){if(!this._dbCoordinator)return!1;if(!await y(this._dbCoordinator,this.pointsTableName)){const i=`Failed to get points data. Table "${this.pointsTableName}" does not exist`;return c(i,"_checkUpdatedRequiredPointsProps","error"),this._updateMessage(`🚨 ${i}`),!1}const t=F.slice(1),o=t.filter((t=>void 0===i[t]));if(o.length>0){const i=`Failed to get points data. \n\nMissing required properties: ${o.map((i=>`"${i}"`)).join(", ")}.`;return c(i,"_checkUpdatedRequiredPointsProps","error"),this._updateMessage(`🚨 ${i}`),!1}const s=t.map((t=>i[t])),n=[];if(!await S(this._dbCoordinator,this.pointsTableName,s,n)){const i=`Failed to get points data. \n\nMissing provided columns for required properties: ${n.map((i=>`"${i}" (${t[n.indexOf(i)]})`)).join(", ")}.`;return c(i,"_checkUpdatedRequiredPointsProps","error"),this._updateMessage(`🚨 ${i}`),!1}return!0}async _updateRequiredLinkProps(i,t){var o;if(!this._dbCoordinator)return!1;if(!i.links)return await this._dropLocalTables(!0),!1;t&&((null===(o=this._dbCoordinator)||void 0===o?void 0:o.internalDB)?await this._uploadData(void 0,i.links):this._updateMessage(null));if(!await y(this._dbCoordinator,this.linksTableName)){const i=`Failed to get links data. Table "${this.linksTableName}" does not exist`;return c(i,"_updateRequiredLinkProps","error"),this._updateMessage(`🚨 ${i}`),!1}const s=U.slice(1),n=s.filter((t=>void 0===i[t]));if(n.length>0)return c(`Failed to get links data, only points will be rendered. \n\nMissing required properties: ${n.map((i=>`"${i}"`)).join(", ")}.`,"_updateRequiredLinkProps","warn"),!1;const e=s.map((t=>i[t])),a=[],r=await S(this._dbCoordinator,this.linksTableName,e,a);return r||c(`Failed to get links data, only points will be rendered.\n\n Missing provided columns for required properties: ${a.map((i=>`"${i}" (${s[a.indexOf(i)]})`)).join(", ")}.`,"_updateRequiredLinkProps","warn"),r}async _updateUnrequiredProps(i,t,o,s,n,e,a){if(!this._dbCoordinator)return;const r=async()=>{a||(a=await n(this._dbCoordinator,s))};for(const[s,n]of Object.entries(e))i&&(null==i?void 0:i[s])===t[s]&&(null==i?void 0:i[n])===t[n]||(await r(),await this._handlePropertyUpdate(t,s,n,o,a))}async _updateUnrequiredPointProps(i,t){if(!this._dbCoordinator)return;let o;const s={pointColor:x.PointColorFn,pointSize:x.PointSizeFn};i&&this.stats.pointsCount&&(null==i?void 0:i.pointX)===t.pointX&&(null==i?void 0:i.pointY)===t.pointY||(o=await f(this._dbCoordinator,this.pointsTableName),await this._handlePointPositions(o)),await this._updateUnrequiredProps(i,t,!1,this.pointsTableName,f,s,o)}async _updateUnrequiredLinkProps(i,t){const o={linkColor:q.LinkColorFn,linkWidth:q.LinkWidthFn,linkArrow:q.LinkArrowFn,linkStrength:q.LinkStrengthFn};await this._updateUnrequiredProps(i,t,!0,this.linksTableName,B,o,undefined)}async addPoints(i){var t,o,s,n,e,a,r,l,d,h,c;this._dbCoordinator&&(null===(t=this._dbCoordinator)||void 0===t?void 0:t.internalDB)&&(await this._dbCoordinator.internalDB.uploadData(i,m.Points,!0),await this._updateUnrequiredPointProps(void 0,this.config),null===(o=this.cosmos)||void 0===o||o.render(),this._stats={pointsCount:null!==(n=null===(s=this._cosmos)||void 0===s?void 0:s.graph.pointsNumber)&&void 0!==n?n:0,linksCount:null!==(r=null===(a=null===(e=this._cosmos)||void 0===e?void 0:e.graph)||void 0===a?void 0:a.linksNumber)&&void 0!==r?r:0,pointsSummary:await this.getPointsSummary(),linksSummary:(null===(d=null===(l=this._cosmos)||void 0===l?void 0:l.graph)||void 0===d?void 0:d.linksNumber)?await this.getLinksSummary():void 0},this._dbCoordinator.clearCache(),this.dispatchEvent(new CustomEvent("dataUpdated")),null===(c=null===(h=this.config)||void 0===h?void 0:h.onDataUpdated)||void 0===c||c.call(h,this._stats))}async removePointsByIndices(i){var t,o,s,n,e,a,r,l,d,h,c;this._dbCoordinator&&(null===(t=this._dbCoordinator)||void 0===t?void 0:t.internalDB)&&(await this._dbCoordinator.internalDB.query(`DELETE FROM ${this.pointsTableName} WHERE ${this.config.pointIndex} IN (${i.join(", ")})`),this._removeCosmosPoints(i),null===(o=this.cosmos)||void 0===o||o.render(),this._stats={pointsCount:null!==(n=null===(s=this._cosmos)||void 0===s?void 0:s.graph.pointsNumber)&&void 0!==n?n:0,linksCount:null!==(r=null===(a=null===(e=this._cosmos)||void 0===e?void 0:e.graph)||void 0===a?void 0:a.linksNumber)&&void 0!==r?r:0,pointsSummary:await this.getPointsSummary(),linksSummary:(null===(d=null===(l=this._cosmos)||void 0===l?void 0:l.graph)||void 0===d?void 0:d.linksNumber)?await this.getLinksSummary():void 0},this._dbCoordinator.clearCache(),this.dispatchEvent(new CustomEvent("dataUpdated")),null===(c=null===(h=this.config)||void 0===h?void 0:h.onDataUpdated)||void 0===c||c.call(h,this._stats))}_setCosmosData(i,t){var o,s,n,e,a,r;switch(i){case x.PointColor:null===(o=this._cosmos)||void 0===o||o.setPointColors(t);break;case x.PointSize:null===(s=this._cosmos)||void 0===s||s.setPointSizes(t);break;case q.LinkColor:null===(n=this._cosmos)||void 0===n||n.setLinkColors(t);break;case q.LinkWidth:null===(e=this._cosmos)||void 0===e||e.setLinkWidths(t);break;case q.LinkArrow:null===(a=this._cosmos)||void 0===a||a.setLinkArrows(t);break;case q.LinkStrength:null===(r=this._cosmos)||void 0===r||r.setLinkStrength(t)}}_removeCosmosPoints(i){var t,o,s,n;if(!i.length)return;const e=null===(t=this.cosmos)||void 0===t?void 0:t.graph.pointPositions,a=[];for(let t=0;t<e.length;t+=2)i.includes(t/2)||a.push(e[t],e[t+1]);null===(o=this.cosmos)||void 0===o||o.setPointPositions(a);const r=null===(s=this.cosmos)||void 0===s?void 0:s.graph.pointColors,l=[];for(let t=0;t<r.length;t+=4)i.includes(t/4)||l.push(r[t],r[t+1],r[t+2],r[t+3]);this._setCosmosData(x.PointColor,l);const d=null===(n=this.cosmos)||void 0===n?void 0:n.graph.pointSizes,h=[];for(let t=0;t<d.length;t+=1)i.includes(t)||h.push(d[t]);this._setCosmosData(x.PointSize,h)}_getDataForProperty(i,t,o,s){switch(o){case x.PointColor:case q.LinkColor:return T(i,t,o,s);case x.PointSize:case q.LinkWidth:case q.LinkStrength:return D(i,t,o,s);case q.LinkArrow:return E(i,t,o,s);default:return[]}}async _handlePropertyUpdate(i,t,o,s,n){if(!this._dbCoordinator)return;const e=i[t],a=s?this.linksTableName:this.pointsTableName;if(!i[t])return i[o]&&c(`\`${o}\` used on \`${t}\`, but \`${t}\` is not provided`,"_handlePropertyUpdate","warn"),void this._setCosmosData(t,[]);const r=await S(this._dbCoordinator,a,[e]),l="function"==typeof i[o]||void 0===i[o];if(!r||!l)return r||c(`Column "${e}" for \`${t}\` not found`,"_handlePropertyUpdate","warn"),l||c(`Provided \`${o}\` is not a function`,"_handlePropertyUpdate","warn"),void this._setCosmosData(t,[]);if(n||(n=s?await B(this._dbCoordinator,a):await f(this._dbCoordinator,a)),null==n?void 0:n.numRows){const s=i[o],a=this._getDataForProperty(n,e,t,s);this._setCosmosData(t,a)}}_clearCosmosBuffers(i){var t,o,s,n,e,a,r,l;i||(null===(t=this.cosmos)||void 0===t||t.setPointPositions([]),null===(o=this.cosmos)||void 0===o||o.setPointColors([]),null===(s=this.cosmos)||void 0===s||s.setPointSizes([])),null===(n=this.cosmos)||void 0===n||n.setLinks([]),null===(e=this.cosmos)||void 0===e||e.setLinkColors([]),null===(a=this.cosmos)||void 0===a||a.setLinkWidths([]),null===(r=this.cosmos)||void 0===r||r.setLinkStrength([]),null===(l=this.cosmos)||void 0===l||l.setLinkArrows([])}async _handlePointPositions(i){var t,o,s;if(!this._dbCoordinator)return;if(!(null==i?void 0:i.numRows))return void(null===(t=this._cosmos)||void 0===t||t.setPointPositions([]));let n;const e=[],a=Boolean(this.config.pointX)!==Boolean(this.config.pointY),r=null===(o=this._cosmos)||void 0===o?void 0:o.getPointPositions();this.config.pointX&&this.config.pointY&&await S(this._dbCoordinator,this.pointsTableName,[this.config.pointX,this.config.pointY],e)?n=C(i,this.config):(null==r?void 0:r.length)?n=r.concat(b(i.numRows-r.length/2,this.config.spaceSize)):(n=b(i.numRows,this.config.spaceSize),a?c(`Only one of \`${x.PointX}\` or \`${x.PointY}\` provided. Random coordinates generated.`,"warn"):this.config.pointX&&this.config.pointY&&c(`Failed to get provided point coordinates. Random coordinates generated.\nMissing provided columns for coordinates: ${e.join(", ")}.`,"warn")),this._labels.render(),null===(s=this._cosmos)||void 0===s||s.setPointPositions(n)}async _uploadData(i,t){var o,s;try{if(await this._dbReadinessPromise,null===(o=this._dbCoordinator)||void 0===o?void 0:o.internalDB){if(c("Data uploading...","uploadData"),this._isDataUploading)return void c("Already uploading data, skipping this call.","uploadData","warn");this._updateMessage("🌀 Loading data...",!0),i&&await this._dbCoordinator.internalDB.uploadData(i,m.Points),t&&await this._dbCoordinator.internalDB.uploadData(t,m.Links),null===(s=this._resolveDataReady)||void 0===s||s.call(this)}}finally{this._updateMessage(null)}}async _createAndPrepareGraph(i,t,o){var s,n,e,a,r,l,d,h,u,m,_,v;try{if(await this._dbReadinessPromise,!this._dbCoordinator)return;if(this.config.points){const i=await k(this._dbCoordinator,this.pointsTableName,o);null===this._disableSimulation&&(this._disableSimulation=!this.config.links||i),this._cosmosConfig.disableSimulation=this._disableSimulation,await this._initializeCosmos(),await this._updateUnrequiredPointProps(t,o)}let p;if(i&&(p=await B(this._dbCoordinator,this.linksTableName),null==p?void 0:p.numRows)){const i=M(p,this.config);null===(s=this._cosmos)||void 0===s||s.setLinks(i),await this._updateUnrequiredLinkProps(void 0,o)}this.config.points&&(null===(n=this.cosmos)||void 0===n||n.render()),this._stats={pointsCount:null!==(a=null===(e=this._cosmos)||void 0===e?void 0:e.graph.pointsNumber)&&void 0!==a?a:0,linksCount:null!==(d=null===(l=null===(r=this._cosmos)||void 0===r?void 0:r.graph)||void 0===l?void 0:l.linksNumber)&&void 0!==d?d:0,pointsSummary:await this.getPointsSummary(),linksSummary:(null===(u=null===(h=this._cosmos)||void 0===h?void 0:h.graph)||void 0===u?void 0:u.linksNumber)?await this.getLinksSummary():void 0},this.config.points?c(`Rendered graph with ${this._stats.pointsCount} points and ${this._stats.linksCount} links.`):(c(`Loaded ${null==p?void 0:p.numRows} links into graph, waiting for points to be loaded.`),this._updateMessage(`🔗 Loaded ${null==p?void 0:p.numRows} links. Upload points to complete the graph.`)),null===(m=this._resolveGraphReady)||void 0===m||m.call(this),null===(v=null===(_=this.config)||void 0===_?void 0:_.onDataUpdated)||void 0===v||v.call(_,this._stats)}catch(i){c(i,"_createAndPrepareGraph","error"),this._updateMessage(`🚨 ${i}`)}}_getIntersection(){const{links:i,points:t}=this._crossfilter,o=t.values();let s=new Set;if(this._linksSelection.clauses.length&&this._pointsSelection.clauses.length)for(const t of o)i.has(t)&&s.add(t);else s=this._linksSelection.clauses.length?i:t;this._crossfilter.intersection=s}activateRectSelection(){this._rectSelect.enable()}deactivateRectSelection(){this._rectSelect.disable()}selectPointsInRect(i){if(!this._cosmos||!i)return;const t=this._cosmos.getPointsInRange(i);this.selectPoints(Array.from(t))}selectPoints(i){var t,o;i&&i.length?null===(t=this._selectionClient)||void 0===t||t.publish(i):null===(o=this._selectionClient)||void 0===o||o.publish(void 0)}selectPoint(i,t=!1){var o,s;if(this._cosmos)if(void 0!==i){let s=[i];t&&(s=s.concat(this._cosmos.getAdjacentIndices(i))),null===(o=this._selectionClient)||void 0===o||o.publish(s)}else null===(s=this._selectionClient)||void 0===s||s.publish(void 0)}unselectPoints(){var i;this._cosmos&&(null===(i=this._selectionClient)||void 0===i||i.publish(void 0))}getSelectedPointIndices(){var i;return null===(i=this._cosmos)||void 0===i?void 0:i.getSelectedIndices()}setZoomLevel(i,t=0){var o;null===(o=this._cosmos)||void 0===o||o.setZoomLevel(i,t)}getZoomLevel(){var i;return null===(i=this._cosmos)||void 0===i?void 0:i.getZoomLevel()}zoomToPoint(i,t,o,s){var n;null===(n=this._cosmos)||void 0===n||n.zoomToPointByIndex(i,t,o,s)}getPointPositions(){var i;return null===(i=this._cosmos)||void 0===i?void 0:i.getPointPositions()}fitView(i=250,t=.1){var o;null===(o=this._cosmos)||void 0===o||o.fitView(i,t)}fitViewByIndices(i,t=250,o){var s;null===(s=this._cosmos)||void 0===s||s.fitViewByPointIndices(i,t,o)}fitViewByCoordinates(i,t=250,o){var s;null===(s=this._cosmos)||void 0===s||s.fitViewByPointPositions(i,t,o)}focusPoint(i){var t;null===(t=this._cosmos)||void 0===t||t.setFocusedPointByIndex(i)}getAdjacentPointIndices(i){var t;return null===(t=this._cosmos)||void 0===t?void 0:t.getAdjacentIndices(i)}spaceToScreenPosition(i){var t;return null===(t=this._cosmos)||void 0===t?void 0:t.spaceToScreenPosition(i)}screenToSpacePosition(i){var t;return null===(t=this._cosmos)||void 0===t?void 0:t.spaceToScreenPosition(i)}spaceToScreenRadius(i){var t;return null===(t=this._cosmos)||void 0===t?void 0:t.spaceToScreenRadius(i)}getPointRadiusByIndex(i){var t;return null===(t=this._cosmos)||void 0===t?void 0:t.getPointRadiusByIndex(i)}getSampledPointPositionsMap(){var i;return null===(i=this._cosmos)||void 0===i?void 0:i.getSampledPointPositionsMap()}start(i=1){var t;null===(t=this._cosmos)||void 0===t||t.start(i)}pause(){var i;null===(i=this._cosmos)||void 0===i||i.pause()}restart(){var i;null===(i=this._cosmos)||void 0===i||i.restart()}step(){var i;null===(i=this._cosmos)||void 0===i||i.step()}async destroy(){var i,t;null===(i=this._cosmos)||void 0===i||i.destroy(),await this._dropLocalTables(),await(null===(t=this.dbCoordinator)||void 0===t?void 0:t.destroy()),this._containerElement.innerHTML="",this._labels.isDestroyed||this._labels.destroy()}create(){var i;null===(i=this._cosmos)||void 0===i||i.create()}async reset(){var i,t;this._labels.destroy(),null===(i=this._cosmos)||void 0===i||i.destroy(),this._cosmographConfig=u,await this._dropLocalTables(),null===(t=this._dbCoordinator)||void 0===t||t.clearCache(),this.dispatchEvent(new CustomEvent("dataUpdated")),this._messageDivElement.innerText="👩🏻‍🚀 Cosmograph is ready, load your data!",this._messageDivElement.style.display="block"}getPointDegrees(){var i;return null===(i=this._cosmos)||void 0===i?void 0:i.graph.degree}async getPointIndicesByIds(i){if(this._dbCoordinator&&this.stats.pointsCount)return await p(this._dbCoordinator,this.pointsTableName,this.config,i)}async getPointIdsByIndices(i){if(this._dbCoordinator&&this.stats.pointsCount)return await g(this._dbCoordinator,this.pointsTableName,this.config,i)}async getPointsByIndices(i){if(this._dbCoordinator&&this.stats.pointsCount)return await P(this._dbCoordinator,this.pointsTableName,this.config.pointIndex,i)}async getPointIndiciesByColumnValues(i,t){if(this._dbCoordinator&&this.stats.pointsCount)return await w(this._dbCoordinator,this.pointsTableName,this.config,i,t)}async getPointIndicesByLinksColumnValues(i,t){if(this._dbCoordinator&&this.stats.linksCount)return await N(this._dbCoordinator,this.linksTableName,this.config,i,t)}async getLinksByPointIds(i){if(this._dbCoordinator&&this.stats.linksCount)return await $(this._dbCoordinator,this.pointsTableName,this.config,i)}async getLinksByPointIndices(i){if(this._dbCoordinator&&this.stats.linksCount)return await I(this._dbCoordinator,this.pointsTableName,this.config,i)}convertCosmographDataToObject(i){return h(i)}flattenPositions(i){var t;return null===(t=this._cosmos)||void 0===t?void 0:t.flatten(i)}pair(i){var t;return null===(t=this._cosmos)||void 0===t?void 0:t.pair(i)}async getPointsSummary(){if(this._dbCoordinator)return await L(this._dbCoordinator,this.pointsTableName)}async getLinksSummary(){if(this._dbCoordinator)return await L(this._dbCoordinator,this.linksTableName)}_createCosmosConfig(i){const t={...i,simulation:{...Object.keys(null!=i?i:{}).filter((i=>-1!==i.indexOf("simulation"))).reduce(((t,o)=>{const s=o.replace("simulation","");return t[s.charAt(0).toLowerCase()+s.slice(1)]=null==i?void 0:i[o],t}),{}),onStart:this._onStart.bind(this),onTick:this._onTick.bind(this),onEnd:this._onEnd.bind(this),onPause:this._onPause.bind(this),onRestart:this._onRestart.bind(this)},events:{onClick:this._onClick.bind(this),onPointMouseOver:this._onPointMouseOver.bind(this),onPointMouseOut:this._onPointMouseOut.bind(this),onMouseMove:this._onMouseMove.bind(this),onZoomStart:this._onZoomStart.bind(this),onZoom:this._onZoom.bind(this),onZoomEnd:this._onZoomEnd.bind(this)}};return delete t.disableSimulation,t}}export{A as Cosmograph};
import{Graph as i}from"@cosmograph/cosmos";import{debounce as t}from"throttle-debounce";import{Selection as o}from"@uwdata/mosaic-core";import{merge as s}from"@cosmograph/ui";import{color as n}from"d3-color";import{watermark as e}from"./watermark.js";import{MosaicDBCoordinator as a}from"../../duckdb/mosaic-coordinator.js";import{SelectionClient as r}from"./selection/selection-client.js";import{hexToBrightness as l,isEqual as d,convertArrowToObject as h}from"../../utils/utils.js";import{cosmographLog as c}from"../../utils/log.js";import{defaultCosmographConfig as u}from"./config/config.js";import{Tables as _}from"../../enum.js";import{Labels as m}from"./labels/index.js";import{RectangularSelect as p}from"./area-select/rectangular/index.js";import{getPointIndicesByIds as v,getPointIdsByIndices as g,getAllPoints as f,getPointPositionsFromTable as C,getRandomPointPositions as b,havePointsLayout as k,getPointsByIndices as P,getPointIndicesByColumnValues as w}from"./data-ops/points.js";import{isTableExists as y,checkColumnsExist as S,filterCosmosArray as E,summarize as L}from"./data-ops/misc.js";import{getArrows as D,getSizes as R,getColors as T}from"./data-ops/vectors.js";import{getPointIndicesFromLinks as $,getAllLinks as B,mergeLinkPositions as U,getPointIndicesByLinksColumnValues as I,getLinksByPointIds as M,getLinksByPointIndices as N}from"./data-ops/links.js";import{requiredPointsConfigKeys as F,requiredLinksConfigKeys as q,unrequiredProps as x,BasePointsConfigKeys as z,BaseLinksConfigKeys as O}from"./config/data.js";import{labelsUpdateKeys as j}from"./config/labels.js";import A from"./style.module.css.js";class W extends EventTarget{constructor(i,t,s){var e;super(),this._stats={pointsCount:0,linksCount:0,pointsSummary:void 0,linksSummary:void 0},this._cosmographConfig={},this._cosmosConfig={},this._svgParser=new DOMParser,this._resolveGraphReady=null,this._isDataUploading=!1,this._dataUploadPromise=null,this._graphReadyPromise=null,this._crossfilter={links:new Set,points:new Set,intersection:new Set},this._pointsSelection=o.crossfilter(),this._linksSelection=o.crossfilter(),this._initializeClients=()=>{var i;this._selectionClient=new r(this,this._pointsSelection,this._onPointsFiltered),null===(i=this._dbCoordinator)||void 0===i||i.connect(this._selectionClient)},this._handleCrossfiltering=(i,t)=>{var o,s,n,e,a,r;this._getSetForCrossfilter(i,t),this._getIntersection(),this.isFilteringActive?null===(o=this._cosmos)||void 0===o||o.selectPointsByIndices(Array.from(this._crossfilter.intersection)):null===(s=this._cosmos)||void 0===s||s.unselectPoints(),"points"===t&&(null===(e=(n=this.config).onPointsFiltered)||void 0===e||e.call(n,i)),"links"===t&&(null===(r=(a=this.config).onLinksFiltered)||void 0===r||r.call(a,i)),this._labels.render(),this.dispatchEvent(new CustomEvent("dataFiltered"))},this._getSetForCrossfilter=(i,t)=>{var o;const s="links"===t?$(i,this.config):new Set(null===(o=i.getChild(this.config.pointIndex))||void 0===o?void 0:o.toArray());this._crossfilter[t]=s},this._controlBackgroundColor=(i,t)=>{var o,s,e,a;const r="#222222";if(t.backgroundColor&&(null==i?void 0:i.backgroundColor)!==t.backgroundColor||!i){let i;if("string"==typeof t.backgroundColor)i=null===(o=n(t.backgroundColor))||void 0===o?void 0:o.formatHex();else if(Array.isArray(t.backgroundColor)){const[o,e,a,r]=t.backgroundColor;i=null===(s=n(`rgba(${o}, ${e}, ${a}, ${r})`))||void 0===s?void 0:s.formatHex()}if(i){const t=l(i)>.65?"#000000":"#ffffff";null===(e=this._containerElement)||void 0===e||e.style.setProperty("--cosmograph-watermark-color",t),this._canvasElement.style.backgroundColor=i}else null===(a=this._containerElement)||void 0===a||a.style.setProperty("--cosmograph-watermark-color","#ffffff"),this._canvasElement.style.backgroundColor=r}else(null==t?void 0:t.backgroundColor)||(this._canvasElement.style.backgroundColor=r)},this._dropLocalTables=async i=>{var t,o;this._dbCoordinator&&(i||await(null===(t=this._dbCoordinator.internalDB)||void 0===t?void 0:t.dropTable(_.Points)),await(null===(o=this._dbCoordinator.internalDB)||void 0===o?void 0:o.dropTable(_.Links)))},this._onClick=(...i)=>{var t,o;null===(o=(t=this.config).onClick)||void 0===o||o.call(t,...i)},this._onLabelClick=async(i,t)=>{var o,s;if(!this._dbCoordinator)return;const n=await v(this._dbCoordinator,this.pointsTableName,this.config,[t.id]);n&&n[0]&&(null===(s=(o=this.config).onLabelClick)||void 0===s||s.call(o,n[0],t.id,i))},this._onHoveredLabelClick=async i=>{var t,o;if(void 0===this._hoveredPointIndex||void 0===this._dbCoordinator)return;const s=await g(this._dbCoordinator,this.pointsTableName,this.config,[this._hoveredPointIndex]);s&&s[0]&&(null===(o=(t=this.config).onLabelClick)||void 0===o||o.call(t,this._hoveredPointIndex,s[0],i))},this._onAreaSelect=i=>{var t,o;this.selectPointsInRect(i),null===(o=(t=this.config).onAreaSelected)||void 0===o||o.call(t,i)},this._onPointMouseOver=(...i)=>{var t,o;null===(o=(t=this.config).onPointMouseOver)||void 0===o||o.call(t,...i);const[s,n]=i;this._hoveredPointIndex=s,this._labels.renderHoveredLabel(s,n)},this._onPointMouseOut=(...i)=>{var t,o;null===(o=(t=this.config).onPointMouseOut)||void 0===o||o.call(t,...i),this._labels.renderHoveredLabel()},this._onMouseMove=(...i)=>{var t,o;null===(o=(t=this.config).onMouseMove)||void 0===o||o.call(t,...i);const[s,n]=i;this._labels.renderHoveredLabel(s,n)},this._onZoomStart=(...i)=>{var t,o;null===(o=(t=this.config).onZoomStart)||void 0===o||o.call(t,...i)},this._onZoom=async(...i)=>{var t,o;null===(o=(t=this.config).onZoom)||void 0===o||o.call(t,...i),this._labels.render(),this._labels.renderHoveredLabel(),this.dispatchEvent(new CustomEvent("pointSizeScaleUpdated")),this.dispatchEvent(new CustomEvent("linkWidthScaleUpdated"))},this._onZoomEnd=(...i)=>{var t,o;null===(o=(t=this.config).onZoomEnd)||void 0===o||o.call(t,...i)},this._onStart=(...i)=>{var t,o;null===(o=(t=this.config).onSimulationStart)||void 0===o||o.call(t,...i)},this._onTick=(...i)=>{var t,o;null===(o=(t=this.config).onSimulationTick)||void 0===o||o.call(t,...i),this._labels.render()},this._onEnd=(...i)=>{var t,o;null===(o=(t=this.config).onSimulationEnd)||void 0===o||o.call(t,...i)},this._onPause=(...i)=>{var t,o;null===(o=(t=this.config).onSimulationPause)||void 0===o||o.call(t,...i)},this._onRestart=(...i)=>{var t,o;null===(o=(t=this.config).onSimulationRestart)||void 0===o||o.call(t,...i)},c("Initialization..."),this._dbReadinessPromise=a.create(s).then((i=>{this._dbCoordinator=i,i?(this._initializeFilters(),this._initializeClients(),this._messageDivElement.innerText="👩🏻‍🚀 Cosmograph is ready, load your data!"):this._messageDivElement.innerText=s?"🚨 Couldn't create coordinator for specified duckDB connection. Please check your external duckDB instance configuration and try to initialize Cosmograph again.":"🚨 Failed to fetch DuckDB-Wasm bundles. Please try to initialize Cosmograph again."})),this._disableSimulation=null!==(e=t.disableSimulation)&&void 0!==e?e:null,this._containerElement=i,this._containerElement.classList.add(A.cosmograph),this._initializeHTMLElements(),this._controlBackgroundColor(void 0,t),this.setConfig(t),this._labels=new m(this,this._containerElement,this._canvasElement,{onLabelClick:this._onLabelClick.bind(this),onHoveredLabelClick:this._onHoveredLabelClick.bind(this)}),this._rectSelect=new p(this,this._containerElement,this._onAreaSelect)}_initializeHTMLElements(){this._canvasElement=document.createElement("canvas"),this._canvasElement.style.width="100%",this._canvasElement.style.height="100%",this._containerElement.appendChild(this._canvasElement),this._addWatermark(),this._addMessageElement()}_addWatermark(){var i;this._watermarkDivElement=document.createElement("div"),this._watermarkDivElement.classList.add(A.watermark),this._watermarkDivElement.onclick=()=>{var i;return null===(i=window.open("https://cosmograph.app/","_blank"))||void 0===i?void 0:i.focus()};const t=this._svgParser.parseFromString(e,"image/svg+xml").firstChild;null===(i=this._watermarkDivElement)||void 0===i||i.appendChild(t),this._containerElement.appendChild(this._watermarkDivElement)}_addMessageElement(){this._messageDivElement=document.createElement("div"),this._messageDivElement.classList.add(A.message),this._messageDivElement.innerText="🚀 Initializing Cosmograph...",this._containerElement.appendChild(this._messageDivElement)}_updateMessage(i,t=!1){this._messageDivElement&&(null===i?this._messageDivElement.style.display="none":(this._messageDivElement.style.display="block",this._messageDivElement.innerText=i),this._isDataUploading=t)}_initializeFilters(){this._onLinksFiltered=t(10,(i=>this._handleCrossfiltering(i,"links"))),this._onPointsFiltered=t(10,(i=>this._handleCrossfiltering(i,"points")))}async _initializeCosmos(){this._cosmos?this._disableSimulation!==this._cosmos.config.disableSimulation&&c(`The \`disableSimulation\` was initialized to \`${this._cosmos.config.disableSimulation}\` during initialization and will not be modified.`,"initializeCosmos","info"):this._cosmos=new i(this._canvasElement,this._cosmosConfig)}async dbReady(){return await this._dbReadinessPromise}async dataReady(){var i;(null===(i=this.dbCoordinator)||void 0===i?void 0:i.internalDB)&&this._dataUploadPromise&&(await this.dbReady(),await this._dataUploadPromise)}async graphReady(){this._graphReadyPromise&&(await this.dataReady(),await this._graphReadyPromise)}get linksTableName(){var i;return(null===(i=this.dbCoordinator)||void 0===i?void 0:i.internalDB)||"string"!=typeof this.config.links?_.Links:this.config.links}get pointsTableName(){var i;return(null===(i=this.dbCoordinator)||void 0===i?void 0:i.internalDB)||"string"!=typeof this.config.points?_.Points:this.config.points}get config(){return this._cosmographConfig}get stats(){return this._stats}get isFilteringActive(){return this._linksSelection.clauses.length||this._pointsSelection.clauses.length}get dbCoordinator(){return this._dbCoordinator}get selectionClient(){return this._selectionClient}get crossfilter(){return this._crossfilter}get pointsSelection(){return this._pointsSelection}get linksSelection(){return this._linksSelection}get onLinksFiltered(){return this._onLinksFiltered}get onPointsFiltered(){return this._onPointsFiltered}get cosmos(){return this._cosmos}get progress(){var i;return null===(i=this._cosmos)||void 0===i?void 0:i.progress}get isSimulationRunning(){var i;return null===(i=this._cosmos)||void 0===i?void 0:i.isSimulationRunning}get maxPointSize(){var i;return null===(i=this._cosmos)||void 0===i?void 0:i.maxPointSize}async setConfig(i){var t;const o=this.config;this._cosmographConfig=s(u,null!=i?i:{}),i&&void 0===i.points&&void 0===o.points||(i&&void 0===i.points&&void 0!==o.points?this.reset():(this._cosmosConfig=this._createCosmosConfig(this.config),this._checkScalesChanged(o,this.config),null===(t=this._cosmos)||void 0===t||t.setConfig(this._cosmosConfig),this._controlBackgroundColor(o,this.config),await this._controlData(o,this.config),this._rectSelect.updateSelectionClassName()))}_checkScalesChanged(i,t){var o;i.pointSizeScale!==t.pointSizeScale&&(null===(o=this._labels)||void 0===o||o.render(),this.dispatchEvent(new CustomEvent("pointSizeScaleUpdated"))),i.linkWidthScale!==t.linkWidthScale&&this.dispatchEvent(new CustomEvent("linkWidthScaleUpdated"))}_hasConfigChanged(i,t,o){return o.some((o=>!d(i[o],t[o])))}async _controlData(i,t){var o,s,n;if(await this._dbReadinessPromise,!this._dbCoordinator)return void c("No MosaicDBCoordinator instance found.","_controlData","warn");let e=!0,a=!0;const r=this._hasConfigChanged(i,t,F),l=this._hasConfigChanged(i,t,q);if(r||l)if(this._graphReadyPromise=new Promise((i=>{this._resolveGraphReady=i})),this.isSimulationRunning&&this.pause(),null===(o=this._cosmos)||void 0===o||o.unselectPoints(),this._crossfilter.intersection=new Set,this._dbCoordinator.clearCache(),r||0===this.stats.pointsCount){this._clearCosmosBuffers();const{pointsOk:i,linksOk:o}=await this._updateRequiredProps(t);e=o,a=i,i?await this._createAndPrepareGraph(e,void 0,t):null===(s=this.cosmos)||void 0===s||s.render()}else{if(0===this.stats.pointsCount)return;this._clearCosmosBuffers(!0),e=await this._updateRequiredLinkProps(t,(null==i?void 0:i.links)!==t.links),e||await this._dropLocalTables(!0),await this._createAndPrepareGraph(e,i,t)}else this.stats.pointsCount&&this._hasConfigChanged(i,t,x)&&(await this._updateUnrequiredPointProps(i,t),e&&await this._updateUnrequiredLinkProps(i,t),null===(n=this.cosmos)||void 0===n||n.render());if(a){(this.stats.pointsCount&&this._hasConfigChanged(i,t,j)||r)&&this._labels.update()}else this._labels.clear()}async _updateRequiredProps(i){var t;if(!this._dbCoordinator)return{pointsOk:!1,linksOk:!1};if(!i.points){this.reset(!1);const i="Points source data is not provided in `points`.";return c(i,"_updateRequiredProps","error"),this._updateMessage(`🚨 ${i}`),{pointsOk:!1,linksOk:!1}}let o={pointsError:!1,linksError:!1};(null===(t=this._dbCoordinator)||void 0===t?void 0:t.internalDB)?o=await this._uploadData(i.points,i.links):this._updateMessage(null);const s=!o.pointsError&&await this._checkUpdatedRequiredPointsProps(i);if(!s)return this.reset(!1),{pointsOk:!1,linksOk:!1};const n=!o.linksError&&await this._updateRequiredLinkProps(i);return i.links&&!n&&c("Provided links data is empty or invalid. Only points will be rendered.","_updateRequiredProps","warn"),{pointsOk:s,linksOk:n}}async _checkUpdatedRequiredPointsProps(i){if(!this._dbCoordinator)return!1;if(!await y(this._dbCoordinator,this.pointsTableName)){const i=`Failed to get points data. Table "${this.pointsTableName}" does not exist`;return c(i,"_checkUpdatedRequiredPointsProps","error"),this._updateMessage(`🚨 ${i}`),!1}const t=F.slice(1),o=t.filter((t=>void 0===i[t]));if(o.length>0){const i=`Failed to get points data. \n\nMissing required properties: ${o.map((i=>`"${i}"`)).join(", ")}.`;return c(i,"_checkUpdatedRequiredPointsProps","error"),this._updateMessage(`🚨 ${i}`),!1}const s=t.map((t=>i[t])),n=[];if(!await S(this._dbCoordinator,this.pointsTableName,s,n)){const i=`Failed to get points data. \n\nMissing provided columns for required properties: ${n.map((i=>`"${i}" (${t[n.indexOf(i)]})`)).join(", ")}.`;return c(i,"_checkUpdatedRequiredPointsProps","error"),this._updateMessage(`🚨 ${i}`),!1}return!0}async _updateRequiredLinkProps(i,t){var o;if(!this._dbCoordinator)return!1;if(!i.links)return await this._dropLocalTables(!0),!1;t&&((null===(o=this._dbCoordinator)||void 0===o?void 0:o.internalDB)?await this._uploadData(void 0,i.links):this._updateMessage(null));if(!await y(this._dbCoordinator,this.linksTableName)){const i=`Failed to get links data. Table "${this.linksTableName}" does not exist`;return c(i,"_updateRequiredLinkProps","error"),this._updateMessage(`🚨 ${i}`),!1}const s=q.slice(1),n=s.filter((t=>void 0===i[t]));if(n.length>0)return c(`Failed to get links data, only points will be rendered. \n\nMissing required properties: ${n.map((i=>`"${i}"`)).join(", ")}.`,"_updateRequiredLinkProps","warn"),!1;const e=s.map((t=>i[t])),a=[],r=await S(this._dbCoordinator,this.linksTableName,e,a);return r||c(`Failed to get links data, only points will be rendered.\n\n Missing provided columns for required properties: ${a.map((i=>`"${i}" (${s[a.indexOf(i)]})`)).join(", ")}.`,"_updateRequiredLinkProps","warn"),r}async _updateUnrequiredProps(i,t,o,s,n,e,a){if(!this._dbCoordinator)return;const r=async()=>{a||(a=await n(this._dbCoordinator,s))};for(const[s,n]of Object.entries(e))i&&(null==i?void 0:i[s])===t[s]&&(null==i?void 0:i[n])===t[n]||(await r(),await this._handlePropertyUpdate(t,s,n,o,a))}async _updateUnrequiredPointProps(i,t,o=!1){if(!this._dbCoordinator)return;let s;const n={pointColor:z.PointColorFn,pointSize:z.PointSizeFn};i&&this.stats.pointsCount&&(null==i?void 0:i.pointX)===t.pointX&&(null==i?void 0:i.pointY)===t.pointY||(s=await f(this._dbCoordinator,this.pointsTableName),await this._handlePointPositions(s,o)),await this._updateUnrequiredProps(i,t,!1,this.pointsTableName,f,n,s)}async _updateUnrequiredLinkProps(i,t){var o;if(!this._dbCoordinator)return;const s={linkColor:O.LinkColorFn,linkWidth:O.LinkWidthFn,linkArrow:O.LinkArrowFn,linkStrength:O.LinkStrengthFn};if(!i||!this.stats.linksCount){const i=await B(this._dbCoordinator,this.linksTableName),t=U(i,this.config);null===(o=this._cosmos)||void 0===o||o.setLinks(t)}await this._updateUnrequiredProps(i,t,!0,this.linksTableName,B,s,undefined)}async addData(i,t){var o,s;if(this._dbCoordinator&&this.stats.pointsCount&&(null===(o=this._dbCoordinator)||void 0===o?void 0:o.internalDB)){if(i&&(await this._dbCoordinator.internalDB.uploadData(i,_.Points,!0),await this._updateUnrequiredPointProps(void 0,this.config,!0)),t){const i=await y(this._dbCoordinator,this.linksTableName);await this._dbCoordinator.internalDB.uploadData(t,_.Links,i),await this._updateUnrequiredLinkProps(void 0,this.config)}null===(s=this.cosmos)||void 0===s||s.render(this.config.simulationImpulse),await this._updateStats(),this._triggerDataUpdated()}}async removePointsByIndices(i,t=!0){var o,s;if(this._dbCoordinator&&!(this.stats.pointsCount<=1)&&(null===(o=this._dbCoordinator)||void 0===o?void 0:o.internalDB)){const o=`${i.join(", ")}`;await this._dbCoordinator.internalDB.query(`DELETE FROM ${this.pointsTableName} WHERE "${this.config.pointIndex}" IN (${o})`),this._removeCosmosPoints(i),t&&this.stats.linksCount&&(await this._dbCoordinator.internalDB.query(`DELETE FROM ${this.linksTableName} WHERE "${this.config.linkSourceIndex}" IN (${o}) \n OR "${this.config.linkTargetIndex}" IN (${o})`),await this._updateUnrequiredLinkProps(void 0,this.config)),null===(s=this.cosmos)||void 0===s||s.render(this.config.simulationImpulse),await this._updateStats(),this._triggerDataUpdated()}}async removeLinksByPointIdPairs(i){await this._removeLinks(i,!1)}async removeLinksByPointIndicesPairs(i){await this._removeLinks(i,!0)}_removeCosmosPoints(i){var t,o,s,n;if(!i.length)return;const e=E(i,null===(t=this.cosmos)||void 0===t?void 0:t.graph.pointPositions,2);null===(o=this.cosmos)||void 0===o||o.setPointPositions(e);const a=E(i,null===(s=this.cosmos)||void 0===s?void 0:s.graph.pointColors,4);this._setCosmosData(z.PointColor,a);const r=E(i,null===(n=this.cosmos)||void 0===n?void 0:n.graph.pointSizes,1);this._setCosmosData(z.PointSize,r)}async _removeLinks(i,t){var o,s;if(!(null===(o=this._dbCoordinator)||void 0===o?void 0:o.internalDB)||!this.stats.linksCount)return;const n=t?this.config.linkSourceIndex:this.config.linkSource,e=t?this.config.linkTargetIndex:this.config.linkTarget,a=i=>t?i.toString():`'${i}'`,r=i.map((([i,t])=>`((${n} = ${a(i)} AND ${e} = ${a(t)}) OR \n (${n} = ${a(t)} AND ${e} = ${a(i)}))`)).join(" OR "),l=`\n DELETE FROM ${this.linksTableName}\n WHERE ${r}\n `;await this._dbCoordinator.internalDB.query(l),await this._updateUnrequiredLinkProps(void 0,this.config),null===(s=this.cosmos)||void 0===s||s.render(this.config.simulationImpulse),await this._updateStats(),this._triggerDataUpdated()}async _triggerDataUpdated(){var i,t;this._dbCoordinator&&(this._dbCoordinator.clearCache(),this.dispatchEvent(new CustomEvent("dataUpdated")),null===(t=null===(i=this.config)||void 0===i?void 0:i.onDataUpdated)||void 0===t||t.call(i,this._stats))}async _updateStats(){var i,t,o,s,n,e,a;this._stats={pointsCount:null!==(t=null===(i=this._cosmos)||void 0===i?void 0:i.graph.pointsNumber)&&void 0!==t?t:0,linksCount:null!==(n=null===(s=null===(o=this._cosmos)||void 0===o?void 0:o.graph)||void 0===s?void 0:s.linksNumber)&&void 0!==n?n:0,pointsSummary:await this.getPointsSummary(),linksSummary:(null===(a=null===(e=this._cosmos)||void 0===e?void 0:e.graph)||void 0===a?void 0:a.linksNumber)?await this.getLinksSummary():void 0}}_setCosmosData(i,t){var o,s,n,e,a,r;switch(i){case z.PointColor:null===(o=this._cosmos)||void 0===o||o.setPointColors(t);break;case z.PointSize:null===(s=this._cosmos)||void 0===s||s.setPointSizes(t);break;case O.LinkColor:null===(n=this._cosmos)||void 0===n||n.setLinkColors(t);break;case O.LinkWidth:null===(e=this._cosmos)||void 0===e||e.setLinkWidths(t);break;case O.LinkArrow:null===(a=this._cosmos)||void 0===a||a.setLinkArrows(t);break;case O.LinkStrength:null===(r=this._cosmos)||void 0===r||r.setLinkStrength(t)}}_getDataForProperty(i,t,o,s){switch(o){case z.PointColor:case O.LinkColor:return T(i,t,o,s);case z.PointSize:case O.LinkWidth:case O.LinkStrength:return R(i,t,o,s);case O.LinkArrow:return D(i,t,o,s);default:return[]}}async _handlePropertyUpdate(i,t,o,s,n){if(!this._dbCoordinator)return;const e=i[t],a=s?this.linksTableName:this.pointsTableName;if(!i[t])return i[o]&&c(`\`${o}\` used on \`${t}\`, but \`${t}\` is not provided`,"_handlePropertyUpdate","warn"),void this._setCosmosData(t,[]);const r=await S(this._dbCoordinator,a,[e]),l="function"==typeof i[o]||void 0===i[o];if(!r||!l)return r||c(`Column "${e}" for \`${t}\` not found`,"_handlePropertyUpdate","warn"),l||c(`Provided \`${o}\` is not a function`,"_handlePropertyUpdate","warn"),void this._setCosmosData(t,[]);if(n||(n=s?await B(this._dbCoordinator,a):await f(this._dbCoordinator,a)),null==n?void 0:n.numRows){const s=i[o],a=this._getDataForProperty(n,e,t,s);this._setCosmosData(t,a)}}_clearCosmosBuffers(i){var t,o,s,n,e,a,r,l;i||(null===(t=this.cosmos)||void 0===t||t.setPointPositions([]),null===(o=this.cosmos)||void 0===o||o.setPointColors([]),null===(s=this.cosmos)||void 0===s||s.setPointSizes([])),null===(n=this.cosmos)||void 0===n||n.setLinks([]),null===(e=this.cosmos)||void 0===e||e.setLinkColors([]),null===(a=this.cosmos)||void 0===a||a.setLinkWidths([]),null===(r=this.cosmos)||void 0===r||r.setLinkStrength([]),null===(l=this.cosmos)||void 0===l||l.setLinkArrows([])}async _handlePointPositions(i,t=!1){var o,s,n;if(!this._dbCoordinator)return;if(!(null==i?void 0:i.numRows))return void(null===(o=this._cosmos)||void 0===o||o.setPointPositions([]));let e=[];const a=[],r=Boolean(this.config.pointX)!==Boolean(this.config.pointY);if(this.config.pointX&&this.config.pointY&&await S(this._dbCoordinator,this.pointsTableName,[this.config.pointX,this.config.pointY],a))e=C(i,this.config);else if(t&&this.stats.pointsCount&&i.numRows>this.stats.pointsCount){const t=null===(s=this._cosmos)||void 0===s?void 0:s.getPointPositions();e=(null==t?void 0:t.length)?null==t?void 0:t.concat(b(i.numRows-t.length/2,this.config.spaceSize)):b(i.numRows,this.config.spaceSize)}else e=b(i.numRows,this.config.spaceSize),r?c(`Only one of \`${z.PointX}\` or \`${z.PointY}\` provided. Random coordinates generated.`,"warn"):this.config.pointX&&this.config.pointY&&c(`Failed to get provided point coordinates. Random coordinates generated.\nMissing provided columns for coordinates: ${a.join(", ")}.`,"warn");this._labels.render(),null===(n=this._cosmos)||void 0===n||n.setPointPositions(e)}async _uploadData(i,t){if(this._dataUploadPromise)return c("Data upload is already in progress, waiting for it to complete.","uploadData","info"),await this._dataUploadPromise,{pointsError:!1,linksError:!1};let o=!1,s=!1;return this._dataUploadPromise=new Promise((n=>{(async()=>{var e;try{if(await this._dbReadinessPromise,null===(e=this._dbCoordinator)||void 0===e?void 0:e.internalDB){if(c("Data uploading...","uploadData"),this._isDataUploading)return void c("Already uploading data, skipping this call.","uploadData","warn");if(this._updateMessage("🌀 Loading data...",!0),i){(await this._dbCoordinator.internalDB.uploadData(i,_.Points)).error&&(o=!0)}if(t){(await this._dbCoordinator.internalDB.uploadData(t,_.Links)).error&&(s=!0)}}}finally{this._updateMessage(o?"🚨 Points data is empty or invalid.":null),n(),this._dataUploadPromise=null}})().catch((i=>{c(`Error during data upload: ${i}`,"uploadData","error"),n(),this._dataUploadPromise=null}))})),this._dataUploadPromise.then((()=>({pointsError:o,linksError:s})))}async _createAndPrepareGraph(i,t,o){var s,n,e;try{if(await this._dbReadinessPromise,!this._dbCoordinator)return;if(this.dispatchEvent(new CustomEvent("dataUpdated")),this.config.points){const i=await k(this._dbCoordinator,this.pointsTableName,o);null===this._disableSimulation&&(this._disableSimulation=!this.config.links||i),this._cosmosConfig.disableSimulation=this._disableSimulation,await this._initializeCosmos(),await this._updateUnrequiredPointProps(t,o)}let a;i&&(a=await B(this._dbCoordinator,this.linksTableName),(null==a?void 0:a.numRows)&&await this._updateUnrequiredLinkProps(void 0,o)),this.config.points&&(null===(s=this.cosmos)||void 0===s||s.render(1)),await this._updateStats(),this.config.points?c(`Rendered graph with ${this._stats.pointsCount} points and ${this._stats.linksCount} links.`):(c(`Loaded ${null==a?void 0:a.numRows} links into graph, waiting for points to be loaded.`),this._updateMessage(`🔗 Loaded ${null==a?void 0:a.numRows} links. Upload points to complete the graph.`)),this._resolveGraphReady&&(this._resolveGraphReady(),this._resolveGraphReady=null),null===(e=null===(n=this.config)||void 0===n?void 0:n.onDataUpdated)||void 0===e||e.call(n,this._stats)}catch(i){c(i,"_createAndPrepareGraph","error"),this._updateMessage(`🚨 ${i}`)}}_getIntersection(){const{links:i,points:t}=this._crossfilter,o=t.values();let s=new Set;if(this._linksSelection.clauses.length&&this._pointsSelection.clauses.length)for(const t of o)i.has(t)&&s.add(t);else s=this._linksSelection.clauses.length?i:t;this._crossfilter.intersection=s}activateRectSelection(){this._rectSelect.enable()}deactivateRectSelection(){this._rectSelect.disable()}selectPointsInRect(i){if(!this._cosmos||!i)return;const t=this._cosmos.getPointsInRange(i);this.selectPoints(Array.from(t))}selectPoints(i){var t,o;i&&i.length?null===(t=this._selectionClient)||void 0===t||t.publish(i):null===(o=this._selectionClient)||void 0===o||o.publish(void 0)}selectPoint(i,t=!1){var o,s;if(this._cosmos)if(void 0!==i){let s=[i];t&&(s=s.concat(this._cosmos.getAdjacentIndices(i))),null===(o=this._selectionClient)||void 0===o||o.publish(s)}else null===(s=this._selectionClient)||void 0===s||s.publish(void 0)}unselectPoints(){var i;this._cosmos&&(null===(i=this._selectionClient)||void 0===i||i.publish(void 0))}getSelectedPointIndices(){var i;return null===(i=this._cosmos)||void 0===i?void 0:i.getSelectedIndices()}setZoomLevel(i,t=0){var o;null===(o=this._cosmos)||void 0===o||o.setZoomLevel(i,t)}getZoomLevel(){var i;return null===(i=this._cosmos)||void 0===i?void 0:i.getZoomLevel()}zoomToPoint(i,t,o,s){var n;null===(n=this._cosmos)||void 0===n||n.zoomToPointByIndex(i,t,o,s)}getPointPositions(){var i;return null===(i=this._cosmos)||void 0===i?void 0:i.getPointPositions()}fitView(i=250,t=.1){var o;null===(o=this._cosmos)||void 0===o||o.fitView(i,t)}fitViewByIndices(i,t=250,o){var s;null===(s=this._cosmos)||void 0===s||s.fitViewByPointIndices(i,t,o)}fitViewByCoordinates(i,t=250,o){var s;null===(s=this._cosmos)||void 0===s||s.fitViewByPointPositions(i,t,o)}focusPoint(i){var t;null===(t=this._cosmos)||void 0===t||t.setFocusedPointByIndex(i)}getAdjacentPointIndices(i){var t;return null===(t=this._cosmos)||void 0===t?void 0:t.getAdjacentIndices(i)}spaceToScreenPosition(i){var t;return null===(t=this._cosmos)||void 0===t?void 0:t.spaceToScreenPosition(i)}screenToSpacePosition(i){var t;return null===(t=this._cosmos)||void 0===t?void 0:t.spaceToScreenPosition(i)}spaceToScreenRadius(i){var t;return null===(t=this._cosmos)||void 0===t?void 0:t.spaceToScreenRadius(i)}getPointRadiusByIndex(i){var t;return null===(t=this._cosmos)||void 0===t?void 0:t.getPointRadiusByIndex(i)}getSampledPointPositionsMap(){var i;return null===(i=this._cosmos)||void 0===i?void 0:i.getSampledPointPositionsMap()}start(i=1){var t;null===(t=this._cosmos)||void 0===t||t.start(i)}pause(){var i;null===(i=this._cosmos)||void 0===i||i.pause()}restart(){var i;null===(i=this._cosmos)||void 0===i||i.restart()}step(){var i;null===(i=this._cosmos)||void 0===i||i.step()}async destroy(){var i,t;null===(i=this._cosmos)||void 0===i||i.destroy(),await this._dropLocalTables(),await(null===(t=this.dbCoordinator)||void 0===t?void 0:t.destroy()),this._containerElement.innerHTML="",this._labels.isDestroyed||this._labels.destroy()}create(){var i;null===(i=this._cosmos)||void 0===i||i.create()}async reset(i=!0){var t;i&&(this._labels.destroy(),this._cosmographConfig=u,this._messageDivElement.innerText="👩🏻‍🚀 Cosmograph is ready, load your data!",this._messageDivElement.style.display="block"),await this._dropLocalTables(),this.dispatchEvent(new CustomEvent("dataUpdated")),null===(t=this._dbCoordinator)||void 0===t||t.clearCache(),this._stats={pointsCount:0,linksCount:0,pointsSummary:void 0,linksSummary:void 0}}getPointDegrees(){var i;return null===(i=this._cosmos)||void 0===i?void 0:i.graph.degree}async getPointIndicesByIds(i){if(this._dbCoordinator&&this.stats.pointsCount)return await v(this._dbCoordinator,this.pointsTableName,this.config,i)}async getPointIdsByIndices(i){if(this._dbCoordinator&&this.stats.pointsCount)return await g(this._dbCoordinator,this.pointsTableName,this.config,i)}async getPointsByIndices(i){if(this._dbCoordinator&&this.stats.pointsCount)return await P(this._dbCoordinator,this.pointsTableName,this.config.pointIndex,i)}async getPointIndicesByColumnValues(i,t){if(this._dbCoordinator&&this.stats.pointsCount)return await w(this._dbCoordinator,this.pointsTableName,this.config,i,t)}async getPointIndicesByLinksColumnValues(i,t){if(this._dbCoordinator&&this.stats.linksCount)return await I(this._dbCoordinator,this.linksTableName,this.config,i,t)}async getLinksByPointIds(i){if(this._dbCoordinator&&this.stats.linksCount)return await M(this._dbCoordinator,this.pointsTableName,this.config,i)}async getLinksByPointIndices(i){if(this._dbCoordinator&&this.stats.linksCount)return await N(this._dbCoordinator,this.pointsTableName,this.config,i)}convertCosmographDataToObject(i){return h(i)}flattenPositions(i){var t;return null===(t=this._cosmos)||void 0===t?void 0:t.flatten(i)}pair(i){var t;return null===(t=this._cosmos)||void 0===t?void 0:t.pair(i)}async getPointsSummary(){if(this._dbCoordinator)return await L(this._dbCoordinator,this.pointsTableName)}async getLinksSummary(){if(this._dbCoordinator)return await L(this._dbCoordinator,this.linksTableName)}_createCosmosConfig(i){const t={...i,simulation:{...Object.keys(null!=i?i:{}).filter((i=>-1!==i.indexOf("simulation"))).reduce(((t,o)=>{const s=o.replace("simulation","");return t[s.charAt(0).toLowerCase()+s.slice(1)]=null==i?void 0:i[o],t}),{}),onStart:this._onStart.bind(this),onTick:this._onTick.bind(this),onEnd:this._onEnd.bind(this),onPause:this._onPause.bind(this),onRestart:this._onRestart.bind(this)},events:{onClick:this._onClick.bind(this),onPointMouseOver:this._onPointMouseOver.bind(this),onPointMouseOut:this._onPointMouseOut.bind(this),onMouseMove:this._onMouseMove.bind(this),onZoomStart:this._onZoomStart.bind(this),onZoom:this._onZoom.bind(this),onZoomEnd:this._onZoomEnd.bind(this)}};return delete t.disableSimulation,t}}export{W as Cosmograph};
//# sourceMappingURL=index.js.map

@@ -1,2 +0,2 @@

import{LabelRenderer as s,CssLabel as e}from"@interacta/css-labels";import{getLabelsByIds as o,getTopLabels as i,getLabelsByIndices as a}from"./queries.js";import{checkColumnsExist as t}from"../data-ops/misc.js";import{cosmographLog as l}from"../../../utils/log.js";import r from"./style.module.css.js";class h{constructor(o,i,a,t){this._staticLabelsMap=new Map,this._dynamicLabelsMap=new Map,this._validLabelAccessor=!1,this._validLabelWeightAccessor=!1,this._validTopLabelsAccessor=!1,this._labelDataMap=new Map,this.div=document.createElement("div"),this.isDestroyed=!1,this._cosmograph=o,this._onHoveredLabelClick=t.onHoveredLabelClick,i.appendChild(this.div),this._cssLabelsRenderer=new s(this.div,{dispatchWheelEventElement:a,pointerEvents:"all",onLabelClick:t.onLabelClick}),this._hoveredCssLabel=new e(this.div),this._hoveredCssLabel.setPointerEvents("all"),this._hoveredCssLabel.element.addEventListener("click",t.onHoveredLabelClick)}async update(){if(this.isDestroyed||!this._cosmograph.cosmos||!this._cosmograph.dbCoordinator)return;const{pointLabel:s,pointLabelWeight:e,showTopLabelsBy:o}=this._cosmograph.config;if(s){const i=[];await t(this._cosmograph.dbCoordinator,this._cosmograph.pointsTableName,[s,o,e].filter(Boolean),i),this._validLabelAccessor=!i.includes(s),this._validTopLabelsAccessor=!!o&&!i.includes(o),this._validLabelWeightAccessor=!!e&&!i.includes(e),this._validLabelAccessor?(await this._updateStaticLabels(),await this.render()):(l(`Column "${s}" for \`pointLabel\` not found`,"Labels > update","warn"),this.clear())}else this.clear()}async render(){!this.isDestroyed&&this._cosmograph.cosmos&&this._cosmograph.config&&this._validLabelAccessor&&(await this._updateLabels(),this._renderLabels())}async _updateStaticLabels(){var s;const{pointLabel:e,showTopLabels:i,showTopLabelsBy:a,showLabelsFor:t}=this._cosmograph.config;if(this._staticLabelsMap.clear(),this._cosmograph.dbCoordinator&&e){if(i){const s=await this._getTopLabels(a);this._setLabels(this._staticLabelsMap,s)}if(null==t?void 0:t.length){const s=await o(this._cosmograph.dbCoordinator,this._cosmograph.pointsTableName,this._cosmograph.config,this._validLabelWeightAccessor);this._setLabels(this._staticLabelsMap,s)}}null===(s=this._cosmograph.cosmos)||void 0===s||s.trackPointPositionsByIndices(Array.from(this._staticLabelsMap.keys()))}async _getTopLabels(s){if(this._cosmograph.dbCoordinator){if(s){if(this._validTopLabelsAccessor)return await i(this._cosmograph.dbCoordinator,this._cosmograph.pointsTableName,this._cosmograph.config,this._validLabelWeightAccessor);l(`Column "${s}" for \`showTopLabelsBy\` not found, getting top labels by degree`,"Labels > _getTopLabels","warn")}return await a(this._cosmograph.dbCoordinator,this._cosmograph.pointsTableName,this._cosmograph.config,this._findTopIndicesByDegree(),this._validLabelWeightAccessor)}}_setLabels(s,e){var o;if(e&&e.indices&&e.labels&&e.ids)for(let i=0;i<e.indices.length;i++)s.set(e.indices.get(i),[e.ids.get(i),e.labels.get(i),null===(o=e.weights)||void 0===o?void 0:o.get(i)])}_findTopIndicesByDegree(){var s,e;if(!(null===(s=this._cosmograph.cosmos)||void 0===s?void 0:s.graph.degree))return[];const o=null===(e=this._cosmograph.cosmos)||void 0===e?void 0:e.graph.degree,i=o.map(((s,e)=>e)).sort(((s,e)=>{var i,a;return(null!==(i=o[e])&&void 0!==i?i:0)-(null!==(a=o[s])&&void 0!==a?a:0)}));return i.slice(0,this._cosmograph.config.showTopLabelsLimit)}async _updateLabels(){var s;const{showDynamicLabels:e,pointLabel:o}=this._cosmograph.config;if(this._dynamicLabelsMap.clear(),e&&o){const e=this._cosmograph.getSampledPointPositionsMap();if(this._cosmograph.dbCoordinator&&(null==e?void 0:e.size)){const o=await a(this._cosmograph.dbCoordinator,this._cosmograph.pointsTableName,this._cosmograph.config,Array.from(null!==(s=null==e?void 0:e.keys())&&void 0!==s?s:[]));this._setLabels(this._dynamicLabelsMap,o)}}this._populateLabelDataMap()}_populateLabelDataMap(){var s;if(this._labelDataMap.clear(),this._staticLabelsMap.size){const e=null===(s=this._cosmograph.cosmos)||void 0===s?void 0:s.getTrackedPointPositionsMap();null==e||e.forEach(((s,e)=>{const o=this._staticLabelsMap.get(e);if(void 0!==o){const[i,a,t]=o;this._labelDataMap.set(i,{index:e,text:a,position:s,className:r.cosmographStaticLabel,weight:null!=t?t:this._cosmograph.config.staticLabelWeight})}}))}const e=this._cosmograph.getSampledPointPositionsMap();null==e||e.forEach(((s,e)=>{const o=this._dynamicLabelsMap.get(e);if(void 0!==o){const[i,a,t]=o;this._labelDataMap.set(i,{index:e,text:a,position:s,className:r.cosmographDynamicLabel,weight:null!=t?t:this._cosmograph.config.dynamicLabelWeight})}}))}_renderLabels(){var s,e,o,i;const{config:a,crossfilter:t,maxPointSize:l}=this._cosmograph,{pointLabelClassName:h,scalePointsOnZoom:n,labelPadding:c}=a,d=null!==(e=null===(s=this._cosmograph.cosmos)||void 0===s?void 0:s.config.pointSizeScale)&&void 0!==e?e:1,p=t.intersection,b=p.size>0,_=Array.from(this._labelDataMap.entries()).map((([s,{index:e,text:o,position:i,className:a,weight:t}])=>{var _;const[m,g]=this._cosmograph.spaceToScreenPosition(i),L=this._cosmograph.getPointRadiusByIndex(e),v=!1!==n?Math.min(d*L*this._cosmograph.getZoomLevel(),l):this._cosmograph.spaceToScreenRadius(d*L),u=p.has(e),f=this._staticLabelsMap.has(e),y=b&&!u?"opacity: 0.1;":"",C="function"==typeof h?null!==(_=h(o,e,s))&&void 0!==_?_:"":null!=h?h:"",w=C.includes(":"),M=w?a:[r.cosmographLabel,C,a].join(" ");return{id:s,text:o,x:m,y:g-v/2-c,weight:b&&!u?t?.1*t:.1:t,shouldBeShown:f,style:w?`${y}${C}`:y,className:M}}));null===(o=this._cssLabelsRenderer)||void 0===o||o.setLabels(_),null===(i=this._cssLabelsRenderer)||void 0===i||i.draw(!0)}async renderHoveredLabel(s,e){var o,i,t,l,h;if(this.isDestroyed||!this._cosmograph.cosmos)return;const{config:n,dbCoordinator:c,maxPointSize:d}=this._cosmograph,{pointLabel:p,showHoveredPointLabel:b,hoveredPointLabelClassName:_,scalePointsOnZoom:m,labelPadding:g}=n;if(!(c&&b&&p&&void 0!==s&&e&&this._validLabelAccessor))return this._hoveredCssLabel.setVisibility(!1),void this._hoveredCssLabel.draw();const L=await a(c,this._cosmograph.pointsTableName,n,[s]);if(!L)return;const v=null===(o=L.ids)||void 0===o?void 0:o.get(0),u=null!==(t=null===(i=L.labels)||void 0===i?void 0:i.get(0))&&void 0!==t?t:"",[f,y]=this._cosmograph.spaceToScreenPosition(e),C=null!==(l=this._cosmograph.cosmos.config.pointSizeScale)&&void 0!==l?l:1,w=this._cosmograph.getPointRadiusByIndex(s),M=!1!==m?Math.min(C*w*this._cosmograph.getZoomLevel(),d):this._cosmograph.spaceToScreenRadius(C*w),T="function"==typeof _?null!==(h=_(u,s,v))&&void 0!==h?h:"":null!=_?_:"",P=T.includes(":"),D=P?r.cosmographLabel:[r.cosmographLabel,T].join(" "),S=P?T:"";this._hoveredCssLabel.setText(u),this._hoveredCssLabel.setVisibility(!0),this._hoveredCssLabel.setPosition(f,y-M/2-g),this._hoveredCssLabel.setClassName(D),this._hoveredCssLabel.setStyle(S),this._hoveredCssLabel.draw()}destroy(){var s,e,o;this.isDestroyed=!0,this._onHoveredLabelClick&&(null===(s=this._hoveredCssLabel)||void 0===s||s.element.removeEventListener("click",this._onHoveredLabelClick)),null===(e=this._hoveredCssLabel)||void 0===e||e.destroy(),null===(o=this._cssLabelsRenderer)||void 0===o||o.destroy()}clear(){var s,e;this._labelDataMap.size&&(this._staticLabelsMap.clear(),this._dynamicLabelsMap.clear(),this._labelDataMap.clear(),null===(s=this._cssLabelsRenderer)||void 0===s||s.setLabels([]),null===(e=this._cssLabelsRenderer)||void 0===e||e.draw())}}export{h as Labels};
import{LabelRenderer as s,CssLabel as e}from"@interacta/css-labels";import{getLabelsByIds as o,getTopLabels as i,getLabelsByIndices as a}from"./queries.js";import{checkColumnsExist as t}from"../data-ops/misc.js";import{cosmographLog as l}from"../../../utils/log.js";import r from"./style.module.css.js";class n{constructor(o,i,a,t){this._staticLabelsMap=new Map,this._dynamicLabelsMap=new Map,this._validLabelAccessor=!1,this._validLabelWeightAccessor=!1,this._validTopLabelsAccessor=!1,this._labelDataMap=new Map,this.div=document.createElement("div"),this.isDestroyed=!1,this._cosmograph=o,this._onHoveredLabelClick=t.onHoveredLabelClick,i.appendChild(this.div),this._cssLabelsRenderer=new s(this.div,{dispatchWheelEventElement:a,pointerEvents:"all",onLabelClick:t.onLabelClick,padding:this._cosmograph.config.labelPadding}),this._hoveredCssLabel=new e(this.div),this._hoveredCssLabel.setPointerEvents("all"),this._hoveredCssLabel.element.addEventListener("click",t.onHoveredLabelClick)}async update(){if(this.isDestroyed||!this._cosmograph.cosmos||!this._cosmograph.dbCoordinator)return;const{pointLabel:s,pointLabelWeight:e,showTopLabelsBy:o}=this._cosmograph.config;if(s){const i=[];await t(this._cosmograph.dbCoordinator,this._cosmograph.pointsTableName,[s,o,e].filter(Boolean),i),this._validLabelAccessor=!i.includes(s),this._validTopLabelsAccessor=!!o&&!i.includes(o),this._validLabelWeightAccessor=!!e&&!i.includes(e),this._validLabelAccessor?(await this._updateStaticLabels(),await this.render()):(l(`Column "${s}" for \`pointLabel\` not found`,"Labels > update","warn"),this.clear())}else this.clear()}async render(){!this.isDestroyed&&this._cosmograph.cosmos&&this._cosmograph.config&&this._validLabelAccessor&&(await this._updateLabels(),this._renderLabels())}async _updateStaticLabels(){var s;const{pointLabel:e,showTopLabels:i,showTopLabelsBy:a,showLabelsFor:t}=this._cosmograph.config;if(this._staticLabelsMap.clear(),this._cosmograph.dbCoordinator&&e){if(i){const s=await this._getTopLabels(a);this._setLabels(this._staticLabelsMap,s)}if(null==t?void 0:t.length){const s=await o(this._cosmograph.dbCoordinator,this._cosmograph.pointsTableName,this._cosmograph.config,this._validLabelWeightAccessor);this._setLabels(this._staticLabelsMap,s)}}null===(s=this._cosmograph.cosmos)||void 0===s||s.trackPointPositionsByIndices(Array.from(this._staticLabelsMap.keys()))}async _getTopLabels(s){if(this._cosmograph.dbCoordinator){if(s){if(this._validTopLabelsAccessor)return await i(this._cosmograph.dbCoordinator,this._cosmograph.pointsTableName,this._cosmograph.config,this._validLabelWeightAccessor);l(`Column "${s}" for \`showTopLabelsBy\` not found, getting top labels by degree`,"Labels > _getTopLabels","warn")}return await a(this._cosmograph.dbCoordinator,this._cosmograph.pointsTableName,this._cosmograph.config,this._findTopIndicesByDegree(),this._validLabelWeightAccessor)}}_setLabels(s,e){var o;if(e&&e.indices&&e.labels&&e.ids)for(let i=0;i<e.indices.length;i++)s.set(e.indices.get(i),[e.ids.get(i),e.labels.get(i),null===(o=e.weights)||void 0===o?void 0:o.get(i)])}_findTopIndicesByDegree(){var s,e;if(!(null===(s=this._cosmograph.cosmos)||void 0===s?void 0:s.graph.degree))return[];const o=null===(e=this._cosmograph.cosmos)||void 0===e?void 0:e.graph.degree,i=o.map(((s,e)=>e)).sort(((s,e)=>{var i,a;return(null!==(i=o[e])&&void 0!==i?i:0)-(null!==(a=o[s])&&void 0!==a?a:0)}));return i.slice(0,this._cosmograph.config.showTopLabelsLimit)}async _updateLabels(){var s;const{showDynamicLabels:e,pointLabel:o}=this._cosmograph.config;if(this._dynamicLabelsMap.clear(),e&&o){const e=this._cosmograph.getSampledPointPositionsMap();if(this._cosmograph.dbCoordinator&&(null==e?void 0:e.size)){const o=await a(this._cosmograph.dbCoordinator,this._cosmograph.pointsTableName,this._cosmograph.config,Array.from(null!==(s=null==e?void 0:e.keys())&&void 0!==s?s:[]));this._setLabels(this._dynamicLabelsMap,o)}}this._populateLabelDataMap()}_populateLabelDataMap(){var s;if(this._labelDataMap.clear(),this._staticLabelsMap.size){const e=null===(s=this._cosmograph.cosmos)||void 0===s?void 0:s.getTrackedPointPositionsMap();null==e||e.forEach(((s,e)=>{const o=this._staticLabelsMap.get(e);if(void 0!==o){const[i,a,t]=o;this._labelDataMap.set(i,{index:e,text:a,position:s,className:r.cosmographStaticLabel,weight:null!=t?t:this._cosmograph.config.staticLabelWeight})}}))}const e=this._cosmograph.getSampledPointPositionsMap();null==e||e.forEach(((s,e)=>{const o=this._dynamicLabelsMap.get(e);if(void 0!==o){const[i,a,t]=o;this._labelDataMap.set(i,{index:e,text:a,position:s,className:r.cosmographDynamicLabel,weight:null!=t?t:this._cosmograph.config.dynamicLabelWeight})}}))}_renderLabels(){var s,e,o,i;const{config:a,crossfilter:t,maxPointSize:l}=this._cosmograph,{pointLabelClassName:n,scalePointsOnZoom:h,labelMargin:c}=a,d=null!==(e=null===(s=this._cosmograph.cosmos)||void 0===s?void 0:s.config.pointSizeScale)&&void 0!==e?e:1,p=t.intersection,b=Array.from(this._labelDataMap.entries()).map((([s,{index:e,text:o,position:i,className:a,weight:t}])=>{var b;const[_,g]=this._cosmograph.spaceToScreenPosition(i),m=this._cosmograph.getPointRadiusByIndex(e),L=!1!==h?Math.min(d*m*this._cosmograph.getZoomLevel(),l):this._cosmograph.spaceToScreenRadius(d*m),v=!this._cosmograph.isFilteringActive||p.has(e),u=this._staticLabelsMap.has(e),f="function"==typeof n?null!==(b=n(o,e,s))&&void 0!==b?b:"":null!=n?n:"",y=f.includes(":"),C=v?r.cosmographLabel:r.cosmographLabelHidden,w=y?[C,a].join(" "):[C,f,a].join(" ");return{id:s,text:o,x:_,y:g-L/2-c,weight:v?t:t?.1*t:.1,shouldBeShown:u,style:f,className:w}}));null===(o=this._cssLabelsRenderer)||void 0===o||o.setLabels(b),null===(i=this._cssLabelsRenderer)||void 0===i||i.draw(!0)}async renderHoveredLabel(s,e){var o,i,t,l,n;if(this.isDestroyed||!this._cosmograph.cosmos)return;const{config:h,dbCoordinator:c,maxPointSize:d}=this._cosmograph,{pointLabel:p,showHoveredPointLabel:b,hoveredPointLabelClassName:_,scalePointsOnZoom:g,labelMargin:m}=h;if(!(c&&b&&p&&void 0!==s&&e&&this._validLabelAccessor))return this._hoveredCssLabel.setVisibility(!1),void this._hoveredCssLabel.draw();const L=await a(c,this._cosmograph.pointsTableName,h,[s]);if(!L)return;const v=null===(o=L.ids)||void 0===o?void 0:o.get(0),u=null!==(t=null===(i=L.labels)||void 0===i?void 0:i.get(0))&&void 0!==t?t:"",[f,y]=this._cosmograph.spaceToScreenPosition(e),C=null!==(l=this._cosmograph.cosmos.config.pointSizeScale)&&void 0!==l?l:1,w=this._cosmograph.getPointRadiusByIndex(s),M=!1!==g?Math.min(C*w*this._cosmograph.getZoomLevel(),d):this._cosmograph.spaceToScreenRadius(C*w),T="function"==typeof _?null!==(n=_(u,s,v))&&void 0!==n?n:"":null!=_?_:"",P=T.includes(":"),D=P?r.cosmographLabelHovered:[r.cosmographLabelHovered,T].join(" "),A=P?T:"";this._hoveredCssLabel.setText(u),this._hoveredCssLabel.setVisibility(!0),this._hoveredCssLabel.setPosition(f,y-M/2-m),this._hoveredCssLabel.setClassName(D),this._hoveredCssLabel.setStyle(A),this._hoveredCssLabel.setPadding(h.labelPadding),this._hoveredCssLabel.draw()}destroy(){var s,e,o;this.isDestroyed=!0,this._onHoveredLabelClick&&(null===(s=this._hoveredCssLabel)||void 0===s||s.element.removeEventListener("click",this._onHoveredLabelClick)),null===(e=this._hoveredCssLabel)||void 0===e||e.destroy(),null===(o=this._cssLabelsRenderer)||void 0===o||o.destroy()}clear(){var s,e;this._labelDataMap.size&&(this._staticLabelsMap.clear(),this._dynamicLabelsMap.clear(),this._labelDataMap.clear(),null===(s=this._cssLabelsRenderer)||void 0===s||s.setLabels([]),null===(e=this._cssLabelsRenderer)||void 0===e||e.draw())}}export{n as Labels};
//# sourceMappingURL=index.js.map

@@ -1,2 +0,2 @@

import{LabelsKeys as n}from"../config/labels.js";import{cosmographLog as t}from"../../../utils/log.js";const e=async(e,i,l,o,s=!1)=>{if(!l.pointId||!l.pointIndex||!l.pointLabel)return{indices:null,ids:null,labels:null,weights:null};const a=await e.query(`SELECT ${l.pointLabel}, ${l.pointIndex}, ${l.pointId}${s&&l.pointLabelWeight?`, ${l.pointLabelWeight}`:""} FROM ${i} ${o}`,!0);if(!a)return{indices:null,ids:null,labels:null,weights:null};const p=a.getChild(l.pointId),u=a.getChild(l.pointIndex),d=a.getChild(l.pointLabel);let r=null;s&&l.pointLabelWeight&&(r=a.getChild(l.pointLabelWeight));const c=l.pointLabelFn,b=l.pointLabelWeightFn;if(c&&"function"!=typeof c)t(`Provided \`${[n.PointLabelFn]}\` is not a function`,"executeLabelsQuery","warn");else if(c)for(let n=0;n<d.length;n++){const t=c(d.get(n),n);if(null==d||d.set(n,t),r&&b&&"function"==typeof b){const t=b(r.get(n),n);null==r||r.set(n,t)}}return{indices:u,ids:p,labels:d,weights:r}},i=async(n,t,i,l,o=!1)=>e(n,t,i,`WHERE ${i.pointIndex} IN (${l.join(", ")})`,o),l=async(n,t,i,l)=>e(n,t,i,`ORDER BY ${i.showTopLabelsBy} DESC LIMIT ${i.showTopLabelsLimit}`,l),o=async(n,t,i,l)=>{var o;const s=(null!==(o=i.showLabelsFor)&&void 0!==o?o:[]).map((n=>`'${n}'`)).join(", ");return e(n,t,i,`WHERE ${i.pointId} IN (${s})`,l)};export{o as getLabelsByIds,i as getLabelsByIndices,l as getTopLabels};
import{LabelsKeys as n}from"../config/labels.js";import{cosmographLog as t}from"../../../utils/log.js";const e=async(e,i,l,o,s=!1)=>{if(!l.pointId||!l.pointIndex||!l.pointLabel)return{indices:null,ids:null,labels:null,weights:null};const a=[...new Set([l.pointLabel,l.pointIndex,l.pointId])],p=await e.query(`SELECT ${a.map((n=>`"${n}"`)).join(", ")}${s&&l.pointLabelWeight?`, "${l.pointLabelWeight}"`:""} FROM ${i} ${o}`,!0);if(!p)return{indices:null,ids:null,labels:null,weights:null};const u=p.getChild(l.pointId),d=p.getChild(l.pointIndex),r=p.getChild(l.pointLabel);let c=null;s&&l.pointLabelWeight&&(c=p.getChild(l.pointLabelWeight));const b=l.pointLabelFn,g=l.pointLabelWeightFn;if(b&&"function"!=typeof b)t(`Provided \`${[n.PointLabelFn]}\` is not a function`,"executeLabelsQuery","warn");else if(b)for(let n=0;n<r.length;n++){const t=b(r.get(n),n);if(null==r||r.set(n,t),c&&g&&"function"==typeof g){const t=g(c.get(n),n);null==c||c.set(n,t)}}return{indices:d,ids:u,labels:r,weights:c}},i=async(n,t,i,l,o=!1)=>e(n,t,i,`WHERE ${i.pointIndex} IN (${l.join(", ")})`,o),l=async(n,t,i,l)=>e(n,t,i,`ORDER BY ${i.showTopLabelsBy} DESC LIMIT ${i.showTopLabelsLimit}`,l),o=async(n,t,i,l)=>{var o;const s=(null!==(o=i.showLabelsFor)&&void 0!==o?o:[]).map((n=>`'${n}'`)).join(", ");return e(n,t,i,`WHERE ${i.pointId} IN (${s})`,l)};export{o as getLabelsByIds,i as getLabelsByIndices,l as getTopLabels};
//# sourceMappingURL=queries.js.map

@@ -1,2 +0,2 @@

import e from'./../../../ext/rollup-plugin-styles/dist/runtime/inject-css.js';var o=".style_module_cosmographDynamicLabel__e6f5036f,.style_module_cosmographStaticLabel__e6f5036f{opacity:1}.style_module_cosmographLabel__e6f5036f{-webkit-font-smoothing:antialiased!important;font-weight:500;max-width:350px;overflow:hidden;padding:4px 7px!important;text-overflow:ellipsis;text-rendering:optimizeLegibility!important;transition:none;white-space:nowrap}",t={cosmographStaticLabel:"style_module_cosmographStaticLabel__e6f5036f",cosmographDynamicLabel:"style_module_cosmographDynamicLabel__e6f5036f",cosmographLabel:"style_module_cosmographLabel__e6f5036f"};e(o,{});export{o as css,t as default};
import e from'./../../../ext/rollup-plugin-styles/dist/runtime/inject-css.js';var o=".style_module_cosmographDynamicLabel__6fc04452,.style_module_cosmographStaticLabel__6fc04452{opacity:1}.style_module_cosmographLabelBase__6fc04452{-webkit-font-smoothing:antialiased!important;font-weight:500;max-width:350px;overflow:hidden;text-overflow:ellipsis;text-rendering:optimizeLegibility!important;transition:opacity .1s linear;white-space:nowrap}.style_module_cosmographLabelHovered__6fc04452{z-index:1}.style_module_cosmographLabelHidden__6fc04452{opacity:.1}",a={cosmographStaticLabel:"style_module_cosmographStaticLabel__6fc04452",cosmographDynamicLabel:"style_module_cosmographDynamicLabel__6fc04452",cosmographLabelBase:"style_module_cosmographLabelBase__6fc04452",cosmographLabel:"style_module_cosmographLabel__6fc04452 style_module_cosmographLabelBase__6fc04452",cosmographLabelHovered:"style_module_cosmographLabelHovered__6fc04452 style_module_cosmographLabelBase__6fc04452",cosmographLabelHidden:"style_module_cosmographLabelHidden__6fc04452 style_module_cosmographLabelBase__6fc04452"};e(o,{});export{o as css,a as default};
//# sourceMappingURL=style.module.css.js.map

@@ -1,2 +0,2 @@

import{MosaicClient as e}from"@uwdata/mosaic-core";import{Query as t}from"@uwdata/mosaic-sql";class i extends e{constructor(e,t,i){super(t),this._cosmograph=e,this._filterIndexable=!1,this._onSelected=i,this._selection=t}get filterIndexable(){return this._filterIndexable}query(e=[]){return 0===this._selection.predicate(this).length?(this._filterIndexable=!1,null):(this._filterIndexable=!0,t.from(this._cosmograph.pointsTableName).select(this._cosmograph.config.pointIndex).where(e))}publish(e){this._selection.update({source:this,predicate:e?`(${this._cosmograph.config.pointIndex} IN (${e.join(",")}))`:"1=1"})}queryResult(e){var t,i;return(null===(i=null===(t=this._selection)||void 0===t?void 0:t.active)||void 0===i?void 0:i.source)===this&&this._onSelected(e),this}}export{i as SelectionClient};
import{MosaicClient as e}from"@uwdata/mosaic-core";import{Query as t}from"@uwdata/mosaic-sql";class i extends e{constructor(e,t,i){super(t),this._cosmograph=e,this._filterIndexable=!1,this._onSelected=i,this._selection=t}get filterIndexable(){return this._filterIndexable}query(e=[]){return 0===this._selection.predicate(this).length?(this._filterIndexable=!1,null):(this._filterIndexable=!0,t.from(this._cosmograph.pointsTableName).select(this._cosmograph.config.pointIndex).where(e))}publish(e){this._selection.update({source:this,predicate:e?`(${this._cosmograph.config.pointIndex} IN (${e.join(",")}))`:void 0})}queryResult(e){var t,i;return(null===(i=null===(t=this._selection)||void 0===t?void 0:t.active)||void 0===i?void 0:i.source)===this&&this._onSelected(e),this}}export{i as SelectionClient};
//# sourceMappingURL=selection-client.js.map

@@ -1,2 +0,2 @@

import{Tables as n,Columns as i}from"../../enum.js";import{checkDevEnv as e,convertArrowToObject as t}from"../../utils/utils.js";const o=e(),p=async(n,i)=>{const e=await n.query(`DESCRIBE ${i}`);return new Map(t(e).map((n=>[n.column_name,n.column_type])))},a=(n,i)=>({existing:[...new Set(n.filter((n=>i.has(n.name))).map((n=>n.name)))],missing:n.filter((n=>!i.has(n.name)))}),r=async(e,t)=>{const{pointId:r,pointIncludeColumns:s=[],pointSize:m,pointColor:l,pointLabel:$,pointLabelWeight:d,pointX:u,pointY:E,linkSource:I,linkTargets:T}=t,S=await p(e,n.RawPoints),g=r?[{prop:"pointId",name:r}]:I&&T?[{prop:"linkSource",name:I},...(T||[]).map((n=>({prop:"linkTarget",name:n})))]:[{prop:"pointId",name:null!=r?r:"undefined"}],{existing:c,missing:C}=a(g,S);if(C.length>0)return{missingRequiredColumns:C,missingOptionalColumns:[]};const A=[...m?[{prop:"pointSize",name:m}]:[],...l?[{prop:"pointColor",name:l}]:[],...$?[{prop:"pointLabel",name:$}]:[],...d?[{prop:"pointLabelWeight",name:d}]:[],...[...new Set(s)].map((n=>({prop:"pointIncludeColumns",name:n}))),...u&&E?[{prop:"pointX",name:u},{prop:"pointY",name:E}]:[]],{existing:R,missing:L}=a(A,S);await e.exec(`\n BEGIN;\n DROP SEQUENCE IF EXISTS ${i.Sequence} CASCADE;\n CREATE SEQUENCE ${i.Sequence} MINVALUE 0;\n CREATE TABLE ${n.PreparedPoints} (\n ${i.Id} VARCHAR,\n ${i.Idx} INT DEFAULT nextval('${i.Sequence}')\n );\n COMMIT;\n `.trim());const x=R.filter((n=>n!==i.Id)),N=x.map((i=>`ALTER TABLE ${n.PreparedPoints} ADD COLUMN IF NOT EXISTS "${i}" ${S.get(i)};`)).join("\n");await e.exec(N);const O=I&&T?[I,...T]:[r],k=`\n INSERT INTO ${n.PreparedPoints} (${i.Id}${x.length?", ":""}${x.join(", ")})\n SELECT DISTINCT ON (${i.Id}) *\n FROM (\n ${O.map((e=>`\n SELECT\n "${e}" AS ${i.Id},\n ${x.map((n=>`"${n}"`)).join(", ")}\n FROM ${n.RawPoints}\n WHERE "${e}" IS NOT NULL\n `)).join(" UNION ALL ")}\n ) AS combined_points\n `.trim();return await e.exec(k),o&&await e.logTable(n.PreparedPoints),{missingRequiredColumns:[],missingOptionalColumns:L}},s=async(e,t)=>{const{linkSource:r=i.Source,linkTargets:s=[i.Target],linkIncludeColumns:m=[],linkColor:l,linkWidth:$,linkArrow:d,linkStrength:u}=t;if(!(null==s?void 0:s.length))return{missingRequiredColumns:[],missingOptionalColumns:[]};const E=await p(e,n.RawLinks),I=[{prop:"linkSource",name:r},...s.map((n=>({prop:"linkTargets",name:n})))],{existing:T,missing:S}=a(I,E);if(S.length>0)return{missingRequiredColumns:S,missingOptionalColumns:[]};const g=[...l?[{prop:"linkColor",name:l}]:[],...$?[{prop:"linkWidth",name:$}]:[],...d?[{prop:"linkArrow",name:d}]:[],...u?[{prop:"linkStrength",name:u}]:[],...m.map((n=>({prop:"linkIncludeColumns",name:n})))],{existing:c,missing:C}=a(g,E);await e.exec(`\n CREATE TABLE IF NOT EXISTS ${n.PreparedLinks} (\n ${i.SourceIdx} INTEGER,\n ${i.TargetIdx} INTEGER,\n ${i.Source} VARCHAR,\n ${i.Target} VARCHAR\n ${c.length>0?`, ${c.map((n=>`"${n}" ${E.get(n)||"VARCHAR"}`)).join(",")}`:""}\n )`.trim()),await e.exec(`\n CREATE TEMP TABLE temp_points AS\n SELECT ${i.Id}, ${i.Idx}\n FROM ${n.PreparedPoints}\n `.trim());const A=s.map((e=>`\n SELECT\n LEAST(sp.${i.Idx}, tp.${i.Idx}) AS ${i.SourceIdx},\n GREATEST(sp.${i.Idx}, tp.${i.Idx}) AS ${i.TargetIdx},\n d."${r}" AS ${i.Source},\n d."${e}" AS ${i.Target}\n ${c.length>0?`,${c.map((n=>`d."${n}"`)).join(",")}`:""}\n FROM ${n.RawLinks} d\n JOIN temp_points sp ON sp.${i.Id} = d."${r}"::text\n JOIN temp_points tp ON tp.${i.Id} = d."${e}"::text\n `)).join(" UNION ALL ").trim();return await e.exec(`\n INSERT INTO ${n.PreparedLinks}\n ${A}\n `.trim()),await e.exec("DROP TABLE temp_points"),o&&await(null==e?void 0:e.logTable(n.PreparedLinks)),{missingRequiredColumns:[],missingOptionalColumns:C}};export{s as insertLinks,r as insertPoints};
import{Tables as n,Columns as i}from"../../enum.js";import{checkDevEnv as e,convertArrowToObject as t}from"../../utils/utils.js";const o=e(),p=async(n,i)=>{const e=await n.query(`DESCRIBE ${i}`);return new Map(t(e).map((n=>[n.column_name,n.column_type])))},a=(n,i)=>({existing:[...new Set(n.filter((n=>i.has(n.name))).map((n=>n.name)))],missing:n.filter((n=>!i.has(n.name)))}),r=async(e,t)=>{const{pointId:r,pointIncludeColumns:s=[],pointSize:m,pointColor:l,pointLabel:$,pointLabelWeight:d,pointX:u,pointY:E,linkSource:I,linkTargets:T}=t,S=await p(e,n.RawPoints),g=r?[{prop:"pointId",name:r}]:I&&T?[{prop:"linkSource",name:I},...(T||[]).map((n=>({prop:"linkTarget",name:n})))]:[{prop:"pointId",name:null!=r?r:"undefined"}],{existing:c,missing:C}=a(g,S);if(C.length>0)return{missingRequiredColumns:C,missingOptionalColumns:[]};const A=[...m?[{prop:"pointSize",name:m}]:[],...l?[{prop:"pointColor",name:l}]:[],...$?[{prop:"pointLabel",name:$}]:[],...d?[{prop:"pointLabelWeight",name:d}]:[],...[...new Set(s)].map((n=>({prop:"pointIncludeColumns",name:n}))),...u&&E?[{prop:"pointX",name:u},{prop:"pointY",name:E}]:[]],{existing:R,missing:L}=a(A,S);await e.exec(`\n BEGIN;\n DROP SEQUENCE IF EXISTS ${i.Sequence} CASCADE;\n CREATE SEQUENCE ${i.Sequence} MINVALUE 0;\n CREATE TABLE ${n.PreparedPoints} (\n ${i.Id} VARCHAR,\n ${i.Idx} INT DEFAULT nextval('${i.Sequence}')\n );\n COMMIT;\n `.trim());const x=R.filter((n=>n!==i.Id)),N=x.map((i=>`ALTER TABLE ${n.PreparedPoints} ADD COLUMN IF NOT EXISTS "${i}" ${S.get(i)};`)).join("\n");await e.exec(N);const O=I&&T?[I,...T]:[r],k=[i.Id,...x],w=`\n INSERT INTO ${n.PreparedPoints} (${k.map((n=>`"${n}"`)).join(", ")})\n SELECT DISTINCT ON (${i.Id}) *\n FROM (\n ${O.map((e=>`\n SELECT\n "${e}" AS ${i.Id},\n ${x.map((n=>`"${n}"`)).join(", ")}\n FROM ${n.RawPoints}\n WHERE "${e}" IS NOT NULL\n `)).join(" UNION ALL ")}\n ) AS combined_points\n `.trim();return await e.exec(w),o&&await e.logTable(n.PreparedPoints),{missingRequiredColumns:[],missingOptionalColumns:L}},s=async(e,t)=>{const{linkSource:r=i.Source,linkTargets:s=[i.Target],linkIncludeColumns:m=[],linkColor:l,linkWidth:$,linkArrow:d,linkStrength:u}=t;if(!(null==s?void 0:s.length))return{missingRequiredColumns:[],missingOptionalColumns:[]};const E=await p(e,n.RawLinks),I=[{prop:"linkSource",name:r},...s.map((n=>({prop:"linkTargets",name:n})))],{existing:T,missing:S}=a(I,E);if(S.length>0)return{missingRequiredColumns:S,missingOptionalColumns:[]};const g=[...l?[{prop:"linkColor",name:l}]:[],...$?[{prop:"linkWidth",name:$}]:[],...d?[{prop:"linkArrow",name:d}]:[],...u?[{prop:"linkStrength",name:u}]:[],...m.map((n=>({prop:"linkIncludeColumns",name:n})))],{existing:c,missing:C}=a(g,E);await e.exec(`\n CREATE TABLE IF NOT EXISTS ${n.PreparedLinks} (\n ${i.SourceIdx} INTEGER,\n ${i.TargetIdx} INTEGER,\n ${i.Source} VARCHAR,\n ${i.Target} VARCHAR\n ${c.length>0?`, ${c.map((n=>`"${n}" ${E.get(n)||"VARCHAR"}`)).join(",")}`:""}\n )`.trim()),await e.exec(`\n CREATE TEMP TABLE temp_points AS\n SELECT ${i.Id}, ${i.Idx}\n FROM ${n.PreparedPoints}\n `.trim());const A=s.map((e=>`\n SELECT\n LEAST(sp.${i.Idx}, tp.${i.Idx}) AS ${i.SourceIdx},\n GREATEST(sp.${i.Idx}, tp.${i.Idx}) AS ${i.TargetIdx},\n d."${r}" AS ${i.Source},\n d."${e}" AS ${i.Target}\n ${c.length>0?`,${c.map((n=>`d."${n}"`)).join(",")}`:""}\n FROM ${n.RawLinks} d\n JOIN temp_points sp ON sp.${i.Id} = d."${r}"::text\n JOIN temp_points tp ON tp.${i.Id} = d."${e}"::text\n `)).join(" UNION ALL ").trim();return await e.exec(`\n INSERT INTO ${n.PreparedLinks}\n ${A}\n `.trim()),await e.exec("DROP TABLE temp_points"),o&&await(null==e?void 0:e.logTable(n.PreparedLinks)),{missingRequiredColumns:[],missingOptionalColumns:C}};export{s as insertLinks,r as insertPoints};
//# sourceMappingURL=queries.js.map

@@ -17,3 +17,3 @@ import { MosaicClient, Param } from '@uwdata/mosaic-core';

accessor: string;
include: string[] | undefined;
include: () => string[];
onFiltered: (result: Table) => void;

@@ -60,2 +60,3 @@ coordinator: MosaicDBCoordinator;

publish(range: [number, number] | [Date, Date] | undefined): void;
reset(): void;
/**

@@ -62,0 +63,0 @@ * Retrieves the current histogram data by accessor without filtering.

@@ -1,2 +0,2 @@

import{MosaicClient as e}from"@uwdata/mosaic-core";import{Query as t,isBetween as r}from"@uwdata/mosaic-sql";class s extends e{constructor(e){super(e.filterBy),this._coordinator=e.coordinator,this._selection=e.filterBy,this._onFiltered=e.onFiltered,this._tableName=e.tableName,this._accessor=e.accessor,this._columnsToInclude=new Set(e.include),this._preventQuerying=!0}set preventQuerying(e){this._preventQuerying=e}get preventQuerying(){return this._preventQuerying}get _fieldsToQuery(){return[...new Set([this._accessor,...this._columnsToInclude])]}query(e=[]){return t.from(this._tableName).select(this._fieldsToQuery).where(e)}queryResult(e){return this._onFiltered(e),this}async updateAccessor(e){e&&(this._accessor=e)}publish(e){this._selection.update({source:this,predicate:e?r(this._accessor,e):"1=1"})}async getCurrentData(){this._selection.update({source:this,predicate:null});return await this._coordinator.query(this.query(this._selection.predicate(this)))}}export{s as HistogramClient};
import{MosaicClient as e}from"@uwdata/mosaic-core";import{Query as t,isBetween as s}from"@uwdata/mosaic-sql";class i extends e{constructor(e){super(e.filterBy),this._coordinator=e.coordinator,this._selection=e.filterBy,this._onFiltered=e.onFiltered,this._tableName=e.tableName,this._accessor=e.accessor,this._columnsToInclude=e.include,this._preventQuerying=!0}set preventQuerying(e){this._preventQuerying=e}get preventQuerying(){return this._preventQuerying}get _fieldsToQuery(){return[...new Set([this._accessor,...new Set(this._columnsToInclude())])]}query(e=[]){return t.from(this._tableName).select(this._fieldsToQuery).where(e)}queryResult(e){return this._onFiltered(e),this}async updateAccessor(e){e&&(this._accessor=e)}publish(e){this._selection.update({source:this,predicate:e?s(this._accessor,e):void 0})}reset(){this._selection.update({source:this,predicate:void 0}),this._selection=this._selection.remove(this)}async getCurrentData(){this._selection.update({source:this,predicate:null});return await this._coordinator.query(this.query(this._selection.predicate(this)))}}export{i as HistogramClient};
//# sourceMappingURL=histogram-client.js.map

@@ -14,3 +14,2 @@ import { Cosmograph } from '../cosmograph';

private _currentData?;
private _columnsToInclude;
private _isValidAccessor;

@@ -17,0 +16,0 @@ private _dataUpdatedHandler;

@@ -1,2 +0,2 @@

import{merge as t,Histogram as i}from"@cosmograph/ui";import{defaultCosmographHistogramConfig as s}from"./config.js";import{HistogramClient as e}from"./histogram-client.js";import{isTableExists as o,checkColumnsExist as a}from"../cosmograph/data-ops/misc.js";class r{constructor(e,o,a){this._columnsToInclude=[],this._isValidAccessor=!1,this._onBrush=(t,i)=>{var s,e;this._applyFilter(t),null===(e=(s=this._config).onSelection)||void 0===e||e.call(s,t,i)},this._onBarHover=(...t)=>{var i,s;null===(s=(i=this._config).onBarHover)||void 0===s||s.call(i,...t)},this._cosmograph=e,this._config=t(s,null!=a?a:{}),this._histogram=new i(o,this._createHistogramConfig(a)),this._filter=this._config.useLinksData?e.linksSelection:e.pointsSelection,this._dataUpdatedHandler=this._getData.bind(this),this._dataFilteredHandler=this._updateCrossfilteredData.bind(this),this._cosmograph.addEventListener("dataUpdated",this._dataUpdatedHandler),this._cosmograph.addEventListener("dataFiltered",this._dataFilteredHandler),this._initialize()}get pointAccessors(){const{pointId:t,pointIndex:i}=this._cosmograph.config;return t&&i?[t,i]:t?[t]:i?[i]:[]}get linkAccessors(){const{linkSourceIndex:t,linkTargetIndex:i}=this._cosmograph.config;return t&&i?[t,i]:t?[t]:i?[i]:[]}get tableName(){return this._config.useLinksData?this._cosmograph.linksTableName:this._cosmograph.pointsTableName}get accessor(){var t;return null!==(t=this._config.accessor)&&void 0!==t?t:s.accessor}setConfig(i){var e;const o=this._config;this._config=t(s,null!=i?i:{}),this._histogram.setConfig(this._createHistogramConfig(i)),this._config.accessor!==o.accessor&&(null===(e=this._client)||void 0===e||e.updateAccessor(this._config.accessor),this._getData(),this._updateData(),this.setSelection())}async _initialize(){await this._cosmograph.dataReady(),this._columnsToInclude=this._config.useLinksData?this.linkAccessors:this.pointAccessors,await this._createClient()}async _getData(){var t;if(!this._cosmograph.dbCoordinator)return;const i=await o(this._cosmograph.dbCoordinator,this.tableName);this._isValidAccessor=i&&await a(this._cosmograph.dbCoordinator,this.tableName,[this.accessor]),i&&this._isValidAccessor?(this._client&&(this._client.preventQuerying=!1),this._currentData=await(null===(t=this._client)||void 0===t?void 0:t.getCurrentData())):(this._currentData=void 0,this._client&&(this._client.preventQuerying=!0)),this._updateData()}async _createClient(){if(!this._cosmograph.dbCoordinator)return;const t={tableName:this.tableName,filterBy:this._filter,accessor:this.accessor,include:this._columnsToInclude,onFiltered:this._handleSelectionUpdate.bind(this),coordinator:this._cosmograph.dbCoordinator};this._client=new e(t),this._cosmograph.dbCoordinator.connect(this._client)}_createHistogramConfig(t){return{...t,events:{onBrush:this._onBrush.bind(this),onBarHover:this._onBarHover.bind(this)}}}_handleSelectionUpdate(t){this._config.accessor&&(this._config.useLinksData?this._cosmograph.onLinksFiltered(t):this._cosmograph.onPointsFiltered(t))}_updateData(){var t,i;if(this._currentData){const s=null===(i=null===(t=this._currentData)||void 0===t?void 0:t.getChild(this.accessor))||void 0===i?void 0:i.toArray();this._histogram.setHistogramData(s,this._config.customExtent),this._updateHighlightedBars(s)}else this._histogram.setHistogramData(void 0),this._updateHighlightedBars(void 0)}_updateCrossfilteredData(){var t,i;if(!this._currentData||!this._isValidAccessor)return;const s=this._cosmograph.crossfilter.intersection;if(this._cosmograph.isFilteringActive){const t=this._filterByIdx(this._currentData,s);this._config.highlightCrossfiltered&&this._updateHighlightedBars(t)}else{const s=null===(i=null===(t=this._currentData)||void 0===t?void 0:t.getChild(this.accessor))||void 0===i?void 0:i.toArray();this._updateHighlightedBars(s)}}_filterByIdx(t,i){var s,e;const{linkSourceIndex:o,linkTargetIndex:a,pointIndex:r}=this._cosmograph.config,n=t.numRows,h=[],c=t.getChild(this.accessor);let l,d=null;this._config.useLinksData?o&&a&&(l=t.getChild(o),d=t.getChild(a)):r&&(l=t.getChild(r));const g=null!==d,_=this._config.useLinksData?null===(e=null===(s=this._cosmograph.linksSelection.active)||void 0===s?void 0:s.predicate)||void 0===e?void 0:e.range:null;for(let t=0;t<n;t++){const s=null==l?void 0:l.get(t),e=g?null==d?void 0:d.get(t):void 0;if(i.has(s)||g&&i.has(e)){const i=null==c?void 0:c.get(t);(!g||_&&_[0]<=i&&i<=_[1]||!_)&&h.push(i)}}return h}_updateHighlightedBars(t){this._histogram.setHighlightedData(t)}_applyFilter(t){var i;null===(i=this._client)||void 0===i||i.publish(t)}getCurrentSelection(){var t;return null===(t=this._histogram)||void 0===t?void 0:t.getCurrentSelection()}getCurrentSelectionInPixels(){var t;return null===(t=this._histogram)||void 0===t?void 0:t.getCurrentSelectionInPixels()}getBarWidth(){return this._histogram.getBarWidth()}setSelection(t){this._histogram.setSelection(t)}getConfig(){return this._config}remove(){this._histogram.destroy(),this._cosmograph.removeEventListener("dataUpdated",this._dataUpdatedHandler),this._cosmograph.removeEventListener("dataFiltered",this._dataFilteredHandler)}}export{r as CosmographHistogram};
import{merge as t,Histogram as i}from"@cosmograph/ui";import{defaultCosmographHistogramConfig as s}from"./config.js";import{HistogramClient as e}from"./histogram-client.js";import{isTableExists as o,checkColumnsExist as a}from"../cosmograph/data-ops/misc.js";class r{constructor(e,o,a){this._isValidAccessor=!1,this._onBrush=(t,i)=>{var s,e;this._applyFilter(t),null===(e=(s=this._config).onSelection)||void 0===e||e.call(s,t,i)},this._onBarHover=(...t)=>{var i,s;null===(s=(i=this._config).onBarHover)||void 0===s||s.call(i,...t)},this._cosmograph=e,this._config=t(s,null!=a?a:{}),this._histogram=new i(o,this._createHistogramConfig(a)),this._filter=this._config.useLinksData?e.linksSelection:e.pointsSelection,this._dataUpdatedHandler=this._getData.bind(this),this._dataFilteredHandler=this._updateCrossfilteredData.bind(this),this._cosmograph.addEventListener("dataUpdated",this._dataUpdatedHandler),this._cosmograph.addEventListener("dataFiltered",this._dataFilteredHandler),this._initialize()}get pointAccessors(){const{pointId:t,pointIndex:i}=this._cosmograph.config;return t&&i?[t,i]:t?[t]:i?[i]:[]}get linkAccessors(){const{linkSourceIndex:t,linkTargetIndex:i}=this._cosmograph.config;return t&&i?[t,i]:t?[t]:i?[i]:[]}get tableName(){return this._config.useLinksData?this._cosmograph.linksTableName:this._cosmograph.pointsTableName}get accessor(){var t;return null!==(t=this._config.accessor)&&void 0!==t?t:s.accessor}setConfig(i){var e;const o=this._config;this._config=t(s,null!=i?i:{}),this._histogram.setConfig(this._createHistogramConfig(i)),this._config.accessor!==o.accessor&&(null===(e=this._client)||void 0===e||e.updateAccessor(this._config.accessor),this._getData(),this._updateData(),this.setSelection())}async _initialize(){await this._createClient(),(this._cosmograph.stats.linksCount||this._cosmograph.stats.pointsCount)&&await this._getData()}async _getData(){var t;if(await this._cosmograph.dataReady(),this._histogram.setLoadingState(),!this._cosmograph.dbCoordinator)return;const i=await o(this._cosmograph.dbCoordinator,this.tableName);this._isValidAccessor=i&&await a(this._cosmograph.dbCoordinator,this.tableName,[this.accessor]),i&&this._isValidAccessor?(this._client&&(this._client.preventQuerying=!1),this._currentData=await(null===(t=this._client)||void 0===t?void 0:t.getCurrentData())):(this._currentData=void 0,this._client&&(this._client.preventQuerying=!0)),this._updateData()}async _createClient(){if(await this._cosmograph.dbReady(),!this._cosmograph.dbCoordinator)return;const t={tableName:this.tableName,filterBy:this._filter,accessor:this.accessor,include:()=>this._config.useLinksData?this.linkAccessors:this.pointAccessors,onFiltered:this._handleSelectionUpdate.bind(this),coordinator:this._cosmograph.dbCoordinator};this._client=new e(t),this._cosmograph.dbCoordinator.connect(this._client)}_createHistogramConfig(t){return{...t,events:{onBrush:this._onBrush.bind(this),onBarHover:this._onBarHover.bind(this)}}}_handleSelectionUpdate(t){this._config.accessor&&(this._config.useLinksData?this._cosmograph.onLinksFiltered(t):this._cosmograph.onPointsFiltered(t))}_updateData(){var t,i;if(this._currentData){const s=null===(i=null===(t=this._currentData)||void 0===t?void 0:t.getChild(this.accessor))||void 0===i?void 0:i.toArray();this._histogram.setHistogramData(s,this._config.customExtent),this._updateHighlightedBars(s)}else this._histogram.setHistogramData(void 0),this._updateHighlightedBars(void 0)}_updateCrossfilteredData(){var t,i;if(!this._currentData||!this._isValidAccessor)return;const s=this._cosmograph.crossfilter.intersection;if(this._cosmograph.isFilteringActive){const t=this._filterByIdx(this._currentData,s);this._config.highlightCrossfiltered&&this._updateHighlightedBars(t)}else{const s=null===(i=null===(t=this._currentData)||void 0===t?void 0:t.getChild(this.accessor))||void 0===i?void 0:i.toArray();this._updateHighlightedBars(s)}}_filterByIdx(t,i){var s,e;const{linkSourceIndex:o,linkTargetIndex:a,pointIndex:r}=this._cosmograph.config,n=t.numRows,h=[],c=t.getChild(this.accessor);let l,d=null;this._config.useLinksData?o&&a&&(l=t.getChild(o),d=t.getChild(a)):r&&(l=t.getChild(r));const g=null!==d,_=this._config.useLinksData?null===(e=null===(s=this._cosmograph.linksSelection.active)||void 0===s?void 0:s.predicate)||void 0===e?void 0:e.range:null;for(let t=0;t<n;t++){const s=null==l?void 0:l.get(t),e=g?null==d?void 0:d.get(t):void 0;if(i.has(s)||g&&i.has(e)){const i=null==c?void 0:c.get(t);(!g||_&&_[0]<=i&&i<=_[1]||!_)&&h.push(i)}}return h}_updateHighlightedBars(t){this._histogram.setHighlightedData(t)}_applyFilter(t){var i;null===(i=this._client)||void 0===i||i.publish(t)}getCurrentSelection(){var t;return null===(t=this._histogram)||void 0===t?void 0:t.getCurrentSelection()}getCurrentSelectionInPixels(){var t;return null===(t=this._histogram)||void 0===t?void 0:t.getCurrentSelectionInPixels()}getBarWidth(){return this._histogram.getBarWidth()}setSelection(t){this._histogram.setSelection(t)}getConfig(){return this._config}remove(){var t;null===(t=this._client)||void 0===t||t.reset(),this._histogram.destroy(),this._cosmograph.removeEventListener("dataUpdated",this._dataUpdatedHandler),this._cosmograph.removeEventListener("dataFiltered",this._dataFilteredHandler)}}export{r as CosmographHistogram};
//# sourceMappingURL=index.js.map

@@ -55,2 +55,3 @@ import { CosmographRangeColorLegendConfig } from './config';

remove(): void;
private _update;
private _createLegendConfig;

@@ -57,0 +58,0 @@ private _getExtent;

@@ -1,2 +0,2 @@

import{RangeColorLegend as i,merge as e}from"@cosmograph/ui";import{defaultCosmographRangeColorLegendConfig as t}from"./config.js";import s from"./style.module.css.js";class n{constructor(e,t,n){this._config={},this._uiConfig={},this._isInternalSelection=!1,this._onClick=(...i)=>{var e,t;null===(t=(e=this._config).onClick)||void 0===t||t.call(e,...i)},this._onHover=(...i)=>{var e,t;null===(t=(e=this._config).onHover)||void 0===t||t.call(e,...i)},this._onMaxClick=(...i)=>{var e,t;null===(t=(e=this._config).onMaxClick)||void 0===t||t.call(e,...i),this._selectOnClick(i[1])},this._onMinClick=(...i)=>{var e,t;null===(t=(e=this._config).onMinClick)||void 0===t||t.call(e,...i),this._selectOnClick(i[1],!0)},this._selectOnClick=(i,e=!1)=>{var t,n,o,l,c,h,a;if(!i)return;if(!this._config.selectOnClick)return;const r=e?"min":"max",_=e?"max":"min";if(this._selected===r)null===(t=this._cosmograph.selectionClient)||void 0===t||t.publish(void 0),null===(n=this._legend.extentElements)||void 0===n||n[r].classList.remove(s.selected),null===(o=this._legend.extentElements)||void 0===o||o[_].classList.remove(s.unselected),this._selected=void 0;else{if(null===(l=this._legend.extentElements)||void 0===l||l[r].classList.remove(s.unselected),null===(c=this._legend.extentElements)||void 0===c||c[r].classList.add(s.selected),null===(h=this._legend.extentElements)||void 0===h||h[_].classList.remove(s.selected),null===(a=this._legend.extentElements)||void 0===a||a[_].classList.add(s.unselected),this.accessor){this._isInternalSelection=!0;(this._config.useLinksData?this._cosmograph.getPointIndicesByLinksColumnValues.bind(this._cosmograph):this._cosmograph.getPointIndiciesByColumnValues.bind(this._cosmograph))(this.accessor,[i]).then((i=>{var e;null===(e=this._cosmograph.selectionClient)||void 0===e||e.publish(i)}))}this._selected=r}},this._cosmograph=e,this._cosmograph.addEventListener("dataFiltered",this._resetAllSelections.bind(this)),this._legend=new i(t),this._initialize(n)}async _initialize(i){await this._cosmograph.graphReady(),this.setConfig(i)}get accessor(){return this._config.useLinksData?this._cosmograph.config.linkColor:this._cosmograph.config.pointColor}async setConfig(i){var s;if(await this._cosmograph.graphReady(),!this._cosmograph.dbCoordinator)return;const n=this._config;this._config=e(t,null!=i?i:{}),this._uiConfig.extent=this._config.overrideColors,this._config.overrideColors&&this._config.overrideColors===n.overrideColors&&this._config.useLinksData===n.useLinksData||(this._config.useLinksData!==n.useLinksData&&this._resetAllSelections(),await this._getExtent(),this._uiConfig.extent&&this._legend.show()),this._config.label="function"==typeof this._config.label?this._config.label(this.accessor):null!==(s=this._config.label)&&void 0!==s?s:this.accessor,this._legend.setConfig(this._createLegendConfig({...this._config,...this._uiConfig}))}getConfig(){return this._config}remove(){this._legend.destroy(),this._cosmograph.removeEventListener("dataFiltered",this._resetAllSelections.bind(this))}_createLegendConfig(i){return{...i,events:{onClick:this._onClick.bind(this),onHover:this._onHover.bind(this),onMaxClick:this._onMaxClick.bind(this),onMinClick:this._onMinClick.bind(this)}}}async _getExtent(){var i;if(this._config.overrideColors)return void(this._uiConfig.extentLabels=this._config.extentLabels);await this._cosmograph.dataReady();const e=this._config.useLinksData?this._cosmograph.stats.linksSummary:this._cosmograph.stats.pointsSummary,t=null==e?void 0:e.find((i=>i.column_name===this.accessor));if(!t)return;const{min:s,max:n}=t,o=[+s,+n];let l,c=[];if(this._config.useLinksData?l=this._cosmograph.config.linkColorFn:this._cosmograph.config.pointColorFn&&(l=this._cosmograph.config.pointColorFn),l){const i=this._config.steps;c=Array.from({length:i},((e,t)=>l(o[0]+t/(i-1)*(o[1]-o[0])))).filter(Boolean)}this._uiConfig.extent=c.length?c:void 0,this._uiConfig.extentLabels=null!==(i=this._config.extentLabels)&&void 0!==i?i:[+s,+n]}_resetAllSelections(){var i,e,t;!this._isInternalSelection&&this._selected?(null===(i=this._cosmograph.selectionClient)||void 0===i||i.publish(void 0),null===(e=this._legend.extentElements)||void 0===e||e.min.classList.remove(s.selected,s.unselected),null===(t=this._legend.extentElements)||void 0===t||t.max.classList.remove(s.selected,s.unselected),this._selected=void 0):this._isInternalSelection&&(this._isInternalSelection=!1)}}export{n as CosmographRangeColorLegend};
import{RangeColorLegend as i,merge as e}from"@cosmograph/ui";import{defaultCosmographRangeColorLegendConfig as t}from"./config.js";import s from"./style.module.css.js";class n{constructor(e,t,n){this._config={},this._uiConfig={},this._isInternalSelection=!1,this._onClick=(...i)=>{var e,t;null===(t=(e=this._config).onClick)||void 0===t||t.call(e,...i)},this._onHover=(...i)=>{var e,t;null===(t=(e=this._config).onHover)||void 0===t||t.call(e,...i)},this._onMaxClick=(...i)=>{var e,t;null===(t=(e=this._config).onMaxClick)||void 0===t||t.call(e,...i),this._selectOnClick(i[1])},this._onMinClick=(...i)=>{var e,t;null===(t=(e=this._config).onMinClick)||void 0===t||t.call(e,...i),this._selectOnClick(i[1],!0)},this._selectOnClick=(i,e=!1)=>{var t,n,o,l,c,h,a;if(!i)return;if(!this._config.selectOnClick)return;const r=e?"min":"max",_=e?"max":"min";if(this._selected===r)null===(t=this._cosmograph.selectionClient)||void 0===t||t.publish(void 0),null===(n=this._legend.extentElements)||void 0===n||n[r].classList.remove(s.selected),null===(o=this._legend.extentElements)||void 0===o||o[_].classList.remove(s.unselected),this._selected=void 0;else{if(null===(l=this._legend.extentElements)||void 0===l||l[r].classList.remove(s.unselected),null===(c=this._legend.extentElements)||void 0===c||c[r].classList.add(s.selected),null===(h=this._legend.extentElements)||void 0===h||h[_].classList.remove(s.selected),null===(a=this._legend.extentElements)||void 0===a||a[_].classList.add(s.unselected),this.accessor){this._isInternalSelection=!0;(this._config.useLinksData?this._cosmograph.getPointIndicesByLinksColumnValues.bind(this._cosmograph):this._cosmograph.getPointIndicesByColumnValues.bind(this._cosmograph))(this.accessor,[i]).then((i=>{var e;null===(e=this._cosmograph.selectionClient)||void 0===e||e.publish(i)}))}this._selected=r}},this._cosmograph=e,this._cosmograph.addEventListener("dataUpdated",this._update.bind(this)),this._cosmograph.addEventListener("dataFiltered",this._resetAllSelections.bind(this)),this._legend=new i(t),this._initialize(n)}async _initialize(i){await this.setConfig(i)}get accessor(){return this._config.useLinksData?this._cosmograph.config.linkColor:this._cosmograph.config.pointColor}async setConfig(i){var s;if(await this._cosmograph.graphReady(),!this._cosmograph.dbCoordinator)return;const n=this._config;this._config=e(t,null!=i?i:{}),this._uiConfig.extent=this._config.overrideColors,this._config.overrideColors&&this._config.overrideColors===n.overrideColors&&this._config.useLinksData===n.useLinksData||(this._config.useLinksData!==n.useLinksData&&this._resetAllSelections(),await this._getExtent(),this._uiConfig.extent&&this._legend.show()),this._config.label="function"==typeof this._config.label?this._config.label(this.accessor):null!==(s=this._config.label)&&void 0!==s?s:this.accessor,this._legend.setConfig(this._createLegendConfig({...this._config,...this._uiConfig}))}getConfig(){return this._config}remove(){this._legend.destroy(),this._cosmograph.removeEventListener("dataFiltered",this._resetAllSelections.bind(this))}_update(){this.setConfig(this._config)}_createLegendConfig(i){return{...i,events:{onClick:this._onClick.bind(this),onHover:this._onHover.bind(this),onMaxClick:this._onMaxClick.bind(this),onMinClick:this._onMinClick.bind(this)}}}async _getExtent(){var i;if(this._config.overrideColors)return void(this._uiConfig.extentLabels=this._config.extentLabels);const e=this._config.useLinksData?this._cosmograph.stats.linksSummary:this._cosmograph.stats.pointsSummary,t=null==e?void 0:e.find((i=>i.column_name===this.accessor));if(!t)return;const{min:s,max:n}=t,o=[+s,+n];let l,c=[];if(this._config.useLinksData?l=this._cosmograph.config.linkColorFn:this._cosmograph.config.pointColorFn&&(l=this._cosmograph.config.pointColorFn),l){const i=this._config.steps;c=Array.from({length:i},((e,t)=>l(o[0]+t/(i-1)*(o[1]-o[0])))).filter(Boolean)}this._uiConfig.extent=c.length?c:void 0,this._uiConfig.extentLabels=null!==(i=this._config.extentLabels)&&void 0!==i?i:[+s,+n]}_resetAllSelections(){var i,e,t;!this._isInternalSelection&&this._selected?(null===(i=this._cosmograph.selectionClient)||void 0===i||i.publish(void 0),null===(e=this._legend.extentElements)||void 0===e||e.min.classList.remove(s.selected,s.unselected),null===(t=this._legend.extentElements)||void 0===t||t.max.classList.remove(s.selected,s.unselected),this._selected=void 0):this._isInternalSelection&&(this._isInternalSelection=!1)}}export{n as CosmographRangeColorLegend};
//# sourceMappingURL=index.js.map

@@ -1,2 +0,2 @@

import e from'./../../../../ext/rollup-plugin-styles/dist/runtime/inject-css.js';var l=".style_module_selected__91af67ac{filter:brightness(1.2)}.style_module_unselected__91af67ac{filter:brightness(.5);opacity:.7}",s={selected:"style_module_selected__91af67ac",unselected:"style_module_unselected__91af67ac"};e(l,{});export{l as css,s as default};
import e from'./../../../../ext/rollup-plugin-styles/dist/runtime/inject-css.js';var l=".style_module_selected__12a865d0{filter:brightness(1.2)}.style_module_unselected__12a865d0{filter:brightness(.5);opacity:.7}",s={selected:"style_module_selected__12a865d0",unselected:"style_module_unselected__12a865d0"};e(l,{});export{l as css,s as default};
//# sourceMappingURL=style.module.css.js.map

@@ -62,2 +62,3 @@ import { CosmographSizeLegendConfig } from './config';

show(): void;
private _update;
private _createLegendConfig;

@@ -64,0 +65,0 @@ private _getExtent;

@@ -1,2 +0,2 @@

import{SizeLegend as i,merge as e}from"@cosmograph/ui";import{defaultCosmographSizeLegendConfig as t}from"./config.js";import s from"./style.module.css.js";class n{constructor(e,t,n){this._config={},this._uiConfig={},this._isInternalSelection=!1,this._onClick=(...i)=>{var e,t;null===(t=(e=this._config).onClick)||void 0===t||t.call(e,...i)},this._onHover=(...i)=>{var e,t;null===(t=(e=this._config).onHover)||void 0===t||t.call(e,...i)},this._onMaxClick=(...i)=>{var e,t;null===(t=(e=this._config).onMaxClick)||void 0===t||t.call(e,...i),this._selectOnClick(i[1])},this._onMinClick=(...i)=>{var e,t;null===(t=(e=this._config).onMinClick)||void 0===t||t.call(e,...i),this._selectOnClick(i[1],!0)},this._selectOnClick=(i,e=!1)=>{var t,n,o,l,h,a,c;if(!i||!this._config.selectOnClick)return;const d=e?"min":"max",_=e?"max":"min";if(this._selected===d)null===(t=this._cosmograph.selectionClient)||void 0===t||t.publish(void 0),null===(n=this._legend.sizeElements)||void 0===n||n[d].classList.remove(s.selected),null===(o=this._legend.sizeElements)||void 0===o||o[_].classList.remove(s.unselected),this._selected=void 0;else{if(null===(l=this._legend.sizeElements)||void 0===l||l[d].classList.remove(s.unselected),null===(h=this._legend.sizeElements)||void 0===h||h[d].classList.add(s.selected),null===(a=this._legend.sizeElements)||void 0===a||a[_].classList.remove(s.selected),null===(c=this._legend.sizeElements)||void 0===c||c[_].classList.add(s.unselected),this.accessor){this._isInternalSelection=!0;(this._config.useLinksData?this._cosmograph.getPointIndicesByLinksColumnValues.bind(this._cosmograph):this._cosmograph.getPointIndiciesByColumnValues.bind(this._cosmograph))(this.accessor,[i]).then((i=>{var e;null===(e=this._cosmograph.selectionClient)||void 0===e||e.publish(i)}))}this._selected=d}},this._onSizeScaleUpdated=()=>{this._updateSizeMultiplier(),this._updateLegendVisibility(),this._legend.setConfig({...this._config,...this._uiConfig})},this._cosmograph=e,this._legend=new i(t),this._initialize(n),this._cosmograph.addEventListener("dataFiltered",this._resetAllSelections.bind(this)),this._cosmograph.addEventListener("pointSizeScaleUpdated",this._onSizeScaleUpdated),this._cosmograph.addEventListener("linkWidthScaleUpdated",this._onSizeScaleUpdated)}async _initialize(i){await this._cosmograph.graphReady(),this.setConfig(i)}get accessor(){return this._config.useLinksData?this._cosmograph.config.linkWidth:this._cosmograph.config.pointSize}async setConfig(i){var s;await this._cosmograph.graphReady();const n=this._config;this._config=e(t,null!=i?i:{}),this._uiConfig.extent=this._config.overrideExtent,this._config.overrideExtent&&this._config.overrideExtent===n.overrideExtent&&this._config.useLinksData===n.useLinksData||(this._config.useLinksData!==n.useLinksData&&this._resetAllSelections(),await this._getExtent()),this._updateSizeMultiplier(),this._uiConfig.form=this._config.useLinksData?"line":"point",this._config.useLinksData!==n.useLinksData&&this._updateLegendVisibility(),this._config.label="function"==typeof this._config.label?this._config.label(this.accessor):null!==(s=this._config.label)&&void 0!==s?s:this.accessor,this._legend.setConfig(this._createLegendConfig({...this._config,...this._uiConfig}))}getConfig(){return this._config}remove(){this._legend.destroy(),this._cosmograph.removeEventListener("dataFiltered",this._resetAllSelections.bind(this)),this._cosmograph.removeEventListener("pointSizeScaleUpdated",this._onSizeScaleUpdated),this._cosmograph.removeEventListener("linkWidthScaleUpdated",this._onSizeScaleUpdated)}hide(){this._legend.hide()}show(){this._legend.show()}_createLegendConfig(i){return{...i,events:{onClick:this._onClick.bind(this),onHover:this._onHover.bind(this),onMaxClick:this._onMaxClick.bind(this),onMinClick:this._onMinClick.bind(this)}}}async _getExtent(){var i;if(this._config.overrideExtent)return void(this._uiConfig.extentLabels=this._config.extentLabels);await this._cosmograph.dataReady();const e=this._config.useLinksData?this._cosmograph.stats.linksSummary:this._cosmograph.stats.pointsSummary,t=null==e?void 0:e.find((i=>i.column_name===this.accessor));if(!t)return;const{min:s,max:n}=t;let o,l=[+s,+n];this._config.useLinksData?o=this._cosmograph.config.linkWidthFn:this._cosmograph.config.pointSizeFn&&(o=this._cosmograph.config.pointSizeFn),o&&(l=l.map((i=>+o(i)))),this._uiConfig.extent=l.filter(Boolean).length?l:void 0,this._uiConfig.extentLabels=null!==(i=this._config.extentLabels)&&void 0!==i?i:[+s,+n]}_resetAllSelections(){var i,e,t;!this._isInternalSelection&&this._selected?(null===(i=this._cosmograph.selectionClient)||void 0===i||i.publish(void 0),null===(e=this._legend.sizeElements)||void 0===e||e.min.classList.remove(s.selected,s.unselected),null===(t=this._legend.sizeElements)||void 0===t||t.max.classList.remove(s.selected,s.unselected),this._selected=void 0):this._isInternalSelection&&(this._isInternalSelection=!1)}_updateSizeMultiplier(){var i,e,t;this._config.useLinksData?this._uiConfig.sizeMultiplier=null!==(i=this._cosmograph.config.linkWidthScale)&&void 0!==i?i:1:!1!==this._cosmograph.config.scalePointsOnZoom?this._uiConfig.sizeMultiplier=(null!==(e=this._cosmograph.config.pointSizeScale)&&void 0!==e?e:1)*this._cosmograph.getZoomLevel():this._uiConfig.sizeMultiplier=null!==(t=this._cosmograph.config.pointSizeScale)&&void 0!==t?t:1}_updateLegendVisibility(){var i,e;if(this._uiConfig.extent){const t=(null!==(e=null===(i=this._uiConfig)||void 0===i?void 0:i.sizeMultiplier)&&void 0!==e?e:1)*this._uiConfig.extent[1];this._config.hideWhenSizeMoreThan&&this._config.hideWhenSizeMoreThan<t?this._legend.hide():this._legend.show()}}}export{n as CosmographSizeLegend};
import{SizeLegend as i,merge as e}from"@cosmograph/ui";import{defaultCosmographSizeLegendConfig as t}from"./config.js";import s from"./style.module.css.js";class n{constructor(e,t,n){this._config={},this._uiConfig={},this._isInternalSelection=!1,this._onClick=(...i)=>{var e,t;null===(t=(e=this._config).onClick)||void 0===t||t.call(e,...i)},this._onHover=(...i)=>{var e,t;null===(t=(e=this._config).onHover)||void 0===t||t.call(e,...i)},this._onMaxClick=(...i)=>{var e,t;null===(t=(e=this._config).onMaxClick)||void 0===t||t.call(e,...i),this._selectOnClick(i[1])},this._onMinClick=(...i)=>{var e,t;null===(t=(e=this._config).onMinClick)||void 0===t||t.call(e,...i),this._selectOnClick(i[1],!0)},this._selectOnClick=(i,e=!1)=>{var t,n,o,l,h,c,a;if(!i||!this._config.selectOnClick)return;const d=e?"min":"max",_=e?"max":"min";if(this._selected===d)null===(t=this._cosmograph.selectionClient)||void 0===t||t.publish(void 0),null===(n=this._legend.sizeElements)||void 0===n||n[d].classList.remove(s.selected),null===(o=this._legend.sizeElements)||void 0===o||o[_].classList.remove(s.unselected),this._selected=void 0;else{if(null===(l=this._legend.sizeElements)||void 0===l||l[d].classList.remove(s.unselected),null===(h=this._legend.sizeElements)||void 0===h||h[d].classList.add(s.selected),null===(c=this._legend.sizeElements)||void 0===c||c[_].classList.remove(s.selected),null===(a=this._legend.sizeElements)||void 0===a||a[_].classList.add(s.unselected),this.accessor){this._isInternalSelection=!0;(this._config.useLinksData?this._cosmograph.getPointIndicesByLinksColumnValues.bind(this._cosmograph):this._cosmograph.getPointIndicesByColumnValues.bind(this._cosmograph))(this.accessor,[i]).then((i=>{var e;null===(e=this._cosmograph.selectionClient)||void 0===e||e.publish(i)}))}this._selected=d}},this._onSizeScaleUpdated=()=>{this._updateSizeMultiplier(),this._updateLegendVisibility(),this._legend.setConfig({...this._config,...this._uiConfig})},this._cosmograph=e,this._legend=new i(t),this._initialize(n),this._cosmograph.addEventListener("dataFiltered",this._resetAllSelections.bind(this)),this._cosmograph.addEventListener("dataUpdated",this._update.bind(this)),this._cosmograph.addEventListener("pointSizeScaleUpdated",this._onSizeScaleUpdated),this._cosmograph.addEventListener("linkWidthScaleUpdated",this._onSizeScaleUpdated)}async _initialize(i){await this.setConfig(i)}get accessor(){return this._config.useLinksData?this._cosmograph.config.linkWidth:this._cosmograph.config.pointSize}async setConfig(i){var s;await this._cosmograph.graphReady();const n=this._config;this._config=e(t,null!=i?i:{}),this._uiConfig.extent=this._config.overrideExtent,this._config.overrideExtent&&this._config.overrideExtent===n.overrideExtent&&this._config.useLinksData===n.useLinksData||(this._config.useLinksData!==n.useLinksData&&this._resetAllSelections(),await this._getExtent()),this._updateSizeMultiplier(),this._uiConfig.form=this._config.useLinksData?"line":"point",this._config.useLinksData!==n.useLinksData&&this._updateLegendVisibility(),this._config.label="function"==typeof this._config.label?this._config.label(this.accessor):null!==(s=this._config.label)&&void 0!==s?s:this.accessor,this._legend.setConfig(this._createLegendConfig({...this._config,...this._uiConfig}))}getConfig(){return this._config}remove(){this._legend.destroy(),this._cosmograph.removeEventListener("dataFiltered",this._resetAllSelections.bind(this)),this._cosmograph.removeEventListener("pointSizeScaleUpdated",this._onSizeScaleUpdated),this._cosmograph.removeEventListener("linkWidthScaleUpdated",this._onSizeScaleUpdated)}hide(){this._legend.hide()}show(){this._legend.show()}_update(){this.setConfig(this._config)}_createLegendConfig(i){return{...i,events:{onClick:this._onClick.bind(this),onHover:this._onHover.bind(this),onMaxClick:this._onMaxClick.bind(this),onMinClick:this._onMinClick.bind(this)}}}async _getExtent(){var i;if(this._config.overrideExtent)return void(this._uiConfig.extentLabels=this._config.extentLabels);const e=this._config.useLinksData?this._cosmograph.stats.linksSummary:this._cosmograph.stats.pointsSummary,t=null==e?void 0:e.find((i=>i.column_name===this.accessor));if(!t)return;const{min:s,max:n}=t;let o,l=[+s,+n];this._config.useLinksData?o=this._cosmograph.config.linkWidthFn:this._cosmograph.config.pointSizeFn&&(o=this._cosmograph.config.pointSizeFn),o&&(l=l.map((i=>+o(i)))),this._uiConfig.extent=l.filter(Boolean).length?l:void 0,this._uiConfig.extentLabels=null!==(i=this._config.extentLabels)&&void 0!==i?i:[+s,+n]}_resetAllSelections(){var i,e,t;!this._isInternalSelection&&this._selected?(null===(i=this._cosmograph.selectionClient)||void 0===i||i.publish(void 0),null===(e=this._legend.sizeElements)||void 0===e||e.min.classList.remove(s.selected,s.unselected),null===(t=this._legend.sizeElements)||void 0===t||t.max.classList.remove(s.selected,s.unselected),this._selected=void 0):this._isInternalSelection&&(this._isInternalSelection=!1)}_updateSizeMultiplier(){var i,e,t;this._config.useLinksData?this._uiConfig.sizeMultiplier=null!==(i=this._cosmograph.config.linkWidthScale)&&void 0!==i?i:1:!1!==this._cosmograph.config.scalePointsOnZoom?this._uiConfig.sizeMultiplier=(null!==(e=this._cosmograph.config.pointSizeScale)&&void 0!==e?e:1)*this._cosmograph.getZoomLevel():this._uiConfig.sizeMultiplier=null!==(t=this._cosmograph.config.pointSizeScale)&&void 0!==t?t:1}_updateLegendVisibility(){var i,e;if(this._uiConfig.extent){const t=(null!==(e=null===(i=this._uiConfig)||void 0===i?void 0:i.sizeMultiplier)&&void 0!==e?e:1)*this._uiConfig.extent[1];this._config.hideWhenSizeMoreThan&&this._config.hideWhenSizeMoreThan<t?this._legend.hide():this._legend.show()}}}export{n as CosmographSizeLegend};
//# sourceMappingURL=index.js.map

@@ -13,3 +13,2 @@ import { Cosmograph } from '../cosmograph';

private _currentData?;
private _columnsToInclude;
private _isValidAccessor;

@@ -16,0 +15,0 @@ private _dataUpdatedHandler;

@@ -1,2 +0,2 @@

import{merge as i,Timeline as t}from"@cosmograph/ui";import{defaultCosmographTimelineConfig as e}from"./config.js";import{HistogramClient as s}from"../histogram/histogram-client.js";import{isTableExists as n,checkColumnsExist as o}from"../cosmograph/data-ops/misc.js";class a{constructor(s,n,o){this._columnsToInclude=[],this._isValidAccessor=!1,this._onBrush=(i,t)=>{var e,s;this._applyFilter(i),null===(s=(e=this._config).onSelection)||void 0===s||s.call(e,i,t)},this._onBarHover=(...i)=>{var t,e;null===(e=(t=this._config).onBarHover)||void 0===e||e.call(t,...i)},this._onAnimationPlay=(...i)=>{var t,e;null===(e=(t=this._config).onAnimationPlay)||void 0===e||e.call(t,...i)},this._onAnimationPause=(...i)=>{var t,e;null===(e=(t=this._config).onAnimationPause)||void 0===e||e.call(t,...i)},this.playAnimation=()=>{this._timeline.playAnimation()},this.pauseAnimation=()=>{this._timeline.pauseAnimation()},this.stopAnimation=()=>{this._timeline.stopAnimation()},this._cosmograph=s,this._config=i(e,null!=o?o:{}),this._timeline=new t(n,this._createTimelineConfig(o)),this._filter=this._config.useLinksData?s.linksSelection:s.pointsSelection,this._dataUpdatedHandler=this._getData.bind(this),this._dataFilteredHandler=this._updateCrossfilteredData.bind(this),this._cosmograph.addEventListener("dataUpdated",this._dataUpdatedHandler),this._cosmograph.addEventListener("dataFiltered",this._dataFilteredHandler),this._initialize()}get pointAccessors(){const{pointId:i,pointIndex:t}=this._cosmograph.config;return i&&t?[i,t]:i?[i]:t?[t]:[]}get linkAccessors(){const{linkSourceIndex:i,linkTargetIndex:t}=this._cosmograph.config;return i&&t?[i,t]:i?[i]:t?[t]:[]}get accessor(){var i;return null!==(i=this._config.accessor)&&void 0!==i?i:e.accessor}get tableName(){return this._config.useLinksData?this._cosmograph.linksTableName:this._cosmograph.pointsTableName}setConfig(t){var s;const n=this._config;this._config=i(e,null!=t?t:{}),this._timeline.setConfig(this._createTimelineConfig(t)),this._config.accessor!==n.accessor&&(null===(s=this._client)||void 0===s||s.updateAccessor(this._config.accessor),this._getData(),this._updateData(),this.setSelection())}async _initialize(){await this._cosmograph.dataReady(),this._columnsToInclude=this._config.useLinksData?this.linkAccessors:this.pointAccessors,await this._createClient()}async _getData(){var i;if(!this._cosmograph.dbCoordinator)return;const t=await n(this._cosmograph.dbCoordinator,this.tableName);this._isValidAccessor=t&&await o(this._cosmograph.dbCoordinator,this.tableName,[this.accessor]),t&&this._isValidAccessor?(this._client&&(this._client.preventQuerying=!1),this._currentData=await(null===(i=this._client)||void 0===i?void 0:i.getCurrentData())):(this._currentData=void 0,this._client&&(this._client.preventQuerying=!0)),this._updateData()}async _createClient(){if(!this._cosmograph.dbCoordinator)return;const i={tableName:this.tableName,filterBy:this._filter,accessor:this.accessor,include:this._columnsToInclude,onFiltered:this._handleSelectionUpdate.bind(this),coordinator:this._cosmograph.dbCoordinator};this._client=new s(i),this._cosmograph.dbCoordinator.connect(this._client)}_createTimelineConfig(i){return{...i,events:{onBrush:this._onBrush.bind(this),onBarHover:this._onBarHover.bind(this),onAnimationPlay:this._onAnimationPlay.bind(this),onAnimationPause:this._onAnimationPause.bind(this)}}}_handleSelectionUpdate(i){this._config.accessor&&(this._config.useLinksData?this._cosmograph.onLinksFiltered(i):this._cosmograph.onPointsFiltered(i))}_updateData(){var i,t;if(this._currentData){let e=null===(t=null===(i=this._currentData)||void 0===i?void 0:i.getChild(this.accessor))||void 0===t?void 0:t.toArray();e instanceof BigInt64Array&&(e=Array.from(e,(i=>Number(i)))),this._timeline.setTimeData(e,this._config.customExtent),this._updateHighlightedBars(e)}else this._timeline.setTimeData(void 0),this._updateHighlightedBars(void 0)}_updateCrossfilteredData(){var i,t;if(!this._currentData||!this._isValidAccessor)return;const e=this._cosmograph.crossfilter.intersection;if(this._cosmograph.isFilteringActive){const i=this._filterByIdx(this._currentData,e);this._config.highlightCrossfiltered&&this._updateHighlightedBars(i)}else{let e=null===(t=null===(i=this._currentData)||void 0===i?void 0:i.getChild(this.accessor))||void 0===t?void 0:t.toArray();e instanceof BigInt64Array&&(e=Array.from(e,(i=>Number(i)))),this._updateHighlightedBars(e)}}_filterByIdx(i,t){var e,s;const{linkSourceIndex:n,linkTargetIndex:o,pointIndex:a}=this._cosmograph.config,r=i.numRows,h=[],l=i.getChild(this.accessor);let c,d=null;this._config.useLinksData?n&&o&&(c=i.getChild(n),d=i.getChild(o)):a&&(c=i.getChild(a));const _=null!==d,g=this._config.useLinksData?null===(s=null===(e=this._cosmograph.linksSelection.active)||void 0===e?void 0:e.predicate)||void 0===s?void 0:s.range:null;for(let i=0;i<r;i++){const e=null==c?void 0:c.get(i),s=_?null==d?void 0:d.get(i):void 0;if(t.has(e)||_&&t.has(s)){const t=null==l?void 0:l.get(i);(!_||g&&g[0]<=t&&t<=g[1]||!g)&&h.push(t)}}return h}_updateHighlightedBars(i){this._timeline.setHighlightedData(i)}_applyFilter(i){var t;null===(t=this._client)||void 0===t||t.publish(i)}getCurrentSelection(){var i;return null===(i=this._timeline)||void 0===i?void 0:i.getCurrentSelection()}getCurrentSelectionInPixels(){var i;return null===(i=this._timeline)||void 0===i?void 0:i.getCurrentSelectionInPixels()}getBarWidth(){return this._timeline.getBarWidth()}setSelection(i){this._timeline.setSelection(i)}getIsAnimationRunning(){return this._timeline.getIsAnimationRunning()}getConfig(){return this._config}remove(){this._timeline.destroy(),this._cosmograph.removeEventListener("dataUpdated",this._dataUpdatedHandler),this._cosmograph.removeEventListener("dataFiltered",this._dataFilteredHandler)}}export{a as CosmographTimeline};
import{merge as t,Timeline as i}from"@cosmograph/ui";import{defaultCosmographTimelineConfig as e}from"./config.js";import{HistogramClient as s}from"../histogram/histogram-client.js";import{isTableExists as n,checkColumnsExist as a}from"../cosmograph/data-ops/misc.js";class o{constructor(s,n,a){this._isValidAccessor=!1,this._onBrush=(t,i)=>{var e,s;this._applyFilter(t),null===(s=(e=this._config).onSelection)||void 0===s||s.call(e,t,i)},this._onBarHover=(...t)=>{var i,e;null===(e=(i=this._config).onBarHover)||void 0===e||e.call(i,...t)},this._onAnimationPlay=(...t)=>{var i,e;null===(e=(i=this._config).onAnimationPlay)||void 0===e||e.call(i,...t)},this._onAnimationPause=(...t)=>{var i,e;null===(e=(i=this._config).onAnimationPause)||void 0===e||e.call(i,...t)},this.playAnimation=()=>{this._timeline.playAnimation()},this.pauseAnimation=()=>{this._timeline.pauseAnimation()},this.stopAnimation=()=>{this._timeline.stopAnimation()},this._cosmograph=s,this._config=t(e,null!=a?a:{}),this._timeline=new i(n,this._createTimelineConfig(a)),this._filter=this._config.useLinksData?s.linksSelection:s.pointsSelection,this._dataUpdatedHandler=this._getData.bind(this),this._dataFilteredHandler=this._updateCrossfilteredData.bind(this),this._cosmograph.addEventListener("dataUpdated",this._dataUpdatedHandler),this._cosmograph.addEventListener("dataFiltered",this._dataFilteredHandler),this._initialize()}get pointAccessors(){const{pointId:t,pointIndex:i}=this._cosmograph.config;return t&&i?[t,i]:t?[t]:i?[i]:[]}get linkAccessors(){const{linkSourceIndex:t,linkTargetIndex:i}=this._cosmograph.config;return t&&i?[t,i]:t?[t]:i?[i]:[]}get accessor(){var t;return null!==(t=this._config.accessor)&&void 0!==t?t:e.accessor}get tableName(){return this._config.useLinksData?this._cosmograph.linksTableName:this._cosmograph.pointsTableName}setConfig(i){var s;const n=this._config;this._config=t(e,null!=i?i:{}),this._timeline.setConfig(this._createTimelineConfig(i)),this._config.accessor!==n.accessor&&(null===(s=this._client)||void 0===s||s.updateAccessor(this._config.accessor),this._getData(),this._updateData(),this.setSelection())}async _initialize(){await this._createClient(),(this._cosmograph.stats.linksCount||this._cosmograph.stats.pointsCount)&&await this._getData()}async _getData(){var t;if(await this._cosmograph.dataReady(),this._timeline.setLoadingState(),!this._cosmograph.dbCoordinator)return;const i=await n(this._cosmograph.dbCoordinator,this.tableName);this._isValidAccessor=i&&await a(this._cosmograph.dbCoordinator,this.tableName,[this.accessor]),i&&this._isValidAccessor?(this._client&&(this._client.preventQuerying=!1),this._currentData=await(null===(t=this._client)||void 0===t?void 0:t.getCurrentData())):(this._currentData=void 0,this._client&&(this._client.preventQuerying=!0)),this._updateData()}async _createClient(){if(await this._cosmograph.dbReady(),!this._cosmograph.dbCoordinator)return;const t={tableName:this.tableName,filterBy:this._filter,accessor:this.accessor,include:()=>this._config.useLinksData?this.linkAccessors:this.pointAccessors,onFiltered:this._handleSelectionUpdate.bind(this),coordinator:this._cosmograph.dbCoordinator};this._client=new s(t),this._cosmograph.dbCoordinator.connect(this._client)}_createTimelineConfig(t){return{...t,events:{onBrush:this._onBrush.bind(this),onBarHover:this._onBarHover.bind(this),onAnimationPlay:this._onAnimationPlay.bind(this),onAnimationPause:this._onAnimationPause.bind(this)}}}_handleSelectionUpdate(t){this._config.accessor&&(this._config.useLinksData?this._cosmograph.onLinksFiltered(t):this._cosmograph.onPointsFiltered(t))}_updateData(){var t,i;if(this._currentData){let e=null===(i=null===(t=this._currentData)||void 0===t?void 0:t.getChild(this.accessor))||void 0===i?void 0:i.toArray();e instanceof BigInt64Array&&(e=Array.from(e,(t=>Number(t)))),this._timeline.setTimeData(e,this._config.customExtent),this._updateHighlightedBars(e)}else this._timeline.setTimeData(void 0),this._updateHighlightedBars(void 0)}_updateCrossfilteredData(){var t,i;if(!this._currentData||!this._isValidAccessor)return;const e=this._cosmograph.crossfilter.intersection;if(this._cosmograph.isFilteringActive){const t=this._filterByIdx(this._currentData,e);this._config.highlightCrossfiltered&&this._updateHighlightedBars(t)}else{let e=null===(i=null===(t=this._currentData)||void 0===t?void 0:t.getChild(this.accessor))||void 0===i?void 0:i.toArray();e instanceof BigInt64Array&&(e=Array.from(e,(t=>Number(t)))),this._updateHighlightedBars(e)}}_filterByIdx(t,i){var e,s;const{linkSourceIndex:n,linkTargetIndex:a,pointIndex:o}=this._cosmograph.config,r=t.numRows,h=[],l=t.getChild(this.accessor);let c,d=null;this._config.useLinksData?n&&a&&(c=t.getChild(n),d=t.getChild(a)):o&&(c=t.getChild(o));const _=null!==d,g=this._config.useLinksData?null===(s=null===(e=this._cosmograph.linksSelection.active)||void 0===e?void 0:e.predicate)||void 0===s?void 0:s.range:null;for(let t=0;t<r;t++){const e=null==c?void 0:c.get(t),s=_?null==d?void 0:d.get(t):void 0;if(i.has(e)||_&&i.has(s)){const i=null==l?void 0:l.get(t);(!_||g&&g[0]<=i&&i<=g[1]||!g)&&h.push(i)}}return h}_updateHighlightedBars(t){this._timeline.setHighlightedData(t)}_applyFilter(t){var i;null===(i=this._client)||void 0===i||i.publish(t)}getCurrentSelection(){var t;return null===(t=this._timeline)||void 0===t?void 0:t.getCurrentSelection()}getCurrentSelectionInPixels(){var t;return null===(t=this._timeline)||void 0===t?void 0:t.getCurrentSelectionInPixels()}getBarWidth(){return this._timeline.getBarWidth()}setSelection(t){this._timeline.setSelection(t)}getIsAnimationRunning(){return this._timeline.getIsAnimationRunning()}getConfig(){return this._config}remove(){var t;null===(t=this._client)||void 0===t||t.reset(),this._timeline.destroy(),this._cosmograph.removeEventListener("dataUpdated",this._dataUpdatedHandler),this._cosmograph.removeEventListener("dataFiltered",this._dataFilteredHandler)}}export{o as CosmographTimeline};
//# sourceMappingURL=index.js.map
{
"name": "@cosmograph/cosmograph",
"version": "2.0.0-beta.5",
"version": "2.0.0-beta.6",
"description": "Cosmograph: The fastest web-based graph visualization library",

@@ -11,8 +11,8 @@ "author": "cosmograph-org",

"dependencies": {
"@cosmograph/cosmos": "2.0.0-beta.9",
"@cosmograph/ui": "2.0.0-beta.5",
"@duckdb/duckdb-wasm": "1.28.1-dev258.0",
"@cosmograph/cosmos": "2.0.0-beta.12",
"@cosmograph/ui": "2.0.0-beta.6",
"@duckdb/duckdb-wasm": "1.29.0",
"@interacta/css-labels": "^0.1.1",
"@uwdata/mosaic-core": "^0.10.0",
"@uwdata/mosaic-sql": "^0.10.0",
"@uwdata/mosaic-core": "^0.11.0",
"@uwdata/mosaic-sql": "^0.11.0",
"apache-arrow": "17.0.0",

@@ -19,0 +19,0 @@ "d3-color": "^3.1.0",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc