repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
doc-solver | github_2023 | ai-hermes | typescript | Typewriter.add | add(str: string) {
if (!str) return
this.queue.push(...str.split(''))
} | /**
* when llm output, it should be add to queue by add method
* @param str
* @returns
*/ | https://github.com/ai-hermes/doc-solver/blob/8f7752e36df3c1f333ec8edb42eb1755a914af34/utils/typewriter.ts#L25-L28 | 8f7752e36df3c1f333ec8edb42eb1755a914af34 |
doc-solver | github_2023 | ai-hermes | typescript | Typewriter.consume | consume() {
if (this.queue.length > 0) {
const str = this.queue.shift()
str && this.onConsume(str)
}
} | /**
* shift the first char in the queue, and call onConsume passed by user
*/ | https://github.com/ai-hermes/doc-solver/blob/8f7752e36df3c1f333ec8edb42eb1755a914af34/utils/typewriter.ts#L32-L37 | 8f7752e36df3c1f333ec8edb42eb1755a914af34 |
doc-solver | github_2023 | ai-hermes | typescript | Typewriter.next | next() {
this.consume()
// set a timer to consume the next char in the queue
this.timer = setTimeout(() => {
this.consume()
if (this.consuming) {
this.next()
}
}, this.dynamicSpeed())
} | /**
* consume next char in the queue, by recursion
*/ | https://github.com/ai-hermes/doc-solver/blob/8f7752e36df3c1f333ec8edb42eb1755a914af34/utils/typewriter.ts#L41-L50 | 8f7752e36df3c1f333ec8edb42eb1755a914af34 |
doc-solver | github_2023 | ai-hermes | typescript | Typewriter.start | start() {
this.consuming = true
this.next()
} | /**
* start consuming the queue
*/ | https://github.com/ai-hermes/doc-solver/blob/8f7752e36df3c1f333ec8edb42eb1755a914af34/utils/typewriter.ts#L54-L57 | 8f7752e36df3c1f333ec8edb42eb1755a914af34 |
doc-solver | github_2023 | ai-hermes | typescript | Typewriter.done | done() {
this.consuming = false
this.timer && clearTimeout(this.timer)
this.onConsume(this.queue.join(''))
this.queue = []
} | /**
* consume the rest of the queue, and stop process of consuming
*/ | https://github.com/ai-hermes/doc-solver/blob/8f7752e36df3c1f333ec8edb42eb1755a914af34/utils/typewriter.ts#L61-L66 | 8f7752e36df3c1f333ec8edb42eb1755a914af34 |
terkelg | github_2023 | terkelg | typescript | levelToInt | const levelToInt = (level: Contribution['contributionLevel']) => {
switch (level) {
case 'NONE':
return 0;
case 'FIRST_QUARTILE':
return 1;
case 'SECOND_QUARTILE':
return 2;
case 'THIRD_QUARTILE':
return 3;
case 'FOURTH_QUARTILE':
return 4;
}
}; | /**
* Turn the GitHub contribution level into a number
* @param level Contribution level
*/ | https://github.com/terkelg/terkelg/blob/a88a9be2f5ebb21cd883a2981952024ee764a89d/scripts/stats.ts#L79-L92 | a88a9be2f5ebb21cd883a2981952024ee764a89d |
terkelg | github_2023 | terkelg | typescript | getAllContributions | async function getAllContributions(start: Date, end = new Date()) {
const years: Year[] = [];
let cursor = start;
let contributions = 0;
while (cursor < end) {
let next = new Date(cursor.getFullYear() + 1, 0, 1);
// prevent fetching data beyond the current date
if (next > end) next = end;
console.info('...Fetching from', cursor.toISOString(), next.toISOString());
const data = await request({ to: next, from: cursor });
contributions += data.contributions;
years.push({
from: cursor.toISOString(),
to: next.toISOString(),
days: data.weeks
.flatMap((week) => week.contributionDays.map((day) => levelToInt(day.contributionLevel)))
.reverse()
});
cursor = next;
}
return [years.reverse(), contributions];
} | /**
* Retrieves GitHub contributions within a specified date range.
* Automatically handles pagination and fetches all contributions.
* Limited to fetching 1-year intervals per GitHub's current restrictions.
* Sorts contributions in reverse chronological order, showing most recent commits first.
*/ | https://github.com/terkelg/terkelg/blob/a88a9be2f5ebb21cd883a2981952024ee764a89d/scripts/stats.ts#L100-L122 | a88a9be2f5ebb21cd883a2981952024ee764a89d |
react-native-release-profiler | github_2023 | margelo | typescript | getLatestFile | function getLatestFile(packageNameWithSuffix: string): string {
try {
const file =
execSync(`adb shell run-as ${packageNameWithSuffix} ls cache/ -tp | grep -v /$ | grep -E '.cpuprofile' | head -1
`);
return file.toString().trim();
} catch (e) {
throw e;
}
} | // Most of the file is just a copy of https://github.com/react-native-community/cli/blob/main/packages/cli-hermes/src/profileHermes/downloadProfile.ts | https://github.com/margelo/react-native-release-profiler/blob/25e3d343f747e7d10c3a75d72af1d586f15df4a5/src/cli.ts#L18-L27 | 25e3d343f747e7d10c3a75d72af1d586f15df4a5 |
react-native-release-profiler | github_2023 | margelo | typescript | jsonStringify | function jsonStringify(obj: any) {
return JSON.stringify(obj, undefined, 4);
} | /**
* A wrapper that converts an object to JSON with 4 spaces for indentation.
*
* @param obj Any object that can be represented as JSON
* @returns A JSON string
*/ | https://github.com/margelo/react-native-release-profiler/blob/25e3d343f747e7d10c3a75d72af1d586f15df4a5/src/cli.ts#L40-L42 | 25e3d343f747e7d10c3a75d72af1d586f15df4a5 |
obsidian-clever-search | github_2023 | yan42685 | typescript | testTokenizer | async function testTokenizer() {
// getInstance(SearchClient).testTickToken()
// getInstance(AssetsProvider).startDownload();
const cutter = getInstance(ChinesePatch);
const tokenizer = getInstance(Tokenizer);
// const text= "今天天气气候不错啊";
// const text= "陈志敏今天似乎好像没有来学校学习啊";
// const text= "In this digital age, 在这个数字时代, let's embrace the wisdom of the past while pushing the boundaries of the future. 让我们在推动未来的同时,拥抱过去的智慧。 past whileaaaaaaa";
// const text= "smart-Connection用起来还不错";
// const text = "camelCase嗟尔远道之人胡为乎来哉";
// const text = "abc/def/knsusg abc#def#ddd camelCase this-boy bush#真好 谷歌is a good thing";
// const text = "他来到了网易杭研大厦";
// const text = "生命的象征";
// const text = "个遮阳避雨的安全之所。"
const text = "abc/nef/adg";
logger.info(cutter.cut(text, false));
logger.info(cutter.cut(text, true));
logger.info(tokenizer.tokenize(text, "index"));
logger.info(tokenizer.tokenize(text, "search"));
logger.info(getInstance(AssetsProvider).assets.stopWordsZh?.size);
logger.info(getInstance(AssetsProvider).assets.stopWordsZh?.has("的"));
} | // async function testLexicalSearch() { | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/dev-test.ts#L77-L99 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | FileItem.viewType | get viewType(): ViewType {
return getInstance(ViewRegistry).viewTypeByPath(this.path);
} | // TODO: store the view type rather than relying on obsidian api | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/globals/search-types.ts#L105-L107 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | OmnisearchIntegration.getLastQuery | async getLastQuery(): Promise<string> {
let lastQuery = "";
if (this.checkOmnisearchStatus()) {
const recentQueries = await this.db.searchHistory.toArray();
lastQuery =
recentQueries.length !== 0
? recentQueries[recentQueries.length - 1].query
: "";
// console.log("last query: " + lastQuery);
}
return lastQuery;
} | /**
* get the last query from database created by omnisearch.
*/ | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/integrations/omnisearch.ts#L36-L47 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | Database.setMiniSearchData | async setMiniSearchData(data: AsPlainObject) {
this.db.transaction("rw", this.db.minisearch, async () => {
// Warning: The clear() here is just a marker for caution to avoid data duplication.
// Ideally, clear() should be executed at an earlier stage.
// Placing clear() and add() together, especially with large data sets,
// may lead to conflicts and cause Obsidian to crash. It is an issue related to Dexie or IndexedDB
await this.db.minisearch.clear();
await this.db.minisearch.add({ data: data });
logger.trace("minisearch data saved");
});
} | // it may finished some time later even if using await | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/database/database.ts#L18-L28 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | Database.deleteOldDatabases | async deleteOldDatabases() {
const toDelete = (await indexedDB.databases()).filter(
(db) =>
db.name === this.db.dbName &&
// version multiplied by 10 https://github.com/dexie/Dexie.js/issues/59
db.version !== this.db.dbVersion * 10,
);
if (toDelete.length) {
logger.info("Old version databases will be deleted");
for (const db of toDelete) {
if (db.name) {
indexedDB.deleteDatabase(db.name);
}
}
}
} | // copied from https://github.com/scambier/obsidian-omnisearch/blob/master/src/database.ts#L36 | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/database/database.ts#L73-L88 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | CommandRegistry.addDevCommands | addDevCommands() {
if (isDevEnvironment) {
this.addCommand({
id: "cs-in-file-search-floating-window",
name: "In file search - floating window",
callback: () =>
getInstance(FloatingWindowManager).toggle("inFile"),
});
this.addCommand({
id: "clever-search-triggerTest",
name: "clever-search-triggerTest",
// hotkeys: [{modifiers: [currModifier], key: "5"}],
callback: async () => await devTest(),
});
}
} | // only for developer | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/obsidian/command-registry.ts#L37-L54 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | PluginManager.onload | async onload() {
await getInstance(SettingManager).initAsync();
getInstance(ViewRegistry).init();
if (isDevEnvironment) {
logger.warn("仅在开发模式开启RecentFileManager")
getInstance(RecentFileManager).init();
}
getInstance(CommandRegistry).addCommandsWithoutDependency();
await getInstance(AssetsProvider).initAsync();
await getInstance(ChinesePatch).initAsync();
await getInstance(SearchClient).createChildThreads();
getInstance(AuxiliaryService).init();
} | // private readonly obFileUtil = getInstance(Vault).adapter as FileSystemAdapter; | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/obsidian/plugin-manager.ts#L20-L35 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | PluginManager.onunload | onunload() {
getInstance(CommandRegistry).onunload();
getInstance(DataManager).onunload();
getInstance(FloatingWindowManager).onunload();
} | // should be called in CleverSearch.onunload() | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/obsidian/plugin-manager.ts#L46-L50 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | SearchService.deprecatedSearchInFile | async deprecatedSearchInFile(queryText: string): Promise<SearchResult> {
const result = new SearchResult("", []);
const activeFile = this.app.workspace.getActiveFile();
if (
!queryText ||
!activeFile ||
this.viewRegistry.viewTypeByPath(activeFile.path) !==
ViewType.MARKDOWN
) {
return result;
}
const path = activeFile.path;
const lines = (await this.dataProvider.readPlainTextLines(path)).map(
(line, index) => new Line(line, index),
);
const lineItems = await this.lineHighlighter.parseLineItems(
lines,
queryText,
);
return {
sourcePath: path,
items: lineItems,
} as SearchResult;
} | /**
* @deprecated since 0.1.x, use SearchService.searchInFile instead
*/ | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/obsidian/search-service.ts#L184-L210 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | SettingManager.saveSettings | async saveSettings() {
await this.plugin.saveData(this.setting);
} | // NOTE: this.plugin.saveData() can't handle Set | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/obsidian/setting-manager.ts#L42-L44 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | GeneralTab.constructor | constructor(@inject(THIS_PLUGIN) plugin: CleverSearch) {
super(plugin.app, plugin);
} | // BE CAUTIOUS | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/obsidian/setting-manager.ts#L87-L89 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | ViewRegistry.viewTypeByPath | viewTypeByPath(path: string): ViewType {
const viewType = this.extensionViewMap.get(FileUtil.getExtension(path));
return viewType === undefined ? ViewType.UNSUPPORTED : viewType;
} | // return the viewType in obsidian by path | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/obsidian/view-registry.ts#L44-L47 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | DataManager.updateDocRefByMtime | private async updateDocRefByMtime(isSemantic: boolean) {
// update index data based on file modification time
const currFiles = new Map<string, TFile>(
this.dataProvider
.allFilesToBeIndexed()
.map((file) => [file.path, file]),
);
const preRefsList = isSemantic
? await this.database.getSemanticDocRefs()
: await this.database.getLexicalDocRefs();
const prevRefs = new Map<string, DocumentRef>(
preRefsList?.map((ref) => [ref.path, ref]),
);
const docsToAdd: TAbstractFile[] = [];
const docsToDelete: string[] = [];
for (const [path, file] of currFiles) {
const prevRef = prevRefs.get(path);
if (!prevRef) {
// to add
docsToAdd.push(file);
} else if (file.stat.mtime > prevRef.updateTime) {
// to update
docsToDelete.push(file.path);
docsToAdd.push(file);
}
}
// to delete
for (const prevPath of prevRefs.keys()) {
if (!currFiles.has(prevPath)) {
docsToDelete.push(prevPath);
}
}
// perform batch delete and add operations
logger.trace(`docs to delete: ${docsToDelete.length}`);
logger.trace(`docs to add: ${docsToAdd.length}`);
await this.deleteDocuments(docsToDelete, isSemantic);
await this.addDocuments(docsToAdd, isSemantic);
await this.saveDocRefs(Array.from(currFiles.values()), isSemantic);
} | // use case: users have changed files without obsidian open. so we need to update the index and refs | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/obsidian/user-data/data-manager.ts#L188-L230 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | DataProvider.init | init() {
this.excludedPaths = new Set(this.setting.excludedPaths);
this.supportedExtensions = new Set(
this.setting.customExtensions.plaintext,
);
} | // update internal states based on OuterSetting | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/obsidian/user-data/data-provider.ts#L40-L45 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | DataProvider.allFilesToBeIndexed | allFilesToBeIndexed(): TFile[] {
// get all fileRefs cached by obsidian
const files = this.vault.getFiles();
logger.debug(`all files: ${files.length}`);
FileUtil.countFileByExtensions(files);
const filesToIndex = files.filter((file) => this.isIndexable(file));
logger.debug(`indexable files: ${filesToIndex.length}`);
FileUtil.countFileByExtensions(filesToIndex);
return filesToIndex;
} | // @monitorDecorator | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/obsidian/user-data/data-provider.ts#L82-L93 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | DataProvider.readPlainText | async readPlainText(fileOrPath: TFile | string): Promise<string> {
const file =
typeof fileOrPath === "string"
? this.vault.getAbstractFileByPath(fileOrPath)
: fileOrPath;
if (file instanceof TFile) {
if (
this.viewRegistry.viewTypeByPath(file.path) ===
ViewType.MARKDOWN
) {
const plainText = await this.vault.cachedRead(file);
// return plainText;
return file.extension === "html"
? this.htmlParser.toMarkdown(plainText)
: plainText;
} else {
throw Error(
`unsupported file extension as plain text to read, path: ${file.path}`,
);
}
} else {
return "";
}
} | /**
* Reads the content of a plain text file.
* @param fileOrPath The file object or path string of the file to read.
* @returns The content of the file as a string.
* @throws Error if the file extension is not supported.
*/ | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/obsidian/user-data/data-provider.ts#L125-L148 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | FileWatcher.onCreate | private readonly onCreate = (file: TAbstractFile) => {
logger.debug(`created: ${file.path}`);
this.dataManager.receiveDocOperation(new DocAddOperation(file));
} | // otherwise `this` will be changed when used as callbacks | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/obsidian/user-data/file-watcher.ts | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | LineHighlighter.parseAll | parseAll(
allLines: Line[],
matchedLines: MatchedLine[],
truncateLimit: TruncateLimit,
hlMatchedLineBackground: boolean,
): HighlightedContext[] {
return matchedLines.map((matchedLine) => {
const firstMatchedCol = Collections.minInSet(matchedLine.positions);
const matchedRow = matchedLine.row;
const context = this.getTruncatedContext(
allLines,
matchedRow,
firstMatchedCol,
truncateLimit,
);
const matchedLineText = context.matchedLineText;
let matchedLinePositions = matchedLine.positions;
if (matchedLine.row === context.lines[0].row) {
// if the matched line locates at the first row in the context,
// it's start part has been truncated and we need to adjust positions
matchedLinePositions = this.adjustPositionsByStartCol(
matchedLinePositions,
context.firstLineStartCol,
);
}
const highlightedLineText = this.highlightMatchedLine(
matchedLineText,
matchedLinePositions,
hlMatchedLineBackground,
);
const highlightedText = context.lines
.map((line) =>
// line.row === matchedRow ? highlightedLineText : this.highlightContextLine(line.text, queryText) ,
line.row === matchedRow ? highlightedLineText : line.text,
)
.join(FileUtil.JOIN_EOL);
return {
row: matchedLine.row,
col: firstMatchedCol,
text: highlightedText,
} as HighlightedContext;
});
} | /**
* @param queryText used for highlight context except matchedLine
*/ | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/search/highlighter.ts#L23-L65 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | LineHighlighter.parse | parse(
allLines: Line[],
matchedLine: MatchedLine,
truncateLimit: TruncateLimit,
hlMatchedLineBackground: boolean,
): HighlightedContext {
return this.parseAll(
allLines,
[matchedLine],
truncateLimit,
hlMatchedLineBackground,
)[0];
} | /**
* @param queryText used for highlight context except matchedLine
*/ | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/search/highlighter.ts#L70-L82 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | LineHighlighter.parseLineItems | async parseLineItems(
lines: Line[],
queryText: string,
): Promise<LineItem[]> {
const queryTextNoSpaces = queryText.replace(/\s/g, "");
const lineItems: LineItem[] = [];
const matchedLines = await this.lexicalEngine.fzfMatch(
queryTextNoSpaces,
lines,
);
for (const matchedLine of matchedLines) {
const row = matchedLine.row;
const firstMatchedCol = Collections.minInSet(matchedLine.positions);
const originLine = lines[row].text;
// only show part of the line that contains the highlighted chars
const start = Math.max(firstMatchedCol - 30, 0);
const end = Math.min(start + 200, originLine.length);
const substring = originLine.substring(start, end);
const adjustedPositions = this.adjustPositionsByStartCol(
matchedLine.positions,
start,
);
const highlightedText = this.highlightLineByCharPositions(
substring,
adjustedPositions,
);
const paragraphContext = await this.getLineHighlightedContext(
lines,
row,
firstMatchedCol,
queryText,
);
lineItems.push(
new LineItem(
{
text: highlightedText,
row: row,
col: firstMatchedCol,
} as HighlightedContext,
paragraphContext,
),
);
}
return lineItems;
} | /**
* @deprecated since 0.1.x, use SearchService.searchInFile instead
*/ | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/search/highlighter.ts#L87-L137 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | LineHighlighter.extendContextAbove | private extendContextAbove(
lines: Line[],
startRow: number,
maxPreChars: number,
maxLines: number,
boundaryLineMinChars: number,
): TruncatedContext {
let firstLineStartCol = 0;
let currRow = startRow;
let preCharsCount = 0;
const resultLines: Line[] = [];
// logger.debug(`extendContextAbove`);
while (currRow >= 0 && startRow - currRow < maxLines) {
// logger.debug(`extendContextAbove`);
const currLineText = lines[currRow].text;
if (preCharsCount + currLineText.length < maxPreChars) {
// logger.debug(`first line truncated`);
resultLines.unshift(lines[currRow]);
preCharsCount += currLineText.length;
--currRow;
} else if (preCharsCount + currLineText.length == maxPreChars) {
resultLines.unshift(lines[currRow]);
break;
} else {
// need to truncate the top line
// logger.debug(`first line truncated`);
const startCol =
preCharsCount + currLineText.length - maxPreChars;
firstLineStartCol = startCol;
const subStr = lines[currRow].text.substring(startCol);
resultLines.unshift({ text: subStr, row: currRow });
break;
}
}
if (
resultLines.length > 0 &&
resultLines[0].text.length < boundaryLineMinChars
) {
firstLineStartCol = 0;
resultLines.shift();
}
return {
lines: resultLines,
firstLineStartCol: firstLineStartCol,
} as TruncatedContext;
} | /**
* @param lines all lines
*/ | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/search/highlighter.ts#L285-L330 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | LineHighlighter.getLineHighlightedContext | private async getLineHighlightedContext(
lines: Line[],
matchedRow: number,
firstMatchedCol: number,
queryText: string,
): Promise<string> {
const currLang = MyLib.getCurrLanguage();
const context = this.getTruncatedContext(
lines,
matchedRow,
firstMatchedCol,
TruncateOption.forType("paragraph"),
);
const contextLines = context.lines;
const highlightedContext = await Promise.all(
contextLines.map(async (line, index) => {
if (line.row === matchedRow) {
// apply fzfMatch to the targetLine
const matchedLines = await this.lexicalEngine.fzfMatch(
queryText,
[line],
);
try {
// There should be only one matchedLine
const matchedLine = matchedLines[0];
let positions = matchedLine.positions;
if (index === 0) {
// the first line has been truncated
positions = this.adjustPositionsByStartCol(
positions,
context.firstLineStartCol,
);
}
return this.highlightMatchedLine(
line.text,
positions,
true,
);
} catch (e) {
logger.warn(
"There might be inconsistency with previous search step, which lead to a missed match to target line",
);
logger.error(e);
}
} else {
// Perform strict matching on other lines
return this.highlightContextLine(line.text, queryText);
// .replace(/ /g, " ");
}
}),
);
return highlightedContext.join(FileUtil.JOIN_EOL);
} | /**
* Get the HTML of context lines surrounding a matched line in a document.
* @deprecated Since 0.1.x
* @param matchedRow - The row number of the matched line.
* @param firstMatchedCol - The column number of the first matched character in the matched line.
* @param queryText - The query text used for matching.
* @returns A string representing the highlighted context HTML.
*/ | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/search/highlighter.ts#L387-L441 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | LexicalEngine.isReady | get isReady(): boolean {
return this._isReady;
} | // NOTE: need be checked before opening a search-in-vault modal to avoid error when search during indexing | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/search/lexical-engine.ts#L66-L68 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | LexicalEngine.fzfMatch | async fzfMatch(queryText: string, lines: Line[]): Promise<MatchedLine[]> {
const fzf = new AsyncFzf(lines, {
selector: (item) => item.text,
});
return (await fzf.find(queryText))
.slice(0, this.outerSetting.ui.maxItemResults)
.map((entry: FzfResultItem<Line>) => {
return {
text: entry.item.text,
row: entry.item.row,
positions: entry.positions,
} as MatchedLine;
});
} | // for in-file search | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/search/lexical-engine.ts#L87-L100 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | LexicalEngine.searchLinesByFileItem | async searchLinesByFileItem(
lines: Line[],
truncateType: TruncateType,
queryText: string,
fileItem: FileItem,
maxParsedLines: number,
): Promise<MatchedLine[]> {
logger.debug(fileItem.queryTerms);
logger.debug(fileItem.matchedTerms);
const maxSubItems = 50;
logger.debug(`max subItems: ${maxSubItems}`);
// optimization for large charset language to avoid using jieba segmenter
// if (LangUtil.isLargeCharset(queryText)) {
const linesMatcher = new LinesMatcher(
lines,
truncateType,
queryText,
fileItem.queryTerms,
fileItem.matchedTerms,
maxParsedLines,
);
return linesMatcher.parse();
// } else {
// // NOTE: lengthy Japanese and Korean file might be a bit slow due to the jieba segmenter,
// // and they are small charset language, so I don't know how to optimize them using bm25Calculator at the moment
// return await this.searchLinesForSmallCharset(
// lines,
// queryText,
// maxSubItems,
// );
// }
} | // the tokenizing speed is unsatisfactory | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/search/lexical-engine.ts#L131-L163 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | LexicalEngine.findAllTermPositions | private findAllTermPositions(line: string, terms: string[]): Set<number> {
const regex = new RegExp(terms.join("|"), "gi");
const positions = new Set<number>();
let match: RegExpExecArray | null;
let lastIndex = -1;
while ((match = regex.exec(line)) !== null) {
// skip and move to the next character if a match is an empty string or at the same position
if (match.index === lastIndex || match[0].length === 0) {
regex.lastIndex++;
continue;
}
for (let i = 0; i < match[0].length; i++) {
positions.add(match.index + i);
}
lastIndex = match.index;
}
return positions;
// return new Set([1]); // test if this function consumes too much time
} | /**
* @deprecated 0.1.x Use `searchLinesByTerms` instead
* find all chars positions of terms in a given line
*/ | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/search/lexical-engine.ts#L204-L227 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | LexicalOptions.getFileSearchOption | getFileSearchOption(userOption: UserSearchOption): SearchOptions {
return {
tokenize: this.tokenizeSearch,
// TODO: for autosuggestion, we can choose to do a prefix match only when the term is
// at the last index of the query terms
prefix: (term) =>
userOption.isPrefixMatch
? term.length >= this.inSetting.minTermLengthForPrefixSearch
: false,
// TODO: fuzziness based on language
fuzzy: (term) =>
userOption.isFuzzy
? term.length <= 3
? 0
: this.inSetting.fuzzyProportion
: false,
// if `fields` are omitted, all fields will be search with weight 1
boost: {
basename: this.inSetting.weightFilename,
aliases: this.inSetting.weightFilename,
folder: this.inSetting.weightFolder,
tags: this.inSetting.weightTagText,
headings: this.inSetting.weightHeading,
} as DocumentWeight,
combineWith: "and",
};
} | /**
* @param {"and"|"or"} combinationMode - The combination mode:
* - "and": Requires any single token to appear in the fields.
* - "or": Requires all tokens to appear across the fields.
*/ | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/search/lexical-engine.ts#L271-L297 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | LinesMatcher.filterMatchedTerms | private filterMatchedTerms(
queryTerms: string[],
matchedTerms: string[],
): string[] {
const matchedQueryTerms = queryTerms.filter(
(t) =>
!queryTerms.some(
(other) => other.length > t.length && other.includes(t),
) && matchedTerms.includes(t),
);
let result: string[];
if (matchedQueryTerms.length === 0) {
result = matchedTerms.filter(
(t) =>
!matchedTerms.some(
(other) => other.length > t.length && other.includes(t),
),
);
} else {
result = matchedQueryTerms;
// NOTE: based on the fact that matchedTerms only contain unique term
for (const mTerm of matchedTerms) {
if (
!matchedQueryTerms.includes(mTerm) &&
!this.isSubstringOrSuperString(mTerm, matchedTerms)
) {
result.push(mTerm);
}
}
}
return result;
} | // @monitorDecorator | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/search/lexical-engine.ts#L349-L381 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | SemanticEngine.doesCollectionExist | async doesCollectionExist(): Promise<boolean | null> {
try {
const result = await this.request.doesCollectionExist();
this._status = "ready";
return result;
} catch (e) {
this._status = "stopped";
logger.warn(
"failed to connect to ai-helper. launch clever-search-ai-helper or disable semantic search in the setting to avoid this warning.",
);
logger.error(e);
return null;
}
} | /**
* @throws Error
*/ | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/search/semantic-engine.ts#L37-L50 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | Tokenizer.tokenize | tokenize(text: string, mode: "index" | "search"): string[] {
const tokens = new Set<string>();
const segments = text.split(SEGMENT_REGEX);
// TODO: extract path for search
for (const segment of segments) {
if (!segment) continue; // skip empty strings
if (
this.setting.enableChinesePatch &&
CHINESE_REGEX.test(segment)
) {
const words = this.chsSegmenter.cut(segment, true);
for (const word of words) {
if (
this.setting.enableStopWordsZh &&
this.stopWordsZh?.has(word)
) {
if (mode === "search" && word.length > 1) {
logger.debug(`excluded: ${word}`);
}
continue;
}
tokens.add(word);
}
} else {
// don't add too short or too long segment for smallCharsetLanguage
// TODO: is this step necessary?
// if (segment.length > 1 && segment.length < 20) {
// tokens.add(segment);
// }
const words = segment.split(SEPERATOR_REGEX);
for (const word of words) {
if (
word.length < 2 || // don't index single char for small charset
(this.setting.enableStopWordsEn &&
this.stopWordsEn?.has(word))
) {
continue;
}
tokens.add(word);
if (word.length > 3) {
const subwords = word
.replace(HYPHEN_AND_CAMEL_CASE_REGEX, "$1 ")
.split(" ");
for (const subword of subwords) {
if (subword.length > 1) {
tokens.add(subword);
}
}
}
}
}
}
// discard lengthy token to avoid memory-overflow
return Array.from(tokens).filter(token => token.length < 30);
} | // TODO: synonym and lemmatization | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/search/tokenizer.ts#L31-L89 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | TruncateOption.forType | static forType(type: TruncateType, text?: string): TruncateLimit {
// return the option by char type, normal char or wide char
if (text && LangUtil.testWideChar(text)) {
return this.limitsByLanguage[LanguageEnum.zh][type];
} else {
// return the default option
return this.limitsByLanguage[LanguageEnum.en][type];
}
} | // TODO: use token if performance permits. token: normal char +1 wide char +2 | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/services/search/truncate-option.ts#L74-L82 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | ViewHelper.purifyHTML | purifyHTML(rawHtml: string): string {
return DOMPurify.sanitize(rawHtml, { USE_PROFILES: { html: true } });
} | // avoid XSS | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/ui/view-helper.ts#L29-L31 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | ViewHelper.scrollTo | scrollTo(
direction: ScrollLogicalPosition,
item: Item | undefined,
behavior: ScrollBehavior,
) {
// wait until the dom states are updated
setTimeout(() => {
if (item && item.element) {
item.element.scrollIntoView({
behavior: behavior,
// behavior: "auto",
// behavior: "instant",
//@ts-ignore the type definition mistakenly spell `block` as `lock`, so there will be a warning
block: direction, // vertical
// inline: "center" // horizontal
});
}
}, 0);
} | // for scroll bar | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/ui/view-helper.ts#L104-L122 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | BufferSet.constructor | constructor(
handler: (elements: T[]) => Promise<void>,
identifier: (element: T) => string,
autoFlushThreshold: number,
) {
this.elementsMap = new Map();
this.handler = handler;
this.identifier = identifier;
this.autoFlushThreshold = autoFlushThreshold;
} | /**
* Creates an instance of BufferSet.
* @param handler The function to handle elements.
* @param identifier A function that provides a unique string identifier for each element.
* @param autoFlushThreshold The number of elements at which the BufferSet should automatically flush.
*/ | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/utils/data-structure.ts#L34-L43 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | BufferSet.add | add(element: T): void {
const id = this.identifier(element);
this.elementsMap.set(id, element);
if (this.elementsMap.size >= this.autoFlushThreshold) {
this.flushThrottled();
}
} | /**
* Adds a new element to the buffer. If the buffer reaches the autoFlushThreshold, it triggers a flush.
* If an element with the same identifier already exists, it will be replaced by the new element.
* @param element The element to be added to the buffer.
*/ | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/utils/data-structure.ts#L50-L57 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | BufferSet.forceFlush | async forceFlush(): Promise<void> {
if (this.elementsMap.size === 0) {
return;
}
const elementsToHandle = Array.from(this.elementsMap.values());
this.elementsMap.clear();
await this.handler(elementsToHandle);
logger.debug("flushed");
} | /**
* Flushes all buffered elements to the handler function and clears the buffer.
*/ | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/utils/data-structure.ts#L62-L72 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | EventBus.on | on(event: EventEnum, callback: EventCallback): void {
// console.log("registered");
if (!this.listeners.has(event)) {
this.listeners.set(event, []);
}
this.listeners.get(event)?.push(callback);
} | // 监听事件 | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/utils/event-bus.ts#L13-L19 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | EventBus.off | off(event: EventEnum, callback: EventCallback): void {
// console.log("unregistered");
const callbacks = this.listeners.get(event);
if (callbacks) {
const index = callbacks.indexOf(callback);
if (index > -1) {
callbacks.splice(index, 1);
}
}
} | // 移除监听器 | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/utils/event-bus.ts#L22-L31 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | EventBus.emit | emit(event: EventEnum, ...args: any[]): void {
this.listeners.get(event)?.forEach((callback) => {
callback(...args);
});
} | // 触发事件 | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/utils/event-bus.ts#L34-L38 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | MyLib.append | static append<T>(host: T[], addition: T[]): T[] {
for (const element of addition) {
host.push(element);
}
return host;
} | /**
* Appends elements from addition to host.
*/ | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/utils/my-lib.ts#L27-L32 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | MyLib.mergeDeep | static mergeDeep<T>(target: T, ...sources: T[]): T {
if (!sources.length) return target;
const source = sources.shift();
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key as keyof T])
// @ts-ignore
Object.assign(target, { [key]: {} });
// @ts-ignore
MyLib.mergeDeep(target[key as keyof T], source[key]);
} else {
// @ts-ignore
Object.assign(target, { [key]: source[key] });
}
}
}
return MyLib.mergeDeep(target, ...sources);
} | /**
* deep version of Object.assign (will change the target)
*/ | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/utils/my-lib.ts#L37-L57 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
obsidian-clever-search | github_2023 | yan42685 | typescript | MyLib.getCurrLanguage | static getCurrLanguage(): LanguageEnum {
// getItem("language") will return `null` if currLanguage === "en"
const langKey = window.localStorage.getItem("language") || "en";
if (langKey in LanguageEnum) {
return LanguageEnum[langKey as keyof typeof LanguageEnum];
} else {
return LanguageEnum.other;
}
} | /**
* Get current runtime language
*/ | https://github.com/yan42685/obsidian-clever-search/blob/adaf124a8b4041cb821c6d2ab21611a55ab9cc6e/src/utils/my-lib.ts#L62-L70 | adaf124a8b4041cb821c6d2ab21611a55ab9cc6e |
arco-admin | github_2023 | oljc | typescript | injectStyle | const injectStyle = (styleText: string) => {
const oldStyle = document.getElementById('theme-color');
if (oldStyle) {
oldStyle.innerHTML = styleText;
} else {
const style = document.createElement('style');
style.id = 'theme-color';
style.innerHTML = styleText;
document.head.appendChild(style);
}
}; | /**
* 注入样式
* @param styleText 样式字符串
*/ | https://github.com/oljc/arco-admin/blob/42ef7251783eb6778a8a102f23533c66eb5669f7/src/hooks/useColorTheme.ts#L37-L48 | 42ef7251783eb6778a8a102f23533c66eb5669f7 |
arco-admin | github_2023 | oljc | typescript | start | const start = () => {
resume();
options.onStart?.();
}; | // 开始 | https://github.com/oljc/arco-admin/blob/42ef7251783eb6778a8a102f23533c66eb5669f7/src/hooks/useCountDown.ts#L50-L53 | 42ef7251783eb6778a8a102f23533c66eb5669f7 |
arco-admin | github_2023 | oljc | typescript | queryDevice | function queryDevice() {
const rect = document.body.getBoundingClientRect();
return rect.width - 1 < WIDTH;
} | // https://arco.design/vue/component/grid#responsivevalue | https://github.com/oljc/arco-admin/blob/42ef7251783eb6778a8a102f23533c66eb5669f7/src/hooks/useResponsive.ts#L8-L11 | 42ef7251783eb6778a8a102f23533c66eb5669f7 |
nym-vpn-client | github_2023 | nymtech | typescript | InAppNotificationProvider | function InAppNotificationProvider({ children }: NotificationProviderProps) {
const [stack, setStack] = useState<Notification[]>([]);
const [current, setCurrent] = useState<Notification | null>(null);
const [isTransitioning, setIsTransitioning] = useState(false);
const transitionRef = useRef<Timeout | null>(null);
const checkDuplicate = useCallback(
(stack: Notification[], toBeChecked: Notification) => {
return stack.some((n) => n.text === toBeChecked.text);
},
[],
);
const push = useCallback(
(notification: Notification | Notification[]) => {
if (Array.isArray(notification)) {
setStack((prev) => {
const isDuplicate = notification.some((n) => checkDuplicate(prev, n));
if (isDuplicate) {
return prev;
}
return [...prev, ...notification];
});
} else {
setStack((prev) => {
if (checkDuplicate(prev, notification)) {
return prev;
}
return [...prev, notification];
});
}
},
[checkDuplicate],
);
const shift = useCallback(() => {
if (stack.length === 0) {
return null;
}
const first = stack[0];
setStack([...stack.slice(1)]);
return first;
}, [stack]);
const clear = () => {
setStack([]);
setIsTransitioning(false);
setCurrent(null);
clearTimeout(transitionRef.current as Timeout | undefined);
};
useEffect(() => {
if (current || isTransitioning) {
return;
}
const notification = shift();
if (notification) {
setCurrent(notification);
}
}, [shift, current, stack.length, isTransitioning]);
const next = () => {
setIsTransitioning(true);
setCurrent(null);
transitionRef.current = setTimeout(() => {
setIsTransitioning(false);
}, transitionDuration);
};
return (
<InAppNotificationContext.Provider
value={{
stack,
current,
next,
push,
clear,
}}
>
{children}
</InAppNotificationContext.Provider>
);
} | // ms | https://github.com/nymtech/nym-vpn-client/blob/04010f7a662cbff31107dc2935a131918630a0f8/nym-vpn-app/src/contexts/in-app-notification/provider.tsx#L15-L98 | 04010f7a662cbff31107dc2935a131918630a0f8 |
nym-vpn-client | github_2023 | nymtech | typescript | fetchCountries | const fetchCountries = async (vpnMode: VpnMode, node: NodeHop) => {
// first try to load from cache
let countries = MCache.get<Country[]>(
vpnMode === 'Mixnet' ? `mn-${node}-countries` : 'wg-countries',
);
// fallback to daemon query
if (!countries) {
console.info(`fetching countries for ${vpnMode} ${node}`);
try {
countries = await invoke<Country[]>('get_countries', {
vpnMode,
nodeType: node === 'entry' ? 'Entry' : 'Exit',
});
MCache.set(
vpnMode === 'Mixnet' ? `mn-${node}-countries` : 'wg-countries',
countries,
CountryCacheDuration,
);
} catch (e) {
console.warn(`Failed to fetch ${node} countries:`, e);
dispatch({
type:
node === 'entry'
? 'set-entry-countries-error'
: 'set-exit-countries-error',
payload: e as BackendError,
});
if (vpnMode === 'TwoHop') {
// in 2hop mode, the error must be set for both entry and exit
dispatch({
type:
node === 'entry'
? 'set-exit-countries-error'
: 'set-entry-countries-error',
payload: e as BackendError,
});
}
}
}
if (!countries) {
console.warn('no countries found');
return;
}
if (vpnMode === 'Mixnet') {
dispatch({
type: 'set-country-list',
payload: {
hop: node,
countries,
},
});
// reset any previous error
dispatch({
type:
node === 'entry'
? 'set-entry-countries-error'
: 'set-exit-countries-error',
payload: null,
});
} else {
// in 2hop mode, the country list is the same for both entry and exit
dispatch({
type: 'set-fast-country-list',
payload: {
countries,
},
});
dispatch({
type: 'set-entry-countries-error',
payload: null,
});
dispatch({
type: 'set-exit-countries-error',
payload: null,
});
}
}; | // use cached values if any, otherwise query from daemon | https://github.com/nymtech/nym-vpn-client/blob/04010f7a662cbff31107dc2935a131918630a0f8/nym-vpn-app/src/contexts/main/provider.tsx#L140-L216 | 04010f7a662cbff31107dc2935a131918630a0f8 |
nym-vpn-client | github_2023 | nymtech | typescript | useAutostart | function useAutostart() {
const { autostart } = useMainState();
const dispatch = useMainDispatch() as StateDispatch;
useEffect(() => {
const init = async () => {
const enabled = await isEnabled();
dispatch({ type: 'set-autostart', enabled });
};
init();
}, [dispatch]);
const toggle = async () => {
const enabled = await isEnabled();
if (enabled) {
await disable();
} else {
await enable();
}
dispatch({ type: 'set-autostart', enabled: !enabled });
};
return { enabled: autostart, toggle };
} | /* thin wrapper around tauri autostart plugin */ | https://github.com/nymtech/nym-vpn-client/blob/04010f7a662cbff31107dc2935a131918630a0f8/nym-vpn-app/src/hooks/useAutostart.ts#L7-L30 | 04010f7a662cbff31107dc2935a131918630a0f8 |
nym-vpn-client | github_2023 | nymtech | typescript | useClipboard | function useClipboard() {
const { push } = useInAppNotify();
const { t } = useTranslation('notifications');
// Writes text to the clipboard
const copy = async (
text: string,
notify = true,
ntfyPosition: 'top' | 'bottom' = 'top',
) => {
try {
await writeText(text);
if (notify) {
push({
text: t('copied-to-clipboard'),
position: ntfyPosition,
clickAway: true,
});
}
} catch (e) {
console.error('failed to copy to clipboard', e);
}
};
return { copy };
} | /* Access the system clipboard */ | https://github.com/nymtech/nym-vpn-client/blob/04010f7a662cbff31107dc2935a131918630a0f8/nym-vpn-app/src/hooks/useClipboard.ts#L6-L31 | 04010f7a662cbff31107dc2935a131918630a0f8 |
nym-vpn-client | github_2023 | nymtech | typescript | copy | const copy = async (
text: string,
notify = true,
ntfyPosition: 'top' | 'bottom' = 'top',
) => {
try {
await writeText(text);
if (notify) {
push({
text: t('copied-to-clipboard'),
position: ntfyPosition,
clickAway: true,
});
}
} catch (e) {
console.error('failed to copy to clipboard', e);
}
}; | // Writes text to the clipboard | https://github.com/nymtech/nym-vpn-client/blob/04010f7a662cbff31107dc2935a131918630a0f8/nym-vpn-app/src/hooks/useClipboard.ts#L11-L28 | 04010f7a662cbff31107dc2935a131918630a0f8 |
nym-vpn-client | github_2023 | nymtech | typescript | useI18nError | function useI18nError() {
const { t } = useTranslation('errors');
const translateError: Terror = useCallback(
(error: ErrorKey | TunnelError) => {
if (typeof error === 'object') {
// tunnel state errors
switch (error.key) {
case 'internal':
return t('tunnel.internal');
case 'firewall':
return t('tunnel.firewall');
case 'routing':
return t('tunnel.routing');
case 'dns':
return t('tunnel.dns');
case 'tun-device':
return t('tunnel.tun-device');
case 'tunnel-provider':
return t('tunnel.provider');
case 'same-entry-and-exit-gw':
return t('tunnel.same-entry-exit-gw');
case 'invalid-entry-gw-country':
return t('tunnel.invalid-entry-gw-country');
case 'invalid-exit-gw-country':
return t('tunnel.invalid-exit-gw-country');
case 'bad-bandwidth-increase':
return t('tunnel.bad-bandwidth-increase');
case 'duplicate-tun-fd':
return t('tunnel.duplicate-tun-fd');
case 'sync-account-no-account-stored':
return t('sync-account', { reason: t('account.not-stored') });
case 'sync-account-unexpected-response':
return t('sync-account', {
reason: t('account.unexpected-response'),
});
case 'sync-account-internal':
return t('sync-account', { reason: t('account.internal') });
case 'sync-account-vpn-api':
return t('sync-account', { reason: t('account.vpn-api') });
case 'sync-device-no-account-stored':
return t('sync-device', { reason: t('account.not-stored') });
case 'sync-device-no-device-stored':
return t('sync-device', { reason: t('account.no-device-stored') });
case 'sync-device-unexpected-response':
return t('sync-device', {
reason: t('account.unexpected-response'),
});
case 'sync-device-internal':
return t('sync-device', { reason: t('account.internal') });
case 'sync-device-vpn-api':
return t('sync-device', { reason: t('account.vpn-api') });
case 'register-device-no-account-stored':
return t('register-device', { reason: t('account.not-stored') });
case 'register-device-no-device-stored':
return t('register-device', {
reason: t('account.no-device-stored'),
});
case 'register-device-unexpected-response':
return t('register-device', {
reason: t('account.unexpected-response'),
});
case 'register-device-internal':
return t('register-device', { reason: t('account.internal') });
case 'register-device-vpn-api':
return t('register-device', { reason: t('account.vpn-api') });
case 'req-zknym-no-account-stored':
return t('request-zknym', { reason: t('account.not-stored') });
case 'req-zknym-no-device-stored':
return t('request-zknym', {
reason: t('account.no-device-stored'),
});
case 'req-zknym-unexpected-response':
return t('request-zknym', {
reason: t('account.unexpected-response'),
});
case 'req-zknym-storage':
return t('request-zknym', { reason: t('account.storage') });
case 'req-zknym-internal':
return t('request-zknym', { reason: t('account.internal') });
case 'req-zknym-vpn-api':
return t('request-zknym', { reason: t('account.vpn-api') });
}
console.warn('unhandled tunnel error', error);
return t('unknown');
}
// no tunnel errors
switch (error) {
// mixnet event errors
case 'entry-gw-down':
return t('entry-gateway-down');
case 'exit-gw-down-ipv4':
return t('exit-gateway-down.ipv4');
case 'exit-gw-down-ipv6':
return t('exit-gateway-down.ipv6');
case 'exit-gw-routing-error-ipv4':
return t('exit-gateway-routing.ipv4');
case 'exit-gw-routing-error-ipv6':
return t('exit-gateway-routing.ipv6');
case 'no-bandwidth':
return t('no-bandwidth');
// general errors
case 'internal-error':
return t('internal');
case 'not-connected-to-daemon':
return t('daemon.not-connected');
case 'grpc-error':
return t('grpc');
case 'account-invalid-mnemonic':
return t('account.invalid-recovery-phrase');
case 'account-storage':
return t('account.storage');
case 'account-is-connected':
return t('account.is-connected');
case 'get-mixnet-entry-countries-query':
return t('countries-request.entry');
case 'get-mixnet-exit-countries-query':
return t('countries-request.exit');
case 'get-wg-countries-query':
return t('countries-request.fast-mode');
case 'invalid-network-name':
return t('daemon.invalid-network');
case 'unknown-error':
return t('unknown');
}
console.warn('unhandled backend error', error);
return t('unknown');
},
[t],
);
return { tE: translateError };
} | /**
* Hook to get the translation function for backend errors
*
* @returns The translation function
*/ | https://github.com/nymtech/nym-vpn-client/blob/04010f7a662cbff31107dc2935a131918630a0f8/nym-vpn-app/src/hooks/useI18nError.ts#L13-L147 | 04010f7a662cbff31107dc2935a131918630a0f8 |
nym-vpn-client | github_2023 | nymtech | typescript | useLang | function useLang() {
const { i18n } = useTranslation();
/**
* Sets the i18n language.
* Also updates dayjs locale accordingly and saves
* the language to the KV store
*
* @param lng - The language tag to set
*/
const set = useCallback(
async (lng: LngTag, updateDb = true) => {
if (i18n.language === lng) {
return;
}
console.info('set language:', lng);
if (updateDb) {
kvSet('UiLanguage', lng);
}
await i18n.changeLanguage(lng);
switch (lng) {
case 'zh-Hans':
dayjs.locale('zh-cn');
break;
case 'pt-BR':
dayjs.locale('pt-br');
break;
default:
dayjs.locale(lng);
}
},
[i18n],
);
/**
* Get the localized country name
*
* @param code - Two-letter country code
*/
const getCountryName = useCallback(
(code: string) => {
const regionNames = new Intl.DisplayNames(i18n.language, {
type: 'region',
fallback: 'none',
style: 'long',
});
let name = null;
try {
name = regionNames.of(code);
} catch (e) {
console.warn(e);
}
return name;
},
[i18n.language],
);
/**
* Compare two strings according to the sort order of the current language
*
* @param a - The first string to compare
* @param b - The second string to compare
*/
const compare = useCallback(
(a: string, b: string) => {
const collator = new Intl.Collator(i18n.language, {});
return collator.compare(a, b);
},
[i18n.language],
);
return { compare, set, getCountryName };
} | /**
* Hook to set the i18n language
*
* @returns The `set` function
*/ | https://github.com/nymtech/nym-vpn-client/blob/04010f7a662cbff31107dc2935a131918630a0f8/nym-vpn-app/src/hooks/useLang.ts#L12-L84 | 04010f7a662cbff31107dc2935a131918630a0f8 |
nym-vpn-client | github_2023 | nymtech | typescript | useNotify | function useNotify() {
const { desktopNotifications } = useMainState();
const location = useLocation();
const [lastNotification, setLastNotification] = useState<string | null>(null);
const id = useRef<number>(0);
useEffect(() => {
if (lastNotification) {
clearTimeout(id.current);
id.current = setTimeout(() => {
setLastNotification(null);
}, AntiSpamTimeout) as unknown as number;
}
}, [lastNotification]);
/**
* Sends desktop notifications. Also checks if the permission is granted
* and desktop notifications are enabled.
*
* @param body - The text to display in the notification
* @param opts - Notification options
*/
const notify = useCallback(
async (body: string, opts: NotifyOptions = {}) => {
const { force = false, locationPath, noSpamCheck } = opts;
const os = type();
const window = getCurrentWebviewWindow();
if (!desktopNotifications) {
return;
}
if (!force) {
const windowFocused = await window.isFocused();
const windowVisible = await window.isVisible();
const onRightScreen = locationPath
? location.pathname === locationPath
: true;
if (windowFocused && windowVisible && onRightScreen) {
return;
}
if (!noSpamCheck && body === lastNotification) {
return;
}
}
const granted = await isPermissionGranted();
if (!granted) {
console.log('Desktop notifications permission not granted');
return;
}
if (os === 'linux') {
sendNotification({ title: AppName, body });
} else {
sendNotification(body);
}
setLastNotification(body);
},
[desktopNotifications, location, lastNotification],
);
return { notify };
} | /**
* Hook to send desktop notifications
*
* @returns The `notify` function
*/ | https://github.com/nymtech/nym-vpn-client/blob/04010f7a662cbff31107dc2935a131918630a0f8/nym-vpn-app/src/hooks/useNotify.ts#L35-L99 | 04010f7a662cbff31107dc2935a131918630a0f8 |
nym-vpn-client | github_2023 | nymtech | typescript | useThrottle | function useThrottle<Fn extends (...args: any[]) => Promise<void> | void>(
fn: Fn,
wait: number,
deps: DependencyList = [],
options?: _.ThrottleSettings,
) {
// eslint-disable-next-line react-hooks/exhaustive-deps
const t = useCallback(
_.throttle(async () => fn(), wait, {
trailing: false,
...options,
}),
[wait, ...deps],
);
return t;
} | /**
* Hook to throttle a function using `_.throttle` as a wrapper
*
* @param fn - The function to throttle
* @param wait - The number of milliseconds to throttle invocations to
* @param deps - The dependencies to watch for callback reset (passed to `useCallback`)
* @param options - Throttle options
* @returns The throttled function
*/ | https://github.com/nymtech/nym-vpn-client/blob/04010f7a662cbff31107dc2935a131918630a0f8/nym-vpn-app/src/hooks/useThrottle.ts#L14-L30 | 04010f7a662cbff31107dc2935a131918630a0f8 |
nym-vpn-client | github_2023 | nymtech | typescript | getInitialTunnelState | const getInitialTunnelState = async () => {
return await invoke<TunnelStateIpc>('get_tunnel_state');
}; | // initialize connection state | https://github.com/nymtech/nym-vpn-client/blob/04010f7a662cbff31107dc2935a131918630a0f8/nym-vpn-app/src/state/init.ts#L33-L35 | 04010f7a662cbff31107dc2935a131918630a0f8 |
nym-vpn-client | github_2023 | nymtech | typescript | getEntryCountries | const getEntryCountries = async () => {
const mode = (await kvGet<VpnMode>('VpnMode')) || DefaultVpnMode;
const countries = await invoke<Country[]>('get_countries', {
vpnMode: mode,
nodeType: 'Entry',
});
return { countries, mode };
}; | // init country list | https://github.com/nymtech/nym-vpn-client/blob/04010f7a662cbff31107dc2935a131918630a0f8/nym-vpn-app/src/state/init.ts#L42-L49 | 04010f7a662cbff31107dc2935a131918630a0f8 |
nym-vpn-client | github_2023 | nymtech | typescript | MsIcon | function MsIcon({ icon, className }: MsIconProps) {
return (
<span
className={clsx([
'font-icon text-2xl select-none',
className && className,
])}
>
{icon}
</span>
);
} | // Component for rendering Google Material Symbols icons | https://github.com/nymtech/nym-vpn-client/blob/04010f7a662cbff31107dc2935a131918630a0f8/nym-vpn-app/src/ui/MsIcon.tsx#L11-L22 | 04010f7a662cbff31107dc2935a131918630a0f8 |
nym-vpn-client | github_2023 | nymtech | typescript | RouteLoading | function RouteLoading() {
return (
<div
className={clsx([
'h-full flex flex-col min-w-80',
'bg-faded-lavender dark:bg-ash',
])}
>
{/* Top-bar placeholder */}
<div className="w-full h-16 shadow-sm bg-white dark:bg-octave-arsenic"></div>
</div>
);
} | // Loading component rendering transitions for lazy loaded route | https://github.com/nymtech/nym-vpn-client/blob/04010f7a662cbff31107dc2935a131918630a0f8/nym-vpn-app/src/ui/RouteLoading.tsx#L4-L16 | 04010f7a662cbff31107dc2935a131918630a0f8 |
0up | github_2023 | 0sumcode | typescript | iconImage | function iconImage() {
return `
<svg aria-hidden="true" focusable="false" width="25" height="25" viewBox="0 0 25 25">
<g fill="#686DE0" fillRule="evenodd">
<path d="M5 7v10h15V7H5zm0-1h15a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1z" fillRule="nonzero" />
<path d="M6.35 17.172l4.994-5.026a.5.5 0 0 1 .707 0l2.16 2.16 3.505-3.505a.5.5 0 0 1 .707 0l2.336 2.31-.707.72-1.983-1.97-3.505 3.505a.5.5 0 0 1-.707 0l-2.16-2.159-3.938 3.939-1.409.026z" fillRule="nonzero" />
<circle cx="7.5" cy="9.5" r="1.5" />
</g>
</svg>
`;
} | // Adapted from @uppy/dashboard | https://github.com/0sumcode/0up/blob/fab2ffa626ae04836d5e52a4011ee01c6b243126/src/lib/getFileTypeIcon.ts#L3-L13 | fab2ffa626ae04836d5e52a4011ee01c6b243126 |
spliit | github_2023 | spliit-app | typescript | iosPWASplash | function iosPWASplash(icon: string, color = 'white') {
// Check if the provided 'icon' is a valid URL
if (typeof icon !== 'string' || icon.length === 0) {
throw new Error('Invalid icon URL provided')
}
// Calculate the device's width and height
const deviceWidth = screen.width
const deviceHeight = screen.height
// Calculate the pixel ratio
const pixelRatio = window.devicePixelRatio || 1
// Create two canvases and get their contexts to draw landscape and portrait splash screens.
const canvas = document.createElement('canvas')
const canvas2 = document.createElement('canvas')
const ctx = canvas.getContext('2d')!
const ctx2 = canvas2.getContext('2d')!
// Create an image element for the icon
const iconImage = new Image()
iconImage.onerror = function () {
throw new Error('Failed to load icon image')
}
iconImage.src = icon
// Load the icon image, make sure it is served from the same domain (ideal size 512pxX512px). If not then set the proper CORS headers on the image and uncomment the next line.
//iconImage.crossOrigin="anonymous"
iconImage.onload = function () {
// Calculate the icon size based on the device's pixel ratio
const iconSizew = iconImage.width / (3 / pixelRatio)
const iconSizeh = iconImage.height / (3 / pixelRatio)
canvas.width = deviceWidth * pixelRatio
canvas2.height = canvas.width
canvas.height = deviceHeight * pixelRatio
canvas2.width = canvas.height
ctx.fillStyle = color
ctx2.fillStyle = color
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx2.fillRect(0, 0, canvas2.width, canvas2.height)
// Calculate the position to center the icon
const x = (canvas.width - iconSizew) / 2
const y = (canvas.height - iconSizeh) / 2
const x2 = (canvas2.width - iconSizew) / 2
const y2 = (canvas2.height - iconSizeh) / 2
// Draw the icon with the calculated size
ctx.drawImage(iconImage, x, y, iconSizew, iconSizeh)
ctx2.drawImage(iconImage, x2, y2, iconSizew, iconSizeh)
const imageDataURL = canvas.toDataURL('image/png')
const imageDataURL2 = canvas2.toDataURL('image/png')
// Create the first startup image <link> tag (splash screen)
const appleTouchStartupImageLink = document.createElement('link')
appleTouchStartupImageLink.setAttribute('rel', 'apple-touch-startup-image')
appleTouchStartupImageLink.setAttribute(
'media',
'screen and (orientation: portrait)',
)
appleTouchStartupImageLink.setAttribute('href', imageDataURL)
document.head.appendChild(appleTouchStartupImageLink)
// Create the second startup image <link> tag (splash screen)
const appleTouchStartupImageLink2 = document.createElement('link')
appleTouchStartupImageLink2.setAttribute('rel', 'apple-touch-startup-image')
appleTouchStartupImageLink2.setAttribute(
'media',
'screen and (orientation: landscape)',
)
appleTouchStartupImageLink2.setAttribute('href', imageDataURL2)
document.head.appendChild(appleTouchStartupImageLink2)
}
} | /*!
* ios-pwa-splash <https://github.com/avadhesh18/iosPWASplash>
*
* Copyright (c) 2023, Avadhesh B.
* Released under the MIT License.
*/ | https://github.com/spliit-app/spliit/blob/9302a32f4c0e3081985f6410debed7f863bfd67b/src/app/apple-pwa-splash.tsx#L24-L98 | 9302a32f4c0e3081985f6410debed7f863bfd67b |
spliit | github_2023 | spliit-app | typescript | compareBalancesForReimbursements | function compareBalancesForReimbursements(b1: any, b2: any): number {
// positive balances come before negative balances
if (b1.total > 0 && 0 > b2.total) {
return -1
} else if (b2.total > 0 && 0 > b1.total) {
return 1
}
// if signs match, sort based on userid
return b1.participantId < b2.participantId ? -1 : 1
} | /**
* A comparator that is stable across reimbursements.
* This ensures that a participant executing a suggested reimbursement
* does not result in completely new repayment suggestions.
*/ | https://github.com/spliit-app/spliit/blob/9302a32f4c0e3081985f6410debed7f863bfd67b/src/lib/balances.ts#L90-L99 | 9302a32f4c0e3081985f6410debed7f863bfd67b |
placemark | github_2023 | placemark | typescript | clampi | function clampi(value: number) {
return Math.max(0, Math.min(255, Math.round(value) || 0));
} | /**
* Helpers, from d3-color. Remove these
* when I can finally use ESM modules.
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/components/color_popover.tsx#L32-L34 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | stopWindowDrag | const stopWindowDrag = (event: DragEvent) => {
event.preventDefault();
}; | /**
* From an event, get files, with handles for re-saving.
* Result is nullable.
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/components/drop.tsx#L15-L17 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | collectFeaturesByFolder | function collectFeaturesByFolder(featureMap: FeatureMap) {
const featuresByFolder = new Map<string | null, IWrappedFeature[]>();
for (const feature of featureMap.values()) {
const group = featuresByFolder.get(feature.folderId) || [];
group.push(feature);
featuresByFolder.set(feature.folderId, group);
}
return featuresByFolder;
} | /**
* Index a list of features by their parent folder.
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/components/panels/feature_editor/feature_editor_folder/math.ts#L68-L76 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | getLevel | function getLevel(
folderId: string | null,
depth: number,
featuresByFolder: ReturnType<typeof collectFeaturesByFolder>,
foldersByFolder: ReturnType<typeof collectFoldersByFolder>,
activeId: UniqueIdentifier | null
) {
let items: FlattenedItem[] = [];
const folders = foldersByFolder.get(folderId) ?? [];
const features = featuresByFolder.get(folderId) ?? [];
/**
* A sort of insane optimization here. Maybe unnecessary,
* but this is a pretty hot part of the codebase.
*
* Basically the features and folders arrays are both sorted,
* and we want to print out a sorted, combined list. So this
* iterates through _both_ of them simultaneously, incrementing
* two loop counters.
*/
function pushFeature(feature: IWrappedFeature, depth: number) {
items.push(featureToFlat(feature, depth));
featureI++;
}
function pushFolder(folder: IFolder, depth: number) {
items.push(folderToFlat(folder, depth));
folderI++;
}
// Indices
let folderI = 0;
let featureI = 0;
while (folderI < folders.length || featureI < features.length) {
const headFolder = folders[folderI];
const headFeature = features[featureI];
// If there's no folder, push the feature
if (!headFolder) {
pushFeature(headFeature, depth);
} else if (!headFeature) {
pushFolder(headFolder, depth);
} else if (headFeature.at < headFolder.at) {
/**
* Otherwise, if there is both a feature and a folder,
* push the one with the lower 'at'.
*/
pushFeature(headFeature, depth);
} else {
pushFolder(headFolder, depth);
}
}
for (let i = items.length - 1; i >= 0; i--) {
const item = items[i];
if (item.kind !== "folder") continue;
const folder = item.data;
const hideChildren = !folder.expanded || activeId === folder.id;
if (!hideChildren) {
const children = getLevel(
folder.id,
depth + 1,
featuresByFolder,
foldersByFolder,
activeId
);
if (children.length) {
// This previously used splice. This is sort of just
// splice via a different mechanism. Slice is slow.
items = items
.slice(0, i + 1)
.concat(children)
.concat(items.slice(i + 1));
}
}
}
return items;
} | /**
* Only used internally (and recursively)
* by useFlattenedItems
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/components/panels/feature_editor/feature_editor_folder/math.ts#L148-L226 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | pushFeature | function pushFeature(feature: IWrappedFeature, depth: number) {
items.push(featureToFlat(feature, depth));
featureI++;
} | /**
* A sort of insane optimization here. Maybe unnecessary,
* but this is a pretty hot part of the codebase.
*
* Basically the features and folders arrays are both sorted,
* and we want to print out a sorted, combined list. So this
* iterates through _both_ of them simultaneously, incrementing
* two loop counters.
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/components/panels/feature_editor/feature_editor_folder/math.ts#L169-L172 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | getDragDepth | function getDragDepth(offset: number, indentationWidth: number) {
return Math.round(offset / indentationWidth);
} | /**
* Round a drag x coordinate to a depth level.
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/components/panels/feature_editor/feature_editor_folder/math.ts#L313-L315 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | resultToTransact | function resultToTransact({
result,
file,
track,
existingFolderId,
}: {
result: ConvertResult;
file: Pick<File, "name">;
track: [
string,
{
format: string;
}
];
existingFolderId?: string | undefined;
}): Partial<MomentInput> {
const folderId = newFeatureId();
/**
* If someone's provided a folder to put this in,
* don't generate a new one. Basically, this is for pasting
* features into a folder.
*/
const putFolders: MomentInput["putFolders"] = existingFolderId
? []
: [
{
name: file?.name || "Imported file",
visibility: true,
id: folderId,
expanded: true,
locked: false,
folderId: null,
},
];
switch (result.type) {
case "geojson": {
const { features } = result.geojson;
const ats = generateNKeysBetween(null, null, features.length);
return {
note: `Imported ${file?.name ? file.name : "a file"}`,
track: track,
putFolders,
putFeatures: result.geojson.features.map((feature, i) => {
return {
at: ats[i],
folderId: existingFolderId || folderId,
id: newFeatureId(),
feature,
};
}),
};
}
case "root": {
// In the (rare) case in which someone imported
// something with a root, then import it in its original
// structure.
const flat = flattenRoot(result.root, [], [], null);
return flat;
}
}
} | /**
* Creates the _input_ to a transact() operation,
* given some imported result.
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/hooks/use_import.tsx#L30-L92 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | justSwitch | function justSwitch() {
set(ephemeralStateAtom, { type: "none" });
const data = get(dataAtom);
set(dataAtom, {
...data,
selection: USelection.selectionToFolder(data),
});
set(modeAtom, {
mode: Mode.DRAW_LINE,
modeOptions: { multi: !!event?.shiftKey, replaceGeometryForId },
});
} | // Just switch to line mode, don't continue a line! | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/hooks/use_line_mode.ts#L66-L77 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | getXY | function getXY(element: HTMLElement | null): FocusCoordinate | null {
let inputLocation: FocusCoordinate["inputLocation"] = "empty";
if (element instanceof HTMLInputElement) {
if ("selectionStart" in element && element.type === "text") {
const value = element.value;
// If there's nothing in the input element,
// this is the special "empty" state - you can navigate
// forward or backward.
if (!value) {
inputLocation = "empty";
}
// If something is selected, never move.
else if (element.selectionStart === element.selectionEnd) {
if (element.selectionStart === 0) {
inputLocation = "start";
} else if (element.selectionStart === value.length) {
inputLocation = "end";
} else {
inputLocation = "middle";
}
} else {
inputLocation = "middle";
}
}
}
while (element && !(element.dataset && "focusScope" in element.dataset)) {
if (element.dataset && "focusX" in element.dataset) {
return {
x: +(element.dataset.focusX || 0),
y: +(element.dataset.focusY || 0),
inputLocation,
};
}
element = element.parentNode as HTMLElement;
}
return null;
} | /**
* Danger: while loop
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/arrow_navigation.ts#L11-L49 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | isNumberLike | function isNumberLike(value: string) {
return !isNaN(+value) && !value.match(/^0\d+$/);
} | /**
* Allow many forms of numbers but _not_ integer
* strings starting with 0, because those are often
* used as identifiers.
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/cast.ts#L79-L81 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | toMercator | function toMercator(position: Pos2): Pos2 {
const [longitude, latitude] = position;
// compensate longitudes passing the 180th meridian
// from https://github.com/proj4js/proj4js/blob/master/lib/common/adjust_lon.js
const adjusted =
Math.abs(longitude) <= 180 ? longitude : longitude - sign(longitude) * 360;
return [
clamp(A * adjusted * D2R, -MAXEXTENT, MAXEXTENT),
clamp(
A * Math.log(Math.tan(Math.PI * 0.25 + 0.5 * latitude * D2R)),
-MAXEXTENT,
MAXEXTENT
),
];
} | /**
* From TURF
* Convert lon/lat values to 900913 x/y.
* (from https://github.com/mapbox/sphericalmercator)
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/circle.ts#L32-L48 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | toLonLat | function toLonLat(xy: Pos2): Pos2 {
return [
(xy[0] * R2D) / A,
(Math.PI * 0.5 - 2.0 * Math.atan(Math.exp(-xy[1] / A))) * R2D,
];
} | /**
* Convert 900913 x/y values to lon/lat.
* (from https://github.com/mapbox/sphericalmercator)
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/circle.ts#L54-L59 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | degreesToRadians | function degreesToRadians(degrees: number): number {
const radians = degrees % 360;
return (radians * Math.PI) / 180;
} | /**
* Same as Turf.
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/circle.ts#L64-L67 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | radiansToDegrees | function radiansToDegrees(radians: number): number {
const degrees = radians % (2 * Math.PI);
return (degrees * 180) / Math.PI;
} | /**
* Also same as turf.
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/circle.ts#L72-L75 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | distanceInRadians | function distanceInRadians(a: Pos2, b: Pos2) {
const dLat = degreesToRadians(b[1] - a[1]);
const dLon = degreesToRadians(b[0] - a[0]);
const lat1 = degreesToRadians(a[1]);
const lat2 = degreesToRadians(b[1]);
const ax =
Math.pow(Math.sin(dLat / 2), 2) +
Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2);
return 2 * Math.atan2(Math.sqrt(ax), Math.sqrt(1 - ax));
} | /**
* Haversine distance. Adapted from Turf.
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/circle.ts#L118-L129 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | handleSelected | function handleSelected(
expression: mapboxgl.Expression | string,
exp = false,
selected: mapboxgl.Expression | string
) {
return exp
? expression
: ([
"match",
["feature-state", "state"],
"selected",
selected,
expression,
] as mapboxgl.Expression);
} | /**
* Optionally add a feature-state expression to emphasize this when
* selected.
*
* @param exp: Whether this is exporting, which case omit the selected
* expression.
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/load_and_augment_style.ts#L395-L409 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | asPoint | function asPoint(
ctx: RoughResultTmp,
inputCoordinates: JsonArray
): Point | null {
const coordinates = asCoordinate(inputCoordinates);
if (coordinates === null) return rejectGeometryForCoordinates(ctx);
return {
type: "Point",
coordinates,
};
} | /**
* Geometry ===================================================================
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/roughly_geojson.ts#L226-L236 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | asProperties | function asProperties(
ctx: RoughResultTmp,
root: JsonValue | undefined
): Feature["properties"] {
if (root === undefined || root === null) return {};
if (isObject(root)) return root;
ctx.notes.push(
`Feature #${ctx._state.featureIndex}'s properties were not an object: transformed into one`
);
return { value: root };
} | /**
* All kinds of properties are recoverable
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/roughly_geojson.ts#L398-L408 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | sortParts | function sortParts(parts: readonly VertexId[]): VertexId[] {
return parts.slice().sort((a, b) => b.vertex - a.vertex);
} | /**
* This is necessary because if we're deleting vertexes
* from something, deleting a vertex changes
* the indexes of all the vertexes 'behind' it.
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/map_operations/delete_features.ts#L44-L46 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | getSqDist | function getSqDist(p1: Position, p2: Position) {
const dx = p1[0] - p2[0],
dy = p1[1] - p2[1];
return dx * dx + dy * dy;
} | // square distance between 2 points | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/map_operations/simplify.ts#L48-L53 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | getSqSegDist | function getSqSegDist(p: Position, p1: Position, p2: Position) {
let x = p1[0];
let y = p1[1];
let dx = p2[0] - x;
let dy = p2[1] - y;
if (dx !== 0 || dy !== 0) {
const t = ((p[0] - x) * dx + (p[1] - y) * dy) / (dx * dx + dy * dy);
if (t > 1) {
x = p2[0];
y = p2[1];
} else if (t > 0) {
x += dx * t;
y += dy * t;
}
}
dx = p[0] - x;
dy = p[1] - y;
return dx * dx + dy * dy;
} | // square distance from a point to a segment | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/map_operations/simplify.ts#L56-L78 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | simplifyRadialDist | function simplifyRadialDist(points: Position[], sqTolerance: number) {
let prevPoint = points[0];
const newPoints = [prevPoint];
let point;
for (let i = 1, len = points.length; i < len; i++) {
point = points[i];
if (getSqDist(point, prevPoint) > sqTolerance) {
newPoints.push(point);
prevPoint = point;
}
}
if (prevPoint !== point && point) newPoints.push(point);
return newPoints;
} | // rest of the code doesn't care about point format | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/map_operations/simplify.ts#L82-L99 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | simplifyDouglasPeucker | function simplifyDouglasPeucker(points: Position[], sqTolerance: number) {
const last = points.length - 1;
const simplified = [points[0]];
simplifyDPStep(points, 0, last, sqTolerance, simplified);
simplified.push(points[last]);
return simplified;
} | // simplification using Ramer-Douglas-Peucker algorithm | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/map_operations/simplify.ts#L130-L138 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | simplifyGeom | function simplifyGeom(
geometry: SimplifySupportedGeometry,
options: SimplifyOptions
) {
return match(geometry)
.with({ type: "LineString" }, (geometry) => ({
...geometry,
coordinates: simplifyJS(geometry.coordinates, options),
}))
.with({ type: "MultiLineString" }, (geometry) => ({
...geometry,
coordinates: geometry.coordinates.map((line) =>
simplifyJS(line, options)
),
}))
.with({ type: "Polygon" }, (geometry) => ({
...geometry,
coordinates: simplifyPolygon(geometry.coordinates, options),
}))
.with({ type: "MultiPolygon" }, (geometry) => ({
...geometry,
coordinates: geometry.coordinates.map((polygon) =>
simplifyPolygon(polygon, options)
),
}))
.exhaustive();
} | /**
* Simplifies a feature's coordinates
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/map_operations/simplify.ts#L173-L199 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | checkValidity | function checkValidity(ring: Position[]): boolean {
if (ring.length < 3) return false;
//if the last point is the same as the first, it's not a triangle
return !(
ring.length === 3 &&
ring[2][0] === ring[0][0] &&
ring[2][1] === ring[0][1]
);
} | /**
* Returns true if ring has at least 3 coordinates and its first
* coordinate is the same as its last
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/map_operations/simplify.ts#L240-L248 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | MemPersistence.useTransact | useTransact() {
// eslint-disable-next-line
return useAtomCallback(
// eslint-disable-next-line
useCallback((get, set, partialMoment: Partial<MomentInput>) => {
trackMoment(partialMoment);
const moment: MomentInput = { ...EMPTY_MOMENT, ...partialMoment };
const result = this.apply(moment);
set(momentLogAtom, UMomentLog.pushMoment(get(momentLogAtom), result));
return Promise.resolve();
}, [])
);
} | // eslint-disable-next-line | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/persistence/memory.ts#L109-L121 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | MemPersistence.useHistoryControl | useHistoryControl = () => {
return useAtomCallback(
useCallback((get, set, direction: "undo" | "redo") => {
const momentLog = UMomentLog.shallowCopy(get(momentLogAtom));
const moment = momentLog[direction].shift();
if (!moment) {
// Nothing to undo
return Promise.resolve();
}
const reverse = this.apply(moment);
if (UMoment.isEmpty(reverse)) {
// console.error(
// "[SKIPPING] Got an empty reverse, forward: ",
// moment,
// " reverse: ",
// reverse
// );
return Promise.resolve();
}
const opposite = OPPOSITE[direction];
momentLog[opposite] = [reverse].concat(momentLog[opposite]);
set(momentLogAtom, momentLog);
return Promise.resolve();
}, [])
);
} | // eslint-disable-next-line | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/persistence/memory.ts | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | MemPersistence.deleteFeaturesInner | private deleteFeaturesInner(
features: readonly IWrappedFeature["id"][],
ctx: Data
) {
const moment = momentForDeleteFeatures(features, ctx);
for (const id of features) {
ctx.featureMap.delete(id);
}
return moment;
} | /**
* Inner workings of delete features. Beware,
* changes ctx by reference.
*
* @param features input features
* @param ctx MUTATED
* @returns new moment
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/persistence/memory.ts#L185-L194 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | CUMoment.isEmpty | isEmpty(moment: Moment) {
return (
moment.putFolders.length === 0 &&
moment.deleteFolders.length === 0 &&
moment.putFeatures.length === 0 &&
moment.deleteFeatures.length === 0 &&
moment.putLayerConfigs.length === 0 &&
moment.deleteLayerConfigs.length === 0
);
} | /**
* Does this moment contain nothing?
* Make sure to update this whenever moments get new arrays!
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/persistence/moment.ts#L125-L134 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | CUMomentLog.pushMoment | pushMoment(oldLog: MomentLog, moment: Moment): MomentLog {
if (UMoment.isEmpty(moment)) {
return oldLog;
}
const momentLog = this.shallowCopy(oldLog);
// If there is future history, delete it.
// There is a single linear history.
if (momentLog.redo.length) {
momentLog.redo = [];
}
momentLog.undo = [moment].concat(momentLog.undo).slice(0, HISTORY_LIMIT);
return momentLog;
} | /**
* Record the 'reverse' state
* for a given transaction.
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/persistence/moment.ts#L192-L204 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.