repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
AIHub
github_2023
classfang
typescript
getSparkHostUrl
const getSparkHostUrl = (model: string) => { let hostUrl = '' switch (model) { case 'chat-v1.1': hostUrl = 'wss://spark-api.xf-yun.com/v1.1/chat' break case 'chat-v2.1': hostUrl = 'wss://spark-api.xf-yun.com/v2.1/chat' break case 'chat-v3.1': hostUrl = 'wss://spark-api.xf-yun.com/v3.1/chat' break case 'chat-v3.5': hostUrl = 'wss://spark-api.xf-yun.com/v3.5/chat' break case 'image-v2.1': hostUrl = 'wss://spark-api.cn-huabei-1.xf-yun.com/v2.1/image' break case 'tti-v2.1': hostUrl = 'https://spark-api.cn-huabei-1.xf-yun.com/v2.1/tti' break } return hostUrl }
// 获取星火服务地址
https://github.com/classfang/AIHub/blob/fd695d39d075c4f6ae0d4210b415856ad701983a/src/renderer/src/utils/big-model/spark-util.ts#L9-L32
fd695d39d075c4f6ae0d4210b415856ad701983a
AIHub
github_2023
classfang
typescript
getAuthUrl
const getAuthUrl = (hostUrl: string, method: string, apiKey: string, apiSecret: string) => { const url = new URL(hostUrl) const host = url.host const path = url.pathname const date = (new Date() as any).toGMTString() const algorithm = 'hmac-sha256' const headers = 'host date request-line' const signatureOrigin = `host: ${host}\ndate: ${date}\n${method} ${path} HTTP/1.1` const signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret) const signature = CryptoJS.enc.Base64.stringify(signatureSha) const authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"` const authorization = btoa(authorizationOrigin) return `${url.toString()}?authorization=${authorization}&date=${date}&host=${host}` }
// 获取ws请求地址
https://github.com/classfang/AIHub/blob/fd695d39d075c4f6ae0d4210b415856ad701983a/src/renderer/src/utils/big-model/spark-util.ts#L60-L73
fd695d39d075c4f6ae0d4210b415856ad701983a
AIHub
github_2023
classfang
typescript
getSparkWsRequestParam
const getSparkWsRequestParam = ( appId: string, model: string, maxTokens: number | undefined, messageList: BaseMessage[] ) => { return JSON.stringify({ header: { app_id: appId, uid: '123456' }, parameter: { chat: { domain: getDomain(model), temperature: 0.5, max_tokens: maxTokens ?? 4096 } }, payload: { message: { text: messageList } } }) }
// 获取对话请求参数
https://github.com/classfang/AIHub/blob/fd695d39d075c4f6ae0d4210b415856ad701983a/src/renderer/src/utils/big-model/spark-util.ts#L76-L100
fd695d39d075c4f6ae0d4210b415856ad701983a
AIHub
github_2023
classfang
typescript
getDrawingRequestParam
const getDrawingRequestParam = (appId: string, imagePrompt: string, imageSize: string) => { return JSON.stringify({ header: { app_id: appId }, parameter: { chat: { domain: 'general', width: Number(imageSize.split('x')[0]), height: Number(imageSize.split('x')[1]) } }, payload: { message: { text: [ { role: 'user', content: imagePrompt } ] } } }) }
// 获取绘画请求参数
https://github.com/classfang/AIHub/blob/fd695d39d075c4f6ae0d4210b415856ad701983a/src/renderer/src/utils/big-model/spark-util.ts#L103-L126
fd695d39d075c4f6ae0d4210b415856ad701983a
AIHub
github_2023
classfang
typescript
uploadImageToOSS
const uploadImageToOSS = async (model: string, apiKey: string | undefined, msg: BaseMessage) => { const getPolicyResp = await fetch( `https://dashscope.aliyuncs.com/api/v1/uploads?action=getPolicy&model=${model}`, { headers: { Authorization: `Bearer ${apiKey}` } } ) const getPolicyJson = await getPolicyResp.json() const imageResp = await fetch(`file://${msg.image}`) const imageBlob = await imageResp.blob() const formData = new FormData() const imageUploadName = `${randomUUID()}.png` const imageUploadPath = `${getPolicyJson.data.upload_dir}/${imageUploadName}` formData.append('OSSAccessKeyId', getPolicyJson.data.oss_access_key_id) formData.append('Signature', getPolicyJson.data.signature) formData.append('policy', getPolicyJson.data.policy) formData.append('key', `${imageUploadPath}`) formData.append('x-oss-object-acl', getPolicyJson.data.x_oss_object_acl) formData.append('x-oss-forbid-overwrite', getPolicyJson.data.x_oss_forbid_overwrite) formData.append('success_action_status', '200') formData.append('x-oss-content-type', 'image/png') formData.append('file', imageBlob, imageUploadName) await fetch(getPolicyJson.data.upload_host, { method: 'POST', headers: { Authorization: `Bearer ${apiKey}` }, body: formData }) return imageUploadPath }
// 上传图片到 DashScope 临时空间
https://github.com/classfang/AIHub/blob/fd695d39d075c4f6ae0d4210b415856ad701983a/src/renderer/src/utils/big-model/tongyi-util.ts#L202-L234
fd695d39d075c4f6ae0d4210b415856ad701983a
AIHub
github_2023
classfang
typescript
changeType
const changeType = (type: string) => { const typeDict = { auto: 'auto', 'zh-CHS': 'zh', en: 'en', ja: 'jp', ko: 'kor', fr: 'fra' } return typeDict[type] }
// 类型转换
https://github.com/classfang/AIHub/blob/fd695d39d075c4f6ae0d4210b415856ad701983a/src/renderer/src/utils/translator/baidu-util.ts#L55-L65
fd695d39d075c4f6ae0d4210b415856ad701983a
tinkerbird
github_2023
wizenheimer
typescript
HNSW.constructor
constructor( M = 16, efConstruction = 200, d: number | null = null, metric: SimilarityMetric = SimilarityMetric.cosine ) { this.metric = metric; this.similarityFunction = this.getSimilarityFunction(); this.d = d; this.M = M; this.efConstruction = efConstruction; this.entryPointId = -1; this.nodes = new Map<number, Node>(); this.probs = this.getProbDistribution(); this.levelMax = this.probs.length - 1; }
// maximum level of the graph
https://github.com/wizenheimer/tinkerbird/blob/f22787fae0c8a2b1959ee33278f8b18b99ec7532/src/hnsw.ts#L32-L47
f22787fae0c8a2b1959ee33278f8b18b99ec7532
tinkerbird
github_2023
wizenheimer
typescript
HNSW.getProbDistribution
private getProbDistribution(): number[] { const levelMult = 1 / Math.log(this.M); let probs = [] as number[], level = 0; while (true) { const prob = Math.exp(-level / levelMult) * (1 - Math.exp(-1 / levelMult)); if (prob < 1e-9) break; probs.push(prob); level++; } return probs; }
// figure out the probability distribution along the level of the layers
https://github.com/wizenheimer/tinkerbird/blob/f22787fae0c8a2b1959ee33278f8b18b99ec7532/src/hnsw.ts#L56-L68
f22787fae0c8a2b1959ee33278f8b18b99ec7532
tinkerbird
github_2023
wizenheimer
typescript
HNSW.query
query(target: Embedding, k: number = 3): vectorResult { const result: vectorResult = []; // storing the query result const visited: Set<number> = new Set<number>(); // de duplicate candidate search // main a heap of candidates that are ordered by similarity const orderBySimilarity = (aID: number, bID: number) => { const aNode = this.nodes.get(aID)!; const bNode = this.nodes.get(bID)!; return ( this.similarityFunction(target, bNode.embedding) - this.similarityFunction(target, aNode.embedding) ); }; const candidates = new Heap<number>(orderBySimilarity); candidates.push(this.entryPointId); let level = this.levelMax; // do until we have required result while (!candidates.isEmpty() && result.length < k) { const currID = candidates.pop()!; if (visited.has(currID)) continue; visited.add(currID); const currNode = this.nodes.get(currID)!; const currSimilarity = this.similarityFunction( currNode.embedding, target ); if (currSimilarity > 0) { result.push({ id: currID, content: currNode.content, embedding: currNode.embedding, score: currSimilarity }); } // no more levels left to explore if (currNode.level === 0) { continue; } // explore the neighbors of candidates from each level level = Math.min(level, currNode.level - 1); for (let i = level; i >= 0; i -= 1) { const neighbors = currNode.neighbors[i]; for (const neighborId of neighbors) { if (!visited.has(neighborId)) { candidates.push(neighborId); } } } } // pick the top k candidates from the result return result.slice(0, k); }
// perform vector search on the index
https://github.com/wizenheimer/tinkerbird/blob/f22787fae0c8a2b1959ee33278f8b18b99ec7532/src/hnsw.ts#L71-L127
f22787fae0c8a2b1959ee33278f8b18b99ec7532
tinkerbird
github_2023
wizenheimer
typescript
orderBySimilarity
const orderBySimilarity = (aID: number, bID: number) => { const aNode = this.nodes.get(aID)!; const bNode = this.nodes.get(bID)!; return ( this.similarityFunction(target, bNode.embedding) - this.similarityFunction(target, aNode.embedding) ); };
// de duplicate candidate search
https://github.com/wizenheimer/tinkerbird/blob/f22787fae0c8a2b1959ee33278f8b18b99ec7532/src/hnsw.ts#L76-L83
f22787fae0c8a2b1959ee33278f8b18b99ec7532
tinkerbird
github_2023
wizenheimer
typescript
HNSW.determineLevel
private determineLevel(): number { let r = Math.random(); this.probs.forEach((pLevel, index) => { if (r < pLevel) return index; r -= pLevel; }); return this.probs.length - 1; }
// stochastically pick a level, higher the probability greater the chances of getting picked
https://github.com/wizenheimer/tinkerbird/blob/f22787fae0c8a2b1959ee33278f8b18b99ec7532/src/hnsw.ts#L130-L137
f22787fae0c8a2b1959ee33278f8b18b99ec7532
tinkerbird
github_2023
wizenheimer
typescript
addToNeighborhood
const addToNeighborhood = (srcNode: Node, trgNode: Node) => { // filter out sentinel ids srcNode.neighbors[level] = srcNode.neighbors[level].filter( (id) => id !== -1 ); // add trgNode to the neighbor srcNode.neighbors[level].push(trgNode.id); // incase the max neighbor are exceeded, remove the farthest if (srcNode.neighbors[level].length > this.M) { srcNode.neighbors[level].pop(); } };
// update the neighborhood, such that both nodes share common neighbors upto a common level
https://github.com/wizenheimer/tinkerbird/blob/f22787fae0c8a2b1959ee33278f8b18b99ec7532/src/hnsw.ts#L216-L227
f22787fae0c8a2b1959ee33278f8b18b99ec7532
tinkerbird
github_2023
wizenheimer
typescript
VectorStore.recreate
static async recreate({ collectionName }: { collectionName: string; }): Promise<VectorStore> { if (!(await VectorStore.exists(collectionName))) return this.create({ collectionName }); const { M, efConstruction } = await VectorStore.getMeta(collectionName); const instance = new VectorStore(M, efConstruction, collectionName); await instance.loadIndex(); return instance; }
// attempt to recreate the index from collection
https://github.com/wizenheimer/tinkerbird/blob/f22787fae0c8a2b1959ee33278f8b18b99ec7532/src/store.ts#L49-L61
f22787fae0c8a2b1959ee33278f8b18b99ec7532
tinkerbird
github_2023
wizenheimer
typescript
VectorStore.exists
static async exists(collectionName: string): Promise<boolean> { return (await indexedDB.databases()) .map((db) => db.name) .includes(collectionName); }
// check if the collection exists
https://github.com/wizenheimer/tinkerbird/blob/f22787fae0c8a2b1959ee33278f8b18b99ec7532/src/store.ts#L64-L68
f22787fae0c8a2b1959ee33278f8b18b99ec7532
tinkerbird
github_2023
wizenheimer
typescript
VectorStore.getMeta
static async getMeta(collectionName: string) { const collection = await openDB<IndexSchema>(collectionName, 1); const efConstruction = await collection.get("meta", "efConstruction"); const M = await collection.get("meta", "neighbors"); collection.close(); return { M, efConstruction, collectionName }; }
// get metadata about any collection
https://github.com/wizenheimer/tinkerbird/blob/f22787fae0c8a2b1959ee33278f8b18b99ec7532/src/store.ts#L80-L86
f22787fae0c8a2b1959ee33278f8b18b99ec7532
tinkerbird
github_2023
wizenheimer
typescript
VectorStore.saveMeta
private async saveMeta() { if (!this.collection) throw VectorStoreUnintialized; await this.collection?.put("meta", this.d, "dimension"); await this.collection?.put( "meta", this.collectionName, "collectionName" ); await this.collection?.put("meta", this.M, "neighbors"); await this.collection?.put("meta", this.entryPointId, "entryPointId"); await this.collection?.put( "meta", this.efConstruction, "efConstruction" ); await this.collection?.put("meta", this.probs, "probs"); await this.collection?.put("meta", this.levelMax, "levelMax"); await this.collection?.put( "meta", this.metric === SimilarityMetric.cosine ? "cosine" : "euclidean", "levelMax" ); }
// save meta info onto meta object store
https://github.com/wizenheimer/tinkerbird/blob/f22787fae0c8a2b1959ee33278f8b18b99ec7532/src/store.ts#L89-L111
f22787fae0c8a2b1959ee33278f8b18b99ec7532
tinkerbird
github_2023
wizenheimer
typescript
VectorStore.loadMeta
private async loadMeta() { if (!this.collection) throw VectorStoreUnintialized; this.d = await this.collection?.get("meta", "dimension"); this.collectionName = await this.collection?.get( "meta", "collectionName" ); this.M = await this.collection?.get("meta", "neighbors"); this.entryPointId = await this.collection?.get("meta", "entryPointId"); this.efConstruction = await this.collection?.get( "meta", "efConstruction" ); this.probs = await this.collection?.get("meta", "probs"); this.levelMax = await this.collection?.get("meta", "levelMax"); this.metric = (await this.collection?.get("meta", "levelMax")) === "cosine" ? SimilarityMetric.cosine : SimilarityMetric.euclidean; }
// load meta info from meta object store
https://github.com/wizenheimer/tinkerbird/blob/f22787fae0c8a2b1959ee33278f8b18b99ec7532/src/store.ts#L114-L133
f22787fae0c8a2b1959ee33278f8b18b99ec7532
tinkerbird
github_2023
wizenheimer
typescript
VectorStore.saveIndex
async saveIndex() { if (!this.collection) throw VectorStoreUnintialized; // delete index if it exists already if (await VectorStore.exists(this.collectionName)) await this.deleteIndex(); // populate the index const nodes = this.nodes; nodes.forEach(async (node: Node, key: number) => { await this.collection?.put("index", node, String(key)); }); // populate the meta await this.saveMeta(); }
// save index into index object store
https://github.com/wizenheimer/tinkerbird/blob/f22787fae0c8a2b1959ee33278f8b18b99ec7532/src/store.ts#L136-L148
f22787fae0c8a2b1959ee33278f8b18b99ec7532
tinkerbird
github_2023
wizenheimer
typescript
VectorStore.loadIndex
private async loadIndex() { if (!this.collection) throw VectorStoreUnintialized; try { // hold the nodes loaded in from indexedDB const nodes: Map<number, Node> = new Map(); let store = this.collection.transaction("index").store; let cursor = await store.openCursor(); // traverse the cursor while (true) { const id = Number(cursor?.key); const node = cursor?.value; nodes.set(id, node); cursor = await cursor!.continue(); if (!cursor) break; } // map the nodes this.nodes = nodes; // load the meta data await this.loadMeta(); } catch (error) { throw VectorStoreRecreationFailed; } }
// load index into index object store
https://github.com/wizenheimer/tinkerbird/blob/f22787fae0c8a2b1959ee33278f8b18b99ec7532/src/store.ts#L151-L175
f22787fae0c8a2b1959ee33278f8b18b99ec7532
tinkerbird
github_2023
wizenheimer
typescript
VectorStore.deleteIndex
async deleteIndex() { if (!this.collection) return VectorStoreUnintialized; try { await deleteDB(this.collectionName); this.init(); } catch (error) { throw VectorStoreIndexPurgeFailed; } }
// delete index if it exists and populate it with empty index
https://github.com/wizenheimer/tinkerbird/blob/f22787fae0c8a2b1959ee33278f8b18b99ec7532/src/store.ts#L178-L187
f22787fae0c8a2b1959ee33278f8b18b99ec7532
ngx-vflow
github_2023
artem-mangilev
typescript
CustomComponentNodesDemoComponent.handleComponentEvent
handleComponentEvent(event: ComponentNodeEvent<[RedSquareNodeComponent, BlueSquareNodeComponent]>) { if (event.eventName === 'redSquareEvent') { this.notifyService.notify(event.eventPayload); } if (event.eventName === 'blueSquareEvent') { this.notifyService.notify(`${event.eventPayload.x + event.eventPayload.y}`); } }
// Type-safe!
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-demo/src/app/categories/features/pages/custom-nodes/demo/custom-component-nodes-demo.component.ts#L56-L64
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
VizdomLayoutDemoComponent.layout
private layout(nodesToLayout: Node[], edgesToLayout: Edge[] = []) { const graph = new DirectedGraph({ layout: { margin_x: 75, }, }); // DirectedGraph not provide VErtexRef ids so we need to store it somewhere // for later access const vertices = new Map<string, VertexRef>(); const nodes = new Map<string, Node>(); nodesToLayout.forEach((n) => { const v = graph.new_vertex( { // For now we only can use static sized nodes layout: { shape_w: 150, shape_h: 100, }, render: { id: n.id, }, }, { compute_bounding_box: false, }, ); vertices.set(n.id, v); nodes.set(n.id, n); }); edgesToLayout.forEach((e) => { graph.new_edge(vertices.get(e.source)!, vertices.get(e.target)!); }); // Compute layout with vizdom internal algorythm const layout = graph.layout().to_json().to_obj(); // Render nodes and edges based on this layout this.nodes.set( layout.nodes.map((n) => { return { ...nodes.get(n.id)!, id: n.id, point: { x: n.x, y: n.y, }, }; }), ); this.edges.set(edgesToLayout); }
/** * Method that responsible to layout and render passed nodes and edges */
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-demo/src/app/categories/workshops/categories/layout/pages/vizdom-layout/demo/vizdom-layout-demo.component.ts#L79-L134
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
VflowComponent.viewportTo
public viewportTo(viewport: ViewportState): void { this.viewportService.writableViewport.set({ changeType: 'absolute', state: viewport, duration: 0, }); }
/** * Change viewport to specified state * * @param viewport viewport state */
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/components/vflow/vflow.component.ts#L339-L345
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
VflowComponent.zoomTo
public zoomTo(zoom: number): void { this.viewportService.writableViewport.set({ changeType: 'absolute', state: { zoom }, duration: 0, }); }
/** * Change zoom * * @param zoom zoom value */
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/components/vflow/vflow.component.ts#L352-L358
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
VflowComponent.panTo
public panTo(point: Point): void { this.viewportService.writableViewport.set({ changeType: 'absolute', state: point, duration: 0, }); }
/** * Move to specified coordinate * * @param point point where to move */
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/components/vflow/vflow.component.ts#L365-L371
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
VflowComponent.getNode
public getNode<T = unknown>(id: string): Node<T> | DynamicNode<T> | undefined { return this.flowEntitiesService.getNode<T>(id)?.node; }
/** * Get node by id * * @param id node id */
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/components/vflow/vflow.component.ts#L382-L384
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
VflowComponent.getDetachedEdges
public getDetachedEdges(): Edge[] { return this.flowEntitiesService.getDetachedEdges().map((e) => e.edge); }
/** * Sync method to get detached edges */
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/components/vflow/vflow.component.ts#L389-L391
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
VflowComponent.documentPointToFlowPoint
public documentPointToFlowPoint(point: Point): Point { return this.spacePointContext().documentPointToFlowPoint(point); }
/** * Convert point received from document to point on the flow */
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/components/vflow/vflow.component.ts#L396-L398
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
VflowComponent.trackNodes
protected trackNodes(idx: number, { node }: NodeModel) { return node; }
// #endregion
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/components/vflow/vflow.component.ts#L401-L403
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
PointerDirective.handleTouchOverAndOut
private handleTouchOverAndOut(target: Element | null, event: TouchEvent) { if (target === this.hostElement) { this.pointerOver.emit(event); this.wasPointerOver = true; } else { // should not emit before pointerOver if (this.wasPointerOver) { this.pointerOut.emit(event); } this.wasPointerOver = false; } }
// TODO: dirty imperative implementation
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/directives/pointer.directive.ts#L72-L84
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
RootPointerDirective.setInitialTouch
public setInitialTouch(event: TouchEvent) { this.initialTouch$.next(event); }
/** * We should know when user started a touch in order to not * show old touch position when connection creation is started */
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/directives/root-pointer.directive.ts#L87-L89
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
calcControlPoint
function calcControlPoint(point: Point, pointPosition: Position, distanceVector: Point) { const factorPoint = { x: 0, y: 0 }; switch (pointPosition) { case 'top': factorPoint.y = 1; break; case 'bottom': factorPoint.y = -1; break; case 'right': factorPoint.x = 1; break; case 'left': factorPoint.x = -1; break; } // TODO: explain name const fullDistanceVector = { x: distanceVector.x * Math.abs(factorPoint.x), y: distanceVector.y * Math.abs(factorPoint.y), }; // TODO: probably need to make this configurable const curvature = 0.25; // thanks colleagues from react/svelte world // https://github.com/xyflow/xyflow/blob/f0117939bae934447fa7f232081f937169ee23b5/packages/system/src/utils/edges/bezier-edge.ts#L56 const controlOffset = curvature * 25 * Math.sqrt(Math.abs(fullDistanceVector.x + fullDistanceVector.y)); return { x: point.x + factorPoint.x * controlOffset, y: point.y - factorPoint.y * controlOffset, }; }
/** * Calculate control point based on provided point * * @param point relative this point control point is gonna be computed (the source or the target) * @param pointPosition position of {point} on block * @param distanceVector transmits the distance between the source and the target as x and y coordinates */
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/math/edge-path/bezier-path.ts#L32-L66
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
getPointOnBezier
function getPointOnBezier( sourcePoint: Point, targetPoint: Point, sourceControl: Point, targetControl: Point, ratio: number, ): Point { const fromSourceToFirstControl: Point = getPointOnLineByRatio(sourcePoint, sourceControl, ratio); const fromFirstControlToSecond: Point = getPointOnLineByRatio(sourceControl, targetControl, ratio); const fromSecondControlToTarget: Point = getPointOnLineByRatio(targetControl, targetPoint, ratio); return getPointOnLineByRatio( getPointOnLineByRatio(fromSourceToFirstControl, fromFirstControlToSecond, ratio), getPointOnLineByRatio(fromFirstControlToSecond, fromSecondControlToTarget, ratio), ratio, ); }
/** * Get point on bezier curve by ratio */
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/math/edge-path/bezier-path.ts#L93-L109
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
getPoints
function getPoints({ source, sourcePosition = 'bottom', target, targetPosition = 'top', offset, }: { source: Point; sourcePosition: Position; target: Point; targetPosition: Position; offset: number; }): [Point[], number, number] { const sourceDir = handleDirections[sourcePosition]; const targetDir = handleDirections[targetPosition]; const sourceGapped: Point = { x: source.x + sourceDir.x * offset, y: source.y + sourceDir.y * offset }; const targetGapped: Point = { x: target.x + targetDir.x * offset, y: target.y + targetDir.y * offset }; const dir = getDirection({ source: sourceGapped, sourcePosition, target: targetGapped, }); const dirAccessor = dir.x !== 0 ? 'x' : 'y'; const currDir = dir[dirAccessor]; let points: Point[] = []; let centerX, centerY; const sourceGapOffset = { x: 0, y: 0 }; const targetGapOffset = { x: 0, y: 0 }; const [defaultCenterX, defaultCenterY] = getEdgeCenter(source, target); // opposite handle positions, default case if (sourceDir[dirAccessor] * targetDir[dirAccessor] === -1) { centerX = defaultCenterX; centerY = defaultCenterY; // ---> // | // >--- const verticalSplit: Point[] = [ { x: centerX, y: sourceGapped.y }, { x: centerX, y: targetGapped.y }, ]; // | // --- // | const horizontalSplit: Point[] = [ { x: sourceGapped.x, y: centerY }, { x: targetGapped.x, y: centerY }, ]; if (sourceDir[dirAccessor] === currDir) { points = dirAccessor === 'x' ? verticalSplit : horizontalSplit; } else { points = dirAccessor === 'x' ? horizontalSplit : verticalSplit; } } else { // sourceTarget means we take x from source and y from target, targetSource is the opposite const sourceTarget: Point[] = [{ x: sourceGapped.x, y: targetGapped.y }]; const targetSource: Point[] = [{ x: targetGapped.x, y: sourceGapped.y }]; // this handles edges with same handle positions if (dirAccessor === 'x') { points = sourceDir.x === currDir ? targetSource : sourceTarget; } else { points = sourceDir.y === currDir ? sourceTarget : targetSource; } if (sourcePosition === targetPosition) { const diff = Math.abs(source[dirAccessor] - target[dirAccessor]); // if an edge goes from right to right for example (sourcePosition === targetPosition) and the distance between source.x and target.x is less than the offset, the added point and the gapped source/target will overlap. This leads to a weird edge path. To avoid this we add a gapOffset to the source/target if (diff <= offset) { const gapOffset = Math.min(offset - 1, offset - diff); if (sourceDir[dirAccessor] === currDir) { sourceGapOffset[dirAccessor] = (sourceGapped[dirAccessor] > source[dirAccessor] ? -1 : 1) * gapOffset; } else { targetGapOffset[dirAccessor] = (targetGapped[dirAccessor] > target[dirAccessor] ? -1 : 1) * gapOffset; } } } // these are conditions for handling mixed handle positions like Right -> Bottom for example if (sourcePosition !== targetPosition) { const dirAccessorOpposite = dirAccessor === 'x' ? 'y' : 'x'; const isSameDir = sourceDir[dirAccessor] === targetDir[dirAccessorOpposite]; const sourceGtTargetOppo = sourceGapped[dirAccessorOpposite] > targetGapped[dirAccessorOpposite]; const sourceLtTargetOppo = sourceGapped[dirAccessorOpposite] < targetGapped[dirAccessorOpposite]; const flipSourceTarget = (sourceDir[dirAccessor] === 1 && ((!isSameDir && sourceGtTargetOppo) || (isSameDir && sourceLtTargetOppo))) || (sourceDir[dirAccessor] !== 1 && ((!isSameDir && sourceLtTargetOppo) || (isSameDir && sourceGtTargetOppo))); if (flipSourceTarget) { points = dirAccessor === 'x' ? sourceTarget : targetSource; } } const sourceGapPoint = { x: sourceGapped.x + sourceGapOffset.x, y: sourceGapped.y + sourceGapOffset.y }; const targetGapPoint = { x: targetGapped.x + targetGapOffset.x, y: targetGapped.y + targetGapOffset.y }; const maxXDistance = Math.max(Math.abs(sourceGapPoint.x - points[0].x), Math.abs(targetGapPoint.x - points[0].x)); const maxYDistance = Math.max(Math.abs(sourceGapPoint.y - points[0].y), Math.abs(targetGapPoint.y - points[0].y)); // we want to place the label on the longest segment of the edge if (maxXDistance >= maxYDistance) { centerX = (sourceGapPoint.x + targetGapPoint.x) / 2; centerY = points[0].y; } else { centerX = points[0].x; centerY = (sourceGapPoint.y + targetGapPoint.y) / 2; } } const pathPoints = [ source, { x: sourceGapped.x + sourceGapOffset.x, y: sourceGapped.y + sourceGapOffset.y }, ...points, { x: targetGapped.x + targetGapOffset.x, y: targetGapped.y + targetGapOffset.y }, target, ]; return [pathPoints, centerX, centerY]; }
// ith this function we try to mimic a orthogonal edge routing behaviour
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/math/edge-path/smooth-step-path.ts#L41-L161
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
notSelfValidator
const notSelfValidator = (connection: Connection) => { return connection.source !== connection.target; };
/** * Internal validator that not allows self connections */
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/models/connection.model.ts#L41-L43
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
DraggableService.enable
public enable(element: Element, model: NodeModel) { select(element).call(this.getDragBehavior(model)); }
/** * Enable draggable behavior for element. * * @param element target element for toggling draggable * @param model model with data for this element */
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/services/draggable.service.ts#L21-L23
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
DraggableService.disable
public disable(element: Element) { select(element).call(drag().on('drag', null)); }
/** * Disable draggable behavior for element. * * @param element target element for toggling draggable * @param model model with data for this element */
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/services/draggable.service.ts#L31-L33
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
DraggableService.destroy
public destroy(element: Element) { select(element).on('.drag', null); }
/** * TODO: not shure if this work, need to check * * @param element */
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/services/draggable.service.ts#L40-L42
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
DraggableService.getDragBehavior
private getDragBehavior(model: NodeModel) { let dragNodes: NodeModel[] = []; let initialPositions: Point[] = []; const filterCondition = (event: Event) => { // if there is at least one drag handle, we should check if we are dragging it if (model.dragHandlesCount()) { return !!(event.target as Element).closest('.vflow-drag-handle'); } return true; }; return drag() .filter(filterCondition) .on('start', (event: DragEvent) => { dragNodes = this.getDragNodes(model); initialPositions = dragNodes.map((node) => ({ x: node.point().x - event.x, y: node.point().y - event.y, })); }) .on('drag', (event: DragEvent) => { dragNodes.forEach((model, index) => { const point = { x: round(event.x + initialPositions[index].x), y: round(event.y + initialPositions[index].y), }; moveNode(model, point); }); }); }
/** * Node drag behavior. Updated node's coordinate according to dragging * * @param model * @returns */
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/services/draggable.service.ts#L50-L84
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
HandleService.createHandle
public createHandle(newHandle: HandleModel) { const node = this.node(); if (node) { node.handles.update((handles) => [...handles, newHandle]); } }
// TODO fixes rendering of handle for group node
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/services/handle.service.ts#L21-L26
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
ViewportService.getDefaultViewport
private static getDefaultViewport(): ViewportState { return { zoom: 1, x: 0, y: 0 }; }
/** * The default value used by d3, just copy it here * * @returns default viewport value */
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/services/viewport.service.ts#L20-L22
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
ViewportService.fitView
public fitView(options: FitViewOptions = { padding: 0.1, duration: 0, nodes: [] }) { const nodes = this.getBoundsNodes(options.nodes ?? []); const state = getViewportForBounds( getNodesBounds(nodes), this.flowSettingsService.computedFlowWidth(), this.flowSettingsService.computedFlowHeight(), this.flowSettingsService.minZoom(), this.flowSettingsService.maxZoom(), options.padding ?? 0.1, ); const duration = options.duration ?? 0; this.writableViewport.set({ changeType: 'absolute', state, duration }); }
// TODO: add writableViewportWithConstraints (to apply min zoom/max zoom values)
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/services/viewport.service.ts#L43-L58
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
VflowMockComponent.fitView
public fitView(options?: FitViewOptions): void {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/testing-utils/component-mocks/vflow-mock.component.ts#L173-L173
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
VflowMockComponent.getNode
public getNode<T = unknown>(id: string): Node<T> | DynamicNode<T> | undefined { return this.nodes().find((node) => node.id === id); }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/testing-utils/component-mocks/vflow-mock.component.ts#L180-L182
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
ReferenceKeeper.nodes
public static nodes(newNodes: Node[] | DynamicNode[], oldNodeModels: NodeModel[]) { const oldNodesMap: Map<Node | DynamicNode, NodeModel> = new Map(); oldNodeModels.forEach((model) => oldNodesMap.set(model.node, model)); return newNodes.map((newNode) => { if (oldNodesMap.has(newNode)) return oldNodesMap.get(newNode)!; else return new NodeModel(newNode); }); }
/** * Create new models for new node references and keep old models for old node references */
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/utils/reference-keeper.ts#L10-L18
5e4c5844196b58745838036652674f89d048462f
ngx-vflow
github_2023
artem-mangilev
typescript
ReferenceKeeper.edges
public static edges(newEdges: Edge[], oldEdgeModels: EdgeModel[]): EdgeModel[] { const oldEdgesMap: Map<Edge, EdgeModel> = new Map(); oldEdgeModels.forEach((model) => oldEdgesMap.set(model.edge, model)); return newEdges.map((newEdge) => { if (oldEdgesMap.has(newEdge)) return oldEdgesMap.get(newEdge)!; else return new EdgeModel(newEdge); }); }
/** * Create new models for new edge references and keep old models for old edge references */
https://github.com/artem-mangilev/ngx-vflow/blob/5e4c5844196b58745838036652674f89d048462f/projects/ngx-vflow-lib/src/lib/vflow/utils/reference-keeper.ts#L23-L31
5e4c5844196b58745838036652674f89d048462f
app
github_2023
WebDB-App
typescript
DiagramComponent.ngOnDestroy
ngOnDestroy(): void { this.drawerObs.unsubscribe(); clearInterval(this.interval); }
/* https://loopback.io/doc/en/lb4/HasManyThrough-relation.html test if FK can be null, etc create all relation possible : FK non null -> PK FK null -> PK PK multi -> PK FK to index uml + hover PK multi FK : relations must be multiple right click to change relation type ? */
https://github.com/WebDB-App/app/blob/b111ff2b8b85d121865093666d548edb067ed6fb/front/src/app/right/diagram/diagram.component.ts#L76-L79
b111ff2b8b85d121865093666d548edb067ed6fb
app
github_2023
WebDB-App
typescript
SortPipe.transform
transform(array: Query[], order: 'time' | 'occurrence') { return array.sort((a: Query, b: Query) => { if (a.star) { return -1; } if (b.star) { return 1; } if (order === 'time') { return b.date - a.date; } return b.occurrence - a.occurrence; }); }
/** * * @param array * @param order * @returns {array} */
https://github.com/WebDB-App/app/blob/b111ff2b8b85d121865093666d548edb067ed6fb/front/src/app/right/history/history.component.ts#L75-L89
b111ff2b8b85d121865093666d548edb067ed6fb
app
github_2023
WebDB-App
typescript
RoundPipe.transform
transform(sizeInOctet: number): number { return Math.floor(sizeInOctet / 1024 / 1024 * 100) / 100; }
/** * * @param sizeInOctet * @returns {number} */
https://github.com/WebDB-App/app/blob/b111ff2b8b85d121865093666d548edb067ed6fb/front/src/shared/round.pipe.ts#L10-L12
b111ff2b8b85d121865093666d548edb067ed6fb
lipi
github_2023
rajput-hemant
typescript
useEventListener
function useEventListener< KW extends keyof WindowEventMap, KH extends keyof HTMLElementEventMap, KM extends keyof MediaQueryListEventMap, T extends HTMLElement | MediaQueryList | void = void, >( eventName: KW | KH | KM, handler: ( event: | WindowEventMap[KW] | HTMLElementEventMap[KH] | MediaQueryListEventMap[KM] | Event ) => void, element?: RefObject<T>, options?: boolean | AddEventListenerOptions ) { // Create a ref that stores handler const savedHandler = useRef(handler); useIsomorphicLayoutEffect(() => { savedHandler.current = handler; }, [handler]); useEffect(() => { // Define the listening target const targetElement: T | Window = element?.current ?? window; if (!(targetElement && targetElement.addEventListener)) return; // Create event listener that calls handler function stored in ref const listener: typeof handler = (event) => savedHandler.current(event); targetElement.addEventListener(eventName, listener, options); // Remove event listener on cleanup return () => { targetElement.removeEventListener(eventName, listener, options); }; }, [eventName, element, options]); }
/** * @see https://usehooks-ts.com/react-hook/use-event-listener */
https://github.com/rajput-hemant/lipi/blob/1f7b32c871f0600bd74d43df31a503a50e0f4c66/hooks/use-event-listener.ts#L46-L86
1f7b32c871f0600bd74d43df31a503a50e0f4c66
lipi
github_2023
rajput-hemant
typescript
listener
const listener: typeof handler = (event) => savedHandler.current(event);
// Create event listener that calls handler function stored in ref
https://github.com/rajput-hemant/lipi/blob/1f7b32c871f0600bd74d43df31a503a50e0f4c66/hooks/use-event-listener.ts#L77-L77
1f7b32c871f0600bd74d43df31a503a50e0f4c66
lipi
github_2023
rajput-hemant
typescript
testPlatform
function testPlatform(re: RegExp) { return typeof window !== "undefined" && window.navigator != null ? re.test( // @ts-expect-error - navigator["userAgentData"] window.navigator["userAgentData"]?.platform || window.navigator.platform ) : false; }
/** * Tests the current platform against the given regular expression. * @param re The regular expression to test against. * @returns True if the platform matches the regular expression, false otherwise. * * @see https://github.com/adobe/react-spectrum/blob/5e49ce79094a90839cec20fc5ce788a34bf4b085/packages/%40react-aria/utils/src/platform.ts#L23C1-L50C1 */
https://github.com/rajput-hemant/lipi/blob/1f7b32c871f0600bd74d43df31a503a50e0f4c66/lib/utils.ts#L110-L117
1f7b32c871f0600bd74d43df31a503a50e0f4c66
homarr
github_2023
homarr-labs
typescript
isSecureCookieEnabled
const isSecureCookieEnabled = (req: NextRequest): boolean => { const url = new URL(req.url); return url.protocol === "https:"; };
/** * wheter to use secure cookies or not, is only supported for https. * For http it will not add the cookie as it is not considered secure. * @param req request containing the url * @returns true if the request is https, false otherwise */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/apps/nextjs/src/app/api/auth/[...nextauth]/route.ts#L23-L26
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
extractProvider
const extractProvider = (req: NextRequest): SupportedAuthProvider | "unknown" => { const url = new URL(req.url); if (url.pathname.includes("oidc")) { return "oidc"; } if (url.pathname.includes("credentials")) { return "credentials"; } if (url.pathname.includes("ldap")) { return "ldap"; } return "unknown"; };
/** * This method extracts the used provider from the url and allows us to override the getUserByEmail method in the adapter. * @param req request containing the url * @returns the provider or "unknown" if the provider could not be extracted */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/apps/nextjs/src/app/api/auth/[...nextauth]/route.ts#L33-L49
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
reqWithTrustedOrigin
const reqWithTrustedOrigin = (req: NextRequest): NextRequest => { const proto = req.headers.get("x-forwarded-proto"); const host = req.headers.get("x-forwarded-host"); if (!proto || !host) { logger.warn("Missing x-forwarded-proto or x-forwarded-host headers."); return req; } const envOrigin = `${proto}://${host}`; const { href, origin } = req.nextUrl; logger.debug(`Rewriting origin from ${origin} to ${envOrigin}`); return new NextRequest(href.replace(origin, envOrigin), req); };
/** * This is a workaround to allow the authentication to work with behind a proxy. * See https://github.com/nextauthjs/next-auth/issues/10928#issuecomment-2162893683 */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/apps/nextjs/src/app/api/auth/[...nextauth]/route.ts#L55-L67
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
setCorsHeaders
function setCorsHeaders(res: Response) { res.headers.set("Access-Control-Allow-Origin", "*"); res.headers.set("Access-Control-Request-Method", "*"); res.headers.set("Access-Control-Allow-Methods", "OPTIONS, GET, POST"); res.headers.set("Access-Control-Allow-Headers", "*"); }
/** * Configure basic CORS headers * You should extend this to match your needs */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/apps/nextjs/src/app/api/trpc/[trpc]/route.ts#L12-L17
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
replace
const replace = (newUrl: string) => { window.history.replaceState({ ...window.history.state, as: newUrl, url: newUrl }, "", newUrl); };
// Replace state without fetchign new data
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/apps/nextjs/src/components/active-tab-accordion.tsx#L13-L15
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
handleResizeChange
const handleResizeChange = ( wrapper: HTMLDivElement, gridstack: GridStack, width: number, height: number, isDynamic: boolean, ) => { wrapper.style.setProperty("--gridstack-column-count", width.toString()); wrapper.style.setProperty("--gridstack-row-count", height.toString()); let cellHeight = wrapper.clientWidth / width; if (isDynamic) { cellHeight = wrapper.clientHeight / height; } if (!isDynamic) { document.body.style.setProperty("--gridstack-cell-size", cellHeight.toString()); } gridstack.cellHeight(cellHeight); };
/** * When the size of a gridstack changes we need to update the css variables * so the gridstack items are displayed correctly * @param wrapper gridstack wrapper * @param gridstack gridstack object * @param width width of the section (column count) * @param height height of the section (row count) * @param isDynamic if the section is dynamic */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/apps/nextjs/src/components/board/sections/gridstack/use-gridstack.ts#L34-L54
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
useCssVariableConfiguration
const useCssVariableConfiguration = ({ gridRef, wrapperRef, width, height, columnCount, isDynamic, }: UseCssVariableConfiguration) => { const onResize = useCallback(() => { if (!wrapperRef.current) return; if (!gridRef.current) return; handleResizeChange( wrapperRef.current, gridRef.current, gridRef.current.getColumn(), gridRef.current.getRow(), isDynamic, ); }, [wrapperRef, gridRef, isDynamic]); useCallback(() => { if (!wrapperRef.current) return; if (!gridRef.current) return; wrapperRef.current.style.setProperty("--gridstack-column-count", gridRef.current.getColumn().toString()); wrapperRef.current.style.setProperty("--gridstack-row-count", gridRef.current.getRow().toString()); let cellHeight = wrapperRef.current.clientWidth / gridRef.current.getColumn(); if (isDynamic) { cellHeight = wrapperRef.current.clientHeight / gridRef.current.getRow(); } gridRef.current.cellHeight(cellHeight); }, [wrapperRef, gridRef, isDynamic]); // Define widget-width by calculating the width of one column with mainRef width and column count useEffect(() => { onResize(); if (typeof window === "undefined") return; window.addEventListener("resize", onResize); const wrapper = wrapperRef.current; wrapper?.addEventListener("resize", onResize); return () => { if (typeof window === "undefined") return; window.removeEventListener("resize", onResize); wrapper?.removeEventListener("resize", onResize); }; }, [wrapperRef, gridRef, onResize]); // Handle resize of inner sections when there size changes useEffect(() => { onResize(); }, [width, height, onResize]); // Define column count by using the sectionColumnCount useEffect(() => { wrapperRef.current?.style.setProperty("--gridstack-column-count", columnCount.toString()); }, [columnCount, wrapperRef]); };
/** * This hook is used to configure the css variables for the gridstack * Those css variables are used to define the size of the gridstack items * @see gridstack.scss * @param gridRef reference to the gridstack object * @param wrapperRef reference to the wrapper of the gridstack * @param width width of the section * @param height height of the section * @param columnCount column count of the gridstack */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/apps/nextjs/src/components/board/sections/gridstack/use-gridstack.ts#L311-L369
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
importCookiesAsync
async function importCookiesAsync() { if (typeof window !== "undefined") { return null; } const { cookies } = await import("next/headers"); return (await cookies()) .getAll() .map(({ name, value }) => `${name}=${value}`) .join(";"); }
/** * This is a workarround as cookies are not passed to the server * when using useSuspenseQuery or middleware * @returns cookie string on server or null on client */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/shared.ts#L27-L38
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
throwIfActionIsNotAllowedAsync
const throwIfActionIsNotAllowedAsync = async ( action: IntegrationAction, db: Database, integrations: Parameters<typeof hasQueryAccessToIntegrationsAsync>[1], session: Session | null, ) => { if (action === "interact") { const haveAllInteractAccess = integrations .map((integration) => constructIntegrationPermissions(integration, session)) .every(({ hasInteractAccess }) => hasInteractAccess); if (haveAllInteractAccess) return; throw new TRPCError({ code: "FORBIDDEN", message: "User does not have permission to interact with at least one of the specified integrations", }); } const hasQueryAccess = await hasQueryAccessToIntegrationsAsync(db, integrations, session); if (hasQueryAccess) return; throw new TRPCError({ code: "FORBIDDEN", message: "User does not have permission to query at least one of the specified integration", }); };
/** * Throws a TRPCError FORBIDDEN if the user does not have permission to perform the specified action on at least one of the specified integrations * @param action action to perform * @param db db instance * @param integrations integrations to check permissions for * @param session session of the user * @throws TRPCError FORBIDDEN if the user does not have permission to perform the specified action on at least one of the specified integrations */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/middlewares/integration.ts#L164-L190
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
getHomeIdBoardAsync
const getHomeIdBoardAsync = async ( db: Database, user: InferSelectModel<typeof users> | null, deviceType: DeviceType, ) => { const settingKey = deviceType === "mobile" ? "mobileHomeBoardId" : "homeBoardId"; if (user?.[settingKey] || user?.homeBoardId) { return user[settingKey] ?? user.homeBoardId; } else { const boardSettings = await getServerSettingByKeyAsync(db, "board"); return boardSettings[settingKey] ?? boardSettings.homeBoardId; } };
/** * Get the home board id of the user with the given device type * For an example of a user with deviceType = 'mobile' it would go through the following order: * 1. user.mobileHomeBoardId * 2. user.homeBoardId * 3. serverSettings.mobileHomeBoardId * 4. serverSettings.homeBoardId * 5. show NOT_FOUND error */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/board.ts#L982-L994
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
notAllowed
function notAllowed(): never { throw new TRPCError({ code: "NOT_FOUND", message: "Board not found", }); }
/** * This method returns NOT_FOUND to prevent snooping on board existence * A function is used to use the method without return statement */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/board/board-access.ts#L67-L72
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
notAllowed
function notAllowed(): never { throw new TRPCError({ code: "NOT_FOUND", message: "Integration not found", }); }
/** * This method returns NOT_FOUND to prevent snooping on board existence * A function is used to use the method without return statement */
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/integration/integration-access.ts#L68-L73
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.all();
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/app.spec.ts#L64-L64
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.byId({ id: "2" });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/app.spec.ts#L124-L124
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.update({ id: createId(), name: "Mantine", iconUrl: "https://mantine.dev/favicon.svg", description: null, href: null, });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/app.spec.ts#L253-L260
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.createBoard({ name: "newBoard", columnCount: 12, isPublic: true });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/board.spec.ts#L325-L325
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.renameBoard({ id: boardId, name: "Newname" });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/board.spec.ts#L382-L382
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.renameBoard({ id: "nonExistentBoardId", name: "newName" });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/board.spec.ts#L394-L394
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.deleteBoard({ id: "nonExistentBoardId" });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/board.spec.ts#L472-L472
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.getHomeBoard();
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/board.spec.ts#L533-L533
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.getBoardByName({ name: "nonExistentBoard" });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/board.spec.ts#L567-L567
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.getPaginated({});
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/group.spec.ts#L146-L146
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.getById({ id: "1" });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/group.spec.ts#L208-L208
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.createGroup({ name: longName, });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/group.spec.ts#L259-L262
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.createGroup({ name: nameToCreate });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/group.spec.ts#L284-L284
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.createGroup({ name: "test" });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/group.spec.ts#L296-L296
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.updateGroup({ id: groupId, name: updateValue, });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/group.spec.ts#L358-L362
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
act
const act = () => caller.updateGroup({ id: createId(), name: "something else", });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/group.spec.ts#L379-L383
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.updateGroup({ id: createId(), name: "test", });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/group.spec.ts#L395-L399
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.savePermissions({ groupId: createId(), permissions: ["integration-create", "board-full-all"], });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/group.spec.ts#L448-L452
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.transferOwnership({ groupId: createId(), userId: createId(), });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/group.spec.ts#L524-L528
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.deleteGroup({ id: createId(), });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/group.spec.ts#L592-L595
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.addMember({ groupId: createId(), userId: createId(), });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/group.spec.ts#L669-L673
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.addMember({ groupId, userId, });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/group.spec.ts#L721-L725
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.removeMember({ groupId: createId(), userId: createId(), });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/group.spec.ts#L787-L791
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.removeMember({ groupId, userId, });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/group.spec.ts#L843-L847
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.deleteInvite({ id: createId() });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/invite.spec.ts#L202-L202
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.register({ inviteId, token: inviteToken, username: "test", password: "123ABCdef+/-", confirmPassword: "123ABCdef+/-", ...partialInput, });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/user.spec.ts#L192-L200
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
act
const act = () => throwIfActionForbiddenAsync({ db, session: null }, eq(boards.id, boardId), permission);
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/board/board-access.spec.ts#L45-L45
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
act
const act = () => throwIfActionForbiddenAsync({ db, session: null }, eq(boards.id, createId()), "full");
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/board/board-access.spec.ts#L143-L143
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
act
const act = () => caller[procedure](validInputs[procedure] as never);
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/docker/docker-router.spec.ts#L60-L60
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
act
const act = () => throwIfActionForbiddenAsync({ db, session: null }, eq(integrations.id, integrationId), permission);
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/integration/integration-access.spec.ts#L45-L46
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
act
const act = () => throwIfActionForbiddenAsync({ db, session: null }, eq(integrations.id, createId()), "full");
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/integration/integration-access.spec.ts#L150-L150
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.byId({ id: "1" });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/integration/integration-router.spec.ts#L168-L168
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.create(input);
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/integration/integration-router.spec.ts#L271-L271
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.update({ id: createId(), name: "Pi Hole", url: "http://hole.local", secrets: [], });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/integration/integration-router.spec.ts#L362-L368
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
actAsync
const actAsync = async () => await caller.delete({ id: createId() });
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/router/test/integration/integration-router.spec.ts#L439-L439
d508fd466d942a15196918742f768e57a6971e09
homarr
github_2023
homarr-labs
typescript
act
const act = () => openApiDocument(base);
// Act
https://github.com/homarr-labs/homarr/blob/d508fd466d942a15196918742f768e57a6971e09/packages/api/src/test/open-api.spec.ts#L12-L12
d508fd466d942a15196918742f768e57a6971e09