merge master

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>
This commit is contained in:
Jari Kolehmainen committed 2020-11-18 14:46:30 +02:00
commit 5b0efe2c86
372 files changed
+37735 -4427

No files matched your search

+80
View File
@@ -0,0 +1,80 @@
/**
* @jest-environment jsdom
*/
import { SearchStore } from "../search-store"
let searchStore: SearchStore = null;
const logs = [
"1:M 30 Oct 2020 16:17:41.553 # Connection with replica 172.17.0.12:6379 lost",
"1:M 30 Oct 2020 16:17:41.623 * Replica 172.17.0.12:6379 asks for synchronization",
"1:M 30 Oct 2020 16:17:41.623 * Starting Partial resynchronization request from 172.17.0.12:6379 accepted. Sending 0 bytes of backlog starting from offset 14407."
]
describe("search store tests", () => {
beforeEach(async () => {
searchStore = new SearchStore();
})
it("does nothing with empty search query", () => {
searchStore.onSearch([], "");
expect(searchStore.occurrences).toEqual([]);
})
it("doesn't break if no text provided", () => {
searchStore.onSearch(null, "replica");
expect(searchStore.occurrences).toEqual([]);
searchStore.onSearch([], "replica");
expect(searchStore.occurrences).toEqual([]);
})
it("find 3 occurences across 3 lines", () => {
searchStore.onSearch(logs, "172");
expect(searchStore.occurrences).toEqual([0, 1, 2]);
})
it("find occurences within 1 line (case-insensitive)", () => {
searchStore.onSearch(logs, "Starting");
expect(searchStore.occurrences).toEqual([2, 2]);
})
it("sets overlay index equal to first occurence", () => {
searchStore.onSearch(logs, "Replica");
expect(searchStore.activeOverlayIndex).toBe(0);
})
it("set overlay index to next occurence", () => {
searchStore.onSearch(logs, "172");
searchStore.setNextOverlayActive();
expect(searchStore.activeOverlayIndex).toBe(1);
})
it("sets overlay to last occurence", () => {
searchStore.onSearch(logs, "172");
searchStore.setPrevOverlayActive();
expect(searchStore.activeOverlayIndex).toBe(2);
})
it("gets line index where overlay is located", () => {
searchStore.onSearch(logs, "synchronization");
expect(searchStore.activeOverlayLine).toBe(1);
})
it("escapes string for using in regex", () => {
const regex = searchStore.escapeRegex("some.interesting-query\\#?()[]");
expect(regex).toBe("some\\.interesting\\-query\\\\\\#\\?\\(\\)\\[\\]");
})
it("gets active find number", () => {
searchStore.onSearch(logs, "172");
searchStore.setNextOverlayActive();
expect(searchStore.activeFind).toBe(2);
})
it("gets total finds number", () => {
searchStore.onSearch(logs, "Starting");
expect(searchStore.totalFinds).toBe(2);
})
})
+3 -2
View File
@@ -57,11 +57,12 @@ describe("user store tests", () => {
expect(us.preferences.colorTheme).toBe('light')
})
it("correctly resets theme to default value", () => {
it("correctly resets theme to default value", async () => {
const us = UserStore.getInstance<UserStore>();
us.isLoaded = true;
us.preferences.colorTheme = "some other theme";
us.resetTheme();
await us.resetTheme();
expect(us.preferences.colorTheme).toBe(UserStore.defaultTheme);
})
+7 -4
View File
@@ -38,15 +38,18 @@ describe("workspace store tests", () => {
expect(() => ws.removeWorkspaceById(WorkspaceStore.defaultId)).toThrowError("Cannot remove");
})
it("can update default workspace name", () => {
it("can update workspace description", () => {
const ws = WorkspaceStore.getInstance<WorkspaceStore>();
ws.addWorkspace(new Workspace({
id: WorkspaceStore.defaultId,
const workspace = ws.addWorkspace(new Workspace({
id: "foobar",
name: "foobar",
}));
expect(ws.currentWorkspace.name).toBe("foobar");
workspace.description = "Foobar description";
ws.updateWorkspace(workspace);
expect(ws.getById("foobar").description).toBe("Foobar description");
})
it("can add workspaces", () => {
+13 -7
View File
@@ -2,7 +2,7 @@ import path from "path"
import Config from "conf"
import { Options as ConfOptions } from "conf/dist/source/types"
import { app, ipcMain, IpcMainEvent, ipcRenderer, IpcRendererEvent, remote } from "electron"
import { action, observable, reaction, runInAction, toJS, when } from "mobx";
import { action, IReactionOptions, observable, reaction, runInAction, toJS, when } from "mobx";
import Singleton from "./utils/singleton";
import { getAppVersion } from "./utils/app-version";
import logger from "../main/logger";
@@ -12,6 +12,7 @@ import isEqual from "lodash/isEqual";
export interface BaseStoreParams<T = any> extends ConfOptions<T> {
autoLoad?: boolean;
syncEnabled?: boolean;
syncOptions?: IReactionOptions;
}
export class BaseStore<T = any> extends Singleton {
@@ -20,7 +21,7 @@ export class BaseStore<T = any> extends Singleton {
whenLoaded = when(() => this.isLoaded);
@observable isLoaded = false;
@observable protected data: T;
@observable data = {} as T;
protected constructor(protected params: BaseStoreParams) {
super();
@@ -44,6 +45,10 @@ export class BaseStore<T = any> extends Singleton {
return `store-sync-main:${this.name}`
}
get path() {
return this.storeConfig.path;
}
protected async init() {
if (this.params.autoLoad) {
await this.load();
@@ -60,19 +65,19 @@ export class BaseStore<T = any> extends Singleton {
...confOptions,
projectName: "lens",
projectVersion: getAppVersion(),
cwd: this.storePath(),
cwd: this.cwd(),
});
logger.info(`[STORE]: LOADED from ${this.storeConfig.path}`);
logger.info(`[STORE]: LOADED from ${this.path}`);
this.fromStore(this.storeConfig.store);
this.isLoaded = true;
}
protected storePath() {
protected cwd() {
return (app || remote.app).getPath("userData")
}
protected async saveToFile(model: T) {
logger.info(`[STORE]: SAVING ${this.name}`);
logger.info(`[STORE]: SAVING ${this.path}`);
// todo: update when fixed https://github.com/sindresorhus/conf/issues/114
Object.entries(model).forEach(([key, value]) => {
this.storeConfig.set(key, value);
@@ -81,7 +86,7 @@ export class BaseStore<T = any> extends Singleton {
enableSync() {
this.syncDisposers.push(
reaction(() => this.toJSON(), model => this.onModelChange(model)),
reaction(() => this.toJSON(), model => this.onModelChange(model), this.params.syncOptions),
);
if (ipcMain) {
const callback = (event: IpcMainEvent, model: T) => {
@@ -143,6 +148,7 @@ export class BaseStore<T = any> extends Singleton {
@action
protected fromStore(data: T) {
if (!data) return;
this.data = data;
}
+4 -3
View File
@@ -40,6 +40,7 @@ export interface ClusterModel {
preferences?: ClusterPreferences;
metadata?: ClusterMetadata;
ownerRef?: string;
accessibleNamespaces?: string[];
/** @deprecated */
kubeConfig?: string; // yaml
@@ -183,8 +184,8 @@ export class ClusterStore extends BaseStore<ClusterStoreModel> {
}
@action
addCluster(model: ClusterModel | Cluster ): Cluster {
appEventBus.emit({name: "cluster", action: "add"})
addCluster(model: ClusterModel | Cluster): Cluster {
appEventBus.emit({ name: "cluster", action: "add" })
let cluster = model as Cluster;
if (!(model instanceof Cluster)) {
cluster = new Cluster(model)
@@ -199,7 +200,7 @@ export class ClusterStore extends BaseStore<ClusterStoreModel> {
@action
async removeById(clusterId: ClusterId) {
appEventBus.emit({name: "cluster", action: "remove"})
appEventBus.emit({ name: "cluster", action: "remove" })
const cluster = this.getById(clusterId);
if (cluster) {
this.clusters.delete(clusterId);
+126
View File
@@ -0,0 +1,126 @@
import { action, computed, observable } from "mobx";
import { autobind } from "../renderer/utils";
export class SearchStore {
@observable searchQuery = ""; // Text in the search input
@observable occurrences: number[] = []; // Array with line numbers, eg [0, 0, 10, 21, 21, 40...]
@observable activeOverlayIndex = -1; // Index withing the occurences array. Showing where is activeOverlay currently located
/**
* Sets default activeOverlayIndex
* @param text An array of any textual data (logs, for example)
* @param query Search query from input
*/
@action
onSearch(text: string[], query = this.searchQuery) {
this.searchQuery = query;
if (!query) {
this.reset();
return;
}
this.occurrences = this.findOccurences(text, query);
if (!this.occurrences.length) return;
// If new highlighted keyword in exact same place as previous one, then no changing in active overlay
if (this.occurrences[this.activeOverlayIndex] !== undefined) return;
this.activeOverlayIndex = this.getNextOverlay(true);
}
/**
* Does searching within text array, create a list of search keyword occurences.
* Each keyword "occurency" is saved as index of the the line where keyword founded
* @param text An array of any textual data (logs, for example)
* @param query Search query from input
* @returns {Array} Array of line indexes [0, 0, 14, 17, 17, 17, 20...]
*/
findOccurences(text: string[], query: string) {
if (!text) return [];
const occurences: number[] = [];
text.forEach((line, index) => {
const regex = new RegExp(this.escapeRegex(query), "gi");
const matches = [...line.matchAll(regex)];
matches.forEach(() => occurences.push(index));
});
return occurences;
}
/**
* Getting next overlay index within the occurences array
* @param loopOver Allows to jump from last element to first
* @returns {number} next overlay index
*/
getNextOverlay(loopOver = false) {
const next = this.activeOverlayIndex + 1;
if (next > this.occurrences.length - 1) {
return loopOver ? 0 : this.activeOverlayIndex;
}
return next;
}
/**
* Getting previous overlay index within the occurences array of occurences
* @param loopOver Allows to jump from first element to last one
* @returns {number} prev overlay index
*/
getPrevOverlay(loopOver = false) {
const prev = this.activeOverlayIndex - 1;
if (prev < 0) {
return loopOver ? this.occurrences.length - 1 : this.activeOverlayIndex;
}
return prev;
}
@autobind()
setNextOverlayActive() {
this.activeOverlayIndex = this.getNextOverlay(true);
}
@autobind()
setPrevOverlayActive() {
this.activeOverlayIndex = this.getPrevOverlay(true);
}
/**
* Gets line index of where active overlay is located
* @returns {number} A line index within the text/logs array
*/
@computed get activeOverlayLine(): number {
return this.occurrences[this.activeOverlayIndex];
}
@computed get activeFind(): number {
return this.activeOverlayIndex + 1;
}
@computed get totalFinds(): number {
return this.occurrences.length;
}
/**
* Checks if overlay is active (to highlight it with orange background usually)
* @param line Index of the line where overlay is located
* @param occurence Number of the overlay within one line
*/
@autobind()
isActiveOverlay(line: number, occurence: number) {
const firstLineIndex = this.occurrences.findIndex(item => item === line);
return firstLineIndex + occurence === this.activeOverlayIndex;
}
/**
* An utility methods escaping user string to safely pass it into new Regex(variable)
* @param value Unescaped string
*/
escapeRegex(value: string) {
return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
}
@action
reset() {
this.searchQuery = "";
this.activeOverlayIndex = -1;
this.occurrences = [];
}
}
export const searchStore = new SearchStore;
+3 -2
View File
@@ -31,7 +31,7 @@ export interface UserPreferences {
}
export class UserStore extends BaseStore<UserStoreModel> {
static readonly defaultTheme: ThemeId = "kontena-dark"
static readonly defaultTheme: ThemeId = "lens-dark"
private constructor() {
super({
@@ -88,7 +88,8 @@ export class UserStore extends BaseStore<UserStoreModel> {
}
@action
resetTheme() {
async resetTheme() {
await this.whenLoaded;
this.preferences.colorTheme = UserStore.defaultTheme;
}
+1 -1
View File
@@ -4,6 +4,6 @@ export function debouncePromise<T, F extends any[]>(func: (...args: F) => T | Pr
let timer: NodeJS.Timeout;
return (...params: any[]) => new Promise((resolve, reject) => {
clearTimeout(timer);
timer = setTimeout(() => resolve(func.apply(this, params)), timeout);
timer = global.setTimeout(() => resolve(func.apply(this, params)), timeout);
});
}
+2 -1
View File
@@ -1,7 +1,8 @@
// Save file to electron app directory (e.g. "/Users/$USER/Library/Application Support/Lens" for MacOS)
import path from "path";
import { app, remote } from "electron";
import { ensureDirSync, writeFileSync, WriteFileOptions } from "fs-extra";
import { ensureDirSync, writeFileSync } from "fs-extra";
import { WriteFileOptions } from "fs"
export function saveToAppFiles(filePath: string, contents: any, options?: WriteFileOptions): string {
const absPath = path.resolve((app || remote.app).getPath("userData"), filePath);
+1
View File
@@ -22,6 +22,7 @@ export const mainDir = path.join(contextDir, "src/main");
export const rendererDir = path.join(contextDir, "src/renderer");
export const htmlTemplate = path.resolve(rendererDir, "template.html");
export const sassCommonVars = path.resolve(rendererDir, "components/vars.scss");
export const webpackDevServerPort = 9009
// Special runtime paths
defineGlobal("__static", {
+7 -7
View File
@@ -150,20 +150,20 @@ export class WorkspaceStore extends BaseStore<WorkspaceStoreModel> {
@action
addWorkspace(workspace: Workspace) {
const { id, name } = workspace;
const existingWorkspace = this.getById(id);
if (!name.trim() || this.getByName(name.trim())) {
return;
}
if (existingWorkspace) {
Object.assign(existingWorkspace, workspace);
appEventBus.emit({name: "workspace", action: "update"})
} else {
appEventBus.emit({name: "workspace", action: "add"})
}
this.workspaces.set(id, workspace);
appEventBus.emit({name: "workspace", action: "add"})
return workspace;
}
@action
updateWorkspace(workspace: Workspace) {
this.workspaces.set(workspace.id, workspace);
appEventBus.emit({name: "workspace", action: "update"});
}
@action
removeWorkspace(workspace: Workspace) {
this.removeWorkspaceById(workspace.id)