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;
conso... | /**
* 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, 在这... | // 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);... | /**
* 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 la... | // 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 wi... | // 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-s... | // 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).i... | // 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;
... | /**
* @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.getSemanticDoc... | // 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.... | // @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 plain... | /**
* 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... | /**
* @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) {
... | /**
* @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`);
... | /**
* @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"... | /**
* 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 matc... | 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,... | // 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}... | // 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... | /**
* @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... | /**
* @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 (matchedQueryTer... | // @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 sea... | /**
* @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 &&
CHIN... | // 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... | // 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",
/... | // 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, { ... | /**
* 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.ap... | /**
* 注入样式
* @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>(nu... | // 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... | // 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 =... | /* 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) {
... | /* 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 ... | // 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'... | /**
* 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 (i18... | /**
* 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 ... | /**
* 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,
.... | /**
* 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 Th... | 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... | // 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 = scre... | /*!
* 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.participan... | /**
* 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);
... | /**
* 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) ?? [];
... | /**
* 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
* t... | 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... | /**
* 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: ... | // 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 inp... | /**
* 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... | /**
* 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... | /**
* 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 ... | /**
* 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)... | // 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);
prevPo... | // 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) => ({
... | /**
* 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.... | // 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.re... | // 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 = [];
... | /**
* 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.