repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
dolt-workbench | github_2023 | dolthub | typescript | KeyNav | const KeyNav = ({
id = "main-content",
tag = "main",
mobileBreakpoint = 768,
className,
children,
onScroll,
}: Props) => {
const { isMobile } = useReactiveWidth(mobileBreakpoint);
if (!isMobile) {
return (
<DesktopNav className={className} onScroll={onScroll} id={id} tag={tag}>
{children}
</DesktopNav>
);
}
return createElement(tag, { className, onScroll, id }, children);
}; | // This component enables default keyboard navigation for its children. | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/components/util/KeyNav/index.tsx#L15-L33 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | useServerConfigIPC | function useServerConfigIPC(): ServerConfigReturnType {
const [data, setData] = useState<ServerConfigContextValue | undefined>(
undefined,
);
const [error, setError] = useState<any>(undefined);
useEffectAsync(async () => {
const fetchConfig = async () => {
try {
const config = await window.ipc.invoke("api-config");
setData(config);
} catch (err) {
setError(err);
}
};
await fetchConfig();
}, []);
return { data, error };
} | // Custom hook to fetch the server config using IPC | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/contexts/serverConfig.tsx#L34-L54 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | transformColsFromDiffCols | function transformColsFromDiffCols(
cols: ColumnForDataTableFragment[],
hiddenColIndexes: number[],
): Array<{ names: string[] }> {
return cols
.filter((_, i) => !isHiddenColumn(i, hiddenColIndexes))
.map(col => {
return { names: [col.name] };
});
} | // Get names and values for every column based on row value and dolt_commit_diff table | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/hooks/useDoltQueryBuilder/useGetDoltCommitDiffQuery.ts#L79-L88 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | transformColsFromDiffCols | function transformColsFromDiffCols(
cols: ColumnForDataTableFragment[],
row: RowForDataTableFragment,
): ColumnWithNamesAndValue[] {
return cols.map((col, i) => {
const rowVal = row.columnValues[i].displayValue;
return { column: col, names: [col.name], value: rowVal };
});
} | // Get names and values for every column based on row value | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/hooks/useDoltQueryBuilder/useGetDoltDiffQuery.ts#L62-L70 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | getSelectColumns | function getSelectColumns(
cols: ColumnWithNamesAndValue[],
cidx: number,
isPK: boolean,
): string[] {
// Gets all column names for row
if (isPK) {
return getAllSelectColumns(cols);
}
// Gets column names for clicked cell
const currCol = cols[cidx];
return ["diff_type"]
.concat(getToAndFromCols(currCol.names))
.concat(diffColumns);
} | // If PK cell clicked, get all columns in "from_[col1], to_[col1], ..."" order | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/hooks/useDoltQueryBuilder/useGetDoltDiffQuery.ts#L74-L89 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | getConditionsForPKs | function getConditionsForPKs(cols: ColumnWithNamesAndValue[]): string {
const toConditionStrings = getConditionString(cols, "to");
const fromConditionStrings = getConditionString(cols, "from");
return `${toConditionStrings} OR ${fromConditionStrings}`;
} | // Looks like "(to_pk1=val1 AND to_pk2=val2...) OR (from_pk1=val1 AND from_pk2=val2...)" | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/hooks/useDoltQueryBuilder/useGetDoltDiffQuery.ts#L104-L108 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | getConditionString | function getConditionString(
cols: ColumnWithNamesAndValue[],
prefix: "to" | "from",
): string {
const strings = cols
.map(col => getConditionForPK(prefix, col))
.filter(Boolean) as string[];
const joined = strings.join(" AND ");
return strings.length > 1 ? `(${joined})` : joined;
} | // Gets condition string for either "to" or "from" prefix and join with comma | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/hooks/useDoltQueryBuilder/useGetDoltDiffQuery.ts#L111-L120 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | getConditionForPK | function getConditionForPK(
prefix: "to" | "from",
col: ColumnWithNamesAndValue,
): string | null {
if (!col.column.isPrimaryKey) {
return null;
}
const conditions = col.names.map(name => {
const value =
col.column.type === "TIMESTAMP" ? convertTimestamp(col.value) : col.value;
return `\`${prefix}_${name}\` = '${escapeSingleQuotes(value)}'`;
});
if (conditions.length === 1) {
return conditions[0];
}
return `(${conditions.join(" OR ")})`;
} | // If column is primary key, get condition for one name "pk=val" | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/hooks/useDoltQueryBuilder/useGetDoltDiffQuery.ts#L124-L141 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | getCellsNotEqualCondition | function getCellsNotEqualCondition(
currCol: ColumnWithNamesAndValue,
isPK: boolean,
): string | null {
if (isPK) {
return null;
}
const names = currCol.names.map(name => {
const colsNotEqual = `\`from_${name}\` <> \`to_${name}\``;
const fromIsNull = `\`from_${name}\` IS NULL AND \`to_${name}\` IS NOT NULL`;
const toIsNull = `\`from_${name}\` IS NOT NULL AND \`to_${name}\` IS NULL`;
return `${colsNotEqual} OR (${fromIsNull}) OR (${toIsNull})`;
});
return `AND (${names.join(" OR ")})`;
} | // For cell history, gets all rows where from and to columns not equal | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/hooks/useDoltQueryBuilder/useGetDoltDiffQuery.ts#L146-L160 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | extractColumnValues | function extractColumnValues(where: Expr | any): Conditions {
const result: Conditions = [];
function traverse(node?: Expr | any) {
if (!node) return;
if (node.type === "binary_expr" && node.operator === "=") {
if (
(node.left?.type === "column_ref" ||
// TODO: Remove when https://github.com/taozhi8833998/node-sql-parser/issues/1941 is resolved
node.left?.type === "double_quote_string") &&
(node.right?.type === "double_quote_string" ||
node.right.type === "single_quote_string")
) {
const col = node.left.column || node.left.value;
if (shouldAddColToConditions(col)) {
result.push({ col: col.replace("to_", ""), val: node.right.value });
}
}
}
if (node.left) {
traverse(node.left);
}
if (node.right) {
traverse(node.right);
}
}
traverse(where);
return result;
} | // Iterates `where` AST and extracts column names and values | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/hooks/useDoltQueryBuilder/useGetDoltHistoryQuery.ts#L75-L104 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | convertDiffColsToHistoryCols | function convertDiffColsToHistoryCols(
columns: any[] | Column[] | undefined,
): string[] {
if (!columns?.length) return [];
if (columns[0].expr.column === "*") return ["*"];
// Remove dolt_commit_diff_[table] specific columns and column to_ and from_ prefixes
const mappedCols = columns
.slice(1, columns.length - 4)
.map(c => c.expr.column.replace(/(to|from)_/gi, ""));
// Remove any duplicate column names
return mappedCols.filter((c, i) => mappedCols.indexOf(c) === i);
} | // Removes "from_" and "to_" prefixes from columns | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/hooks/useDoltQueryBuilder/useGetDoltHistoryQuery.ts#L107-L118 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | convertToSqlWithNewCols | function convertToSqlWithNewCols(
q: string,
cols: ColumnForDataTableFragment[] | "*",
tableNames?: string[],
): string {
const ast = parseSelectQuery(q);
const isJoinClause = tableNames && tableNames.length > 1;
const columns = u.mapColsToColumnRef(cols, !!isJoinClause);
if (!ast) return "";
if (!tableNames || tableNames.length === 0) {
return convertToSqlSelect({
...ast,
columns,
from: u.getSqlFromTable(null),
where: u.escapeSingleQuotesInWhereObj(ast.where, isPostgres),
});
}
const newAst: Select = {
...ast,
columns,
from: tableNames.map(table => u.getSqlTable(table)),
where: u.escapeSingleQuotesInWhereObj(ast.where, isPostgres),
};
return convertToSqlSelect(newAst);
} | // Converts query string to sql with new table name and columns | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/hooks/useSqlBuilder/index.ts#L39-L64 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | convertToSqlWithNewColNames | function convertToSqlWithNewColNames(
q: string,
cols: string[] | "*",
tableNames: string,
): string {
const ast = parseSelectQuery(q);
const columns = u.mapColsToColumnNames(cols);
if (!ast) return "";
const newAst: Select = {
...ast,
columns,
from: u.getSqlFromTable(tableNames),
where: u.escapeSingleQuotesInWhereObj(ast.where, isPostgres),
};
return convertToSqlSelect(newAst);
} | // Converts query string to sql with new table name and columns | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/hooks/useSqlBuilder/index.ts#L67-L82 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | convertToSqlWithOrderBy | function convertToSqlWithOrderBy(
query: string,
column: string,
type?: "ASC" | "DESC",
): string {
const parsed = parseSelectQuery(query);
if (!parsed) {
return query;
}
const orderby = u.getOrderByArr(parsed, column, type);
return convertToSqlSelect({ ...parsed, orderby });
} | // Adds order by clause to query string | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/hooks/useSqlBuilder/index.ts#L85-L96 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | removeColumnFromQuery | function removeColumnFromQuery(
q: string,
colNameToRemove: string,
cols: ColumnForDataTableFragment[],
): string {
const newCols = cols.filter(c => c.name !== colNameToRemove);
const tableNames = getTableNames(q);
return convertToSqlWithNewCols(q, newCols, tableNames);
} | // Removes a column from a select query | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/hooks/useSqlBuilder/index.ts#L99-L107 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | getTableNames | function getTableNames(q: string): string[] | undefined {
try {
const tl = parser.tableList(q, opt);
return tl.map(tn => {
const [, schemaName, tableName] = tn.split("::");
if (isPostgres && schemaName !== "null") {
return `${schemaName}.${tableName}`;
}
return tableName;
});
} catch (err) {
console.error(getQueryError(q, err));
return undefined;
}
} | // Gets table names as array `{type}::{dbName}::{tableName}` and converts to array of tableNames | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/hooks/useSqlParser/index.ts#L32-L46 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | getTableName | function getTableName(q?: string): Maybe<string> {
if (!q) return undefined;
const tns = getTableNames(q);
if (!tns || tns.length === 0) return undefined;
return tns[0];
} | // Extracts tableName from query | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/hooks/useSqlParser/index.ts#L54-L59 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | getColumns | function getColumns(q: string): any[] | Column[] | undefined {
const ast = parseSelectQuery(q);
return ast?.columns;
} | // Extracts columns from query string | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/hooks/useSqlParser/index.ts#L62-L65 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | queryHasOrderBy | function queryHasOrderBy(
query: string,
column: string,
type?: "ASC" | "DESC",
): boolean {
const parsed = parseSelectQuery(query);
if (!parsed) {
return false;
}
// If no order by, return true for default and false otherwise
if (!parsed.orderby) {
return !type;
}
// If default, check if order by for column exists
if (!type) {
return !parsed.orderby.some(
o => o.expr.column === column || o.expr.value === column,
);
}
// Check if column and type match
return parsed.orderby.some(
o =>
(o.expr.column === column || o.expr.value === column) &&
o.type === type,
);
} | // Check if query has order by clause for column and type | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/hooks/useSqlParser/index.ts#L72-L97 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | getQueryType | function getQueryType(q: string): string | undefined {
let ast = {};
try {
ast = parser.astify(q, opt);
} catch (err) {
console.error(getQueryError(q, err));
return undefined;
}
const obj: AST | undefined = Array.isArray(ast) ? ast[0] : ast;
if (!obj) return undefined;
return obj.type;
} | // Gets the type of query | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/hooks/useSqlParser/index.ts#L100-L111 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | createContextWithNoDefault | function createContextWithNoDefault<T>(): Context<T> {
return createContext<T>(undefined as any);
} | // Creates a React.Context with an undefined default value. | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/lib/createCustomContext.ts#L25-L27 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
dolt-workbench | github_2023 | dolthub | typescript | fetcher | const fetcher = async (input: RequestInfo, init: RequestInit) => {
const res = await fetch(input, init);
if (!res.ok) {
throw await res.json();
}
return res.json();
}; | // configure fetch for use with SWR | https://github.com/dolthub/dolt-workbench/blob/789bcfc3825ebe9a70a339cef43f7dcbe355e00b/web/renderer/pages/_app.tsx#L16-L22 | 789bcfc3825ebe9a70a339cef43f7dcbe355e00b |
bitmagnet | github_2023 | bitmagnet-io | typescript | QueueJobsTableComponent.isAllSelected | isAllSelected() {
return this.items.every((i) => this.selection.isSelected(i.id));
} | /** Whether the number of selected elements matches the total number of rows. */ | https://github.com/bitmagnet-io/bitmagnet/blob/8c4a5c35660942eb0b62a8cea8b698b0a56527d3/webui/src/app/dashboard/queue/queue-jobs-table.component.ts#L67-L69 | 8c4a5c35660942eb0b62a8cea8b698b0a56527d3 |
bitmagnet | github_2023 | bitmagnet-io | typescript | QueueJobsTableComponent.toggleAllRows | toggleAllRows() {
if (this.isAllSelected()) {
this.selection.clear();
return;
}
this.selection.select(...this.items.map((i) => i.id));
} | /** Selects all rows if they are not all selected; otherwise clear selection. */ | https://github.com/bitmagnet-io/bitmagnet/blob/8c4a5c35660942eb0b62a8cea8b698b0a56527d3/webui/src/app/dashboard/queue/queue-jobs-table.component.ts#L72-L78 | 8c4a5c35660942eb0b62a8cea8b698b0a56527d3 |
bitmagnet | github_2023 | bitmagnet-io | typescript | QueueJobsTableComponent.item | item(item: generated.QueueJob): generated.QueueJob {
return item;
} | /**
* Workaround for untyped table cell definitions
*/ | https://github.com/bitmagnet-io/bitmagnet/blob/8c4a5c35660942eb0b62a8cea8b698b0a56527d3/webui/src/app/dashboard/queue/queue-jobs-table.component.ts#L91-L93 | 8c4a5c35660942eb0b62a8cea8b698b0a56527d3 |
bitmagnet | github_2023 | bitmagnet-io | typescript | QueueJobsController.activateFilter | activateFilter(def: FacetDefinition<any>, filter: string) {
this.update((ctrl) => {
const input = def.extractInput(ctrl.facets);
return {
...ctrl,
page: 1,
facets: def.patchInput(ctrl.facets, {
...input,
filter: Array.from(
new Set([...((input.filter as unknown[]) ?? []), filter]),
).sort(),
}),
};
});
} | // eslint-disable-next-line @typescript-eslint/no-explicit-any | https://github.com/bitmagnet-io/bitmagnet/blob/8c4a5c35660942eb0b62a8cea8b698b0a56527d3/webui/src/app/dashboard/queue/queue-jobs.controller.ts#L36-L50 | 8c4a5c35660942eb0b62a8cea8b698b0a56527d3 |
bitmagnet | github_2023 | bitmagnet-io | typescript | QueueJobsController.deactivateFilter | deactivateFilter(def: FacetDefinition<any>, filter: string) {
this.update((ctrl) => {
const input = def.extractInput(ctrl.facets);
const nextFilter: string[] | undefined = input.filter?.filter(
(value) => value !== filter,
);
return {
...ctrl,
page: 1,
facets: def.patchInput(ctrl.facets, {
...input,
filter: nextFilter?.length ? nextFilter : undefined,
}),
};
});
} | // eslint-disable-next-line @typescript-eslint/no-explicit-any | https://github.com/bitmagnet-io/bitmagnet/blob/8c4a5c35660942eb0b62a8cea8b698b0a56527d3/webui/src/app/dashboard/queue/queue-jobs.controller.ts#L53-L68 | 8c4a5c35660942eb0b62a8cea8b698b0a56527d3 |
bitmagnet | github_2023 | bitmagnet-io | typescript | TorrentFilesTableComponent.item | item(item: generated.TorrentFile): generated.TorrentFile {
return item;
} | /**
* Workaround for untyped table cell definitions
*/ | https://github.com/bitmagnet-io/bitmagnet/blob/8c4a5c35660942eb0b62a8cea8b698b0a56527d3/webui/src/app/torrents/torrent-files-table.component.ts#L59-L61 | 8c4a5c35660942eb0b62a8cea8b698b0a56527d3 |
bitmagnet | github_2023 | bitmagnet-io | typescript | TorrentsSearchController.activateFacet | activateFacet(def: FacetDefinition<any, any>) {
this.update((ctrl) => ({
...ctrl,
facets: def.patchInput(ctrl.facets, {
...def.extractInput(ctrl.facets),
active: true,
}),
}));
} | // eslint-disable-next-line @typescript-eslint/no-explicit-any | https://github.com/bitmagnet-io/bitmagnet/blob/8c4a5c35660942eb0b62a8cea8b698b0a56527d3/webui/src/app/torrents/torrents-search.controller.ts#L208-L216 | 8c4a5c35660942eb0b62a8cea8b698b0a56527d3 |
bitmagnet | github_2023 | bitmagnet-io | typescript | TorrentsSearchController.deactivateFacet | deactivateFacet(def: FacetDefinition<any, any>) {
this.update((ctrl) => {
const input = def.extractInput(ctrl.facets);
return {
...ctrl,
page: input.filter ? 1 : ctrl.page,
facets: def.patchInput(ctrl.facets, {
...input,
active: false,
filter: undefined,
}),
};
});
} | // eslint-disable-next-line @typescript-eslint/no-explicit-any | https://github.com/bitmagnet-io/bitmagnet/blob/8c4a5c35660942eb0b62a8cea8b698b0a56527d3/webui/src/app/torrents/torrents-search.controller.ts#L219-L232 | 8c4a5c35660942eb0b62a8cea8b698b0a56527d3 |
bitmagnet | github_2023 | bitmagnet-io | typescript | TorrentsSearchController.activateFilter | activateFilter(def: FacetDefinition<any, any>, filter: string) {
this.update((ctrl) => {
const input = def.extractInput(ctrl.facets);
return {
...ctrl,
page: 1,
facets: def.patchInput(ctrl.facets, {
...input,
filter: Array.from(
new Set([...((input.filter as unknown[]) ?? []), filter]),
).sort(),
}),
};
});
} | // eslint-disable-next-line @typescript-eslint/no-explicit-any | https://github.com/bitmagnet-io/bitmagnet/blob/8c4a5c35660942eb0b62a8cea8b698b0a56527d3/webui/src/app/torrents/torrents-search.controller.ts#L235-L249 | 8c4a5c35660942eb0b62a8cea8b698b0a56527d3 |
bitmagnet | github_2023 | bitmagnet-io | typescript | TorrentsSearchController.deactivateFilter | deactivateFilter(def: FacetDefinition<any, any>, filter: string) {
this.update((ctrl) => {
const input = def.extractInput(ctrl.facets);
const nextFilter: string[] | undefined = input.filter?.filter(
(value) => value !== filter,
);
return {
...ctrl,
page: 1,
facets: def.patchInput(ctrl.facets, {
...input,
filter: nextFilter?.length ? nextFilter : undefined,
}),
};
});
} | // eslint-disable-next-line @typescript-eslint/no-explicit-any | https://github.com/bitmagnet-io/bitmagnet/blob/8c4a5c35660942eb0b62a8cea8b698b0a56527d3/webui/src/app/torrents/torrents-search.controller.ts#L252-L267 | 8c4a5c35660942eb0b62a8cea8b698b0a56527d3 |
bitmagnet | github_2023 | bitmagnet-io | typescript | TorrentsTableComponent.isAllSelected | isAllSelected() {
return this.items.every((i) => this.multiSelection.isSelected(i.infoHash));
} | /** Whether the number of selected elements matches the total number of rows. */ | https://github.com/bitmagnet-io/bitmagnet/blob/8c4a5c35660942eb0b62a8cea8b698b0a56527d3/webui/src/app/torrents/torrents-table.component.ts#L75-L77 | 8c4a5c35660942eb0b62a8cea8b698b0a56527d3 |
bitmagnet | github_2023 | bitmagnet-io | typescript | TorrentsTableComponent.toggleAllRows | toggleAllRows() {
if (this.isAllSelected()) {
this.multiSelection.clear();
return;
}
this.multiSelection.select(...this.items.map((i) => i.infoHash));
} | /** Selects all rows if they are not all selected; otherwise clear selection. */ | https://github.com/bitmagnet-io/bitmagnet/blob/8c4a5c35660942eb0b62a8cea8b698b0a56527d3/webui/src/app/torrents/torrents-table.component.ts#L80-L86 | 8c4a5c35660942eb0b62a8cea8b698b0a56527d3 |
bitmagnet | github_2023 | bitmagnet-io | typescript | TorrentsTableComponent.item | item(item: generated.TorrentContent): generated.TorrentContent {
return item;
} | /**
* Workaround for untyped table cell definitions
*/ | https://github.com/bitmagnet-io/bitmagnet/blob/8c4a5c35660942eb0b62a8cea8b698b0a56527d3/webui/src/app/torrents/torrents-table.component.ts#L104-L106 | 8c4a5c35660942eb0b62a8cea8b698b0a56527d3 |
react-native-unistyles | github_2023 | jpudysz | typescript | cyrb53 | const cyrb53 = (data: string, seed = 0) => {
let h1 = 0xdeadbeef ^ seed
let h2 = 0x41c6ce57 ^ seed
for (let i = 0, ch: number; i < data.length; i++) {
ch = data.charCodeAt(i)
h1 = Math.imul(h1 ^ ch, 2654435761)
h2 = Math.imul(h2 ^ ch, 1597334677)
}
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)
return 4294967296 * (2097151 & h2) + (h1 >>> 0)
} | // Based on https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js | https://github.com/jpudysz/react-native-unistyles/blob/368887fd75be696ad99ea03050e7e9836de2b7c6/src/web/utils/common.ts#L49-L63 | 368887fd75be696ad99ea03050e7e9836de2b7c6 |
chat-llamaindex | github_2023 | run-llama | typescript | addFileToPipeline | async function addFileToPipeline(
projectId: string,
pipelineId: string,
uploadFile: File | Blob,
customMetadata: Record<string, any> = {},
) {
const file = await FilesService.uploadFileApiV1FilesPost({
projectId,
formData: {
upload_file: uploadFile,
},
});
const files = [
{
file_id: file.id,
custom_metadata: { file_id: file.id, ...customMetadata },
},
];
await PipelinesService.addFilesToPipelineApiV1PipelinesPipelineIdFilesPut({
pipelineId,
requestBody: files,
});
} | // TODO: should be moved to LlamaCloudFileService of LlamaIndexTS | https://github.com/run-llama/chat-llamaindex/blob/179c907196cf4f63f6d3ae1beb192186a1e00a0c/app/api/chat/engine/generate.ts#L35-L57 | 179c907196cf4f63f6d3ae1beb192186a1e00a0c |
chat-llamaindex | github_2023 | run-llama | typescript | withBot | function withBot(Component: React.FunctionComponent, bot?: Bot) {
return function WithBotComponent() {
const [botInitialized, setBotInitialized] = useState(false);
const navigate = useNavigate();
const botStore = useBotStore();
if (bot && !botInitialized) {
if (!bot.share?.id) {
throw new Error("bot must have a shared id");
}
// ensure that bot for the same share id is not created a 2nd time
let sharedBot = botStore.getByShareId(bot.share?.id);
if (!sharedBot) {
sharedBot = botStore.create(bot, { readOnly: true });
}
// let the user directly chat with the bot
botStore.selectBot(sharedBot.id);
setTimeout(() => {
// redirect to chat - use history API to clear URL
history.pushState({}, "", "/");
navigate(Path.Chat);
}, 1);
setBotInitialized(true);
return <LoadingPage />;
}
return <Component />;
};
} | // if a bot is passed this HOC ensures that the bot is added to the store | https://github.com/run-llama/chat-llamaindex/blob/179c907196cf4f63f6d3ae1beb192186a1e00a0c/app/components/home.tsx#L54-L81 | 179c907196cf4f63f6d3ae1beb192186a1e00a0c |
streamlit-shadcn-ui | github_2023 | ObservedObserver | typescript | ComponentRouter.declare | declare<C extends React.ComponentType<any>>(name: string, component: C) {
this.collection.set(name, component);
} | // Use a generic type for the declare method to ensure type safety | https://github.com/ObservedObserver/streamlit-shadcn-ui/blob/52e74d116d397295ddd56d3ab0eccff100f6e68f/streamlit_shadcn_ui/components/packages/frontend/src/componentRouter.tsx#L8-L10 | 52e74d116d397295ddd56d3ab0eccff100f6e68f |
streamlit-shadcn-ui | github_2023 | ObservedObserver | typescript | ComponentRouter.render | render(name: string, ref: React.MutableRefObject<any>, props: Record<string, any>): React.ReactNode {
const Component = this.collection.get(name);
if (Component) {
// Correctly spread props into the component
return <Component {...props} ref={ref} />;
}
return <div ref={ref}>Undefined Component {name}</div>;
} | // Use React.ReactNode as the return type for render method | https://github.com/ObservedObserver/streamlit-shadcn-ui/blob/52e74d116d397295ddd56d3ab0eccff100f6e68f/streamlit_shadcn_ui/components/packages/frontend/src/componentRouter.tsx#L13-L20 | 52e74d116d397295ddd56d3ab0eccff100f6e68f |
streamlit-shadcn-ui | github_2023 | ObservedObserver | typescript | handleInputChange | const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(event.target.value);
Streamlit.setComponentValue(event.target.value);
}; | // Handle input change | https://github.com/ObservedObserver/streamlit-shadcn-ui/blob/52e74d116d397295ddd56d3ab0eccff100f6e68f/streamlit_shadcn_ui/components/packages/frontend/src/components/streamlit/input.tsx#L24-L27 | 52e74d116d397295ddd56d3ab0eccff100f6e68f |
streamlit-shadcn-ui | github_2023 | ObservedObserver | typescript | handleRadioChange | const handleRadioChange = (value: string) => {
setSelectedValue(value);
Streamlit.setComponentValue(value);
}; | // Handle radio value change | https://github.com/ObservedObserver/streamlit-shadcn-ui/blob/52e74d116d397295ddd56d3ab0eccff100f6e68f/streamlit_shadcn_ui/components/packages/frontend/src/components/streamlit/radioGroup.tsx#L22-L25 | 52e74d116d397295ddd56d3ab0eccff100f6e68f |
streamlit-shadcn-ui | github_2023 | ObservedObserver | typescript | handleSliderChange | const handleSliderChange = (value: number[]) => {
setSliderValue(value);
Streamlit.setComponentValue(value);
}; | // Handle slider value change | https://github.com/ObservedObserver/streamlit-shadcn-ui/blob/52e74d116d397295ddd56d3ab0eccff100f6e68f/streamlit_shadcn_ui/components/packages/frontend/src/components/streamlit/slider.tsx#L19-L22 | 52e74d116d397295ddd56d3ab0eccff100f6e68f |
streamlit-shadcn-ui | github_2023 | ObservedObserver | typescript | handleTextareaChange | const handleTextareaChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
setTextareaValue(event.target.value);
Streamlit.setComponentValue(event.target.value);
}; | // Handle textarea value change | https://github.com/ObservedObserver/streamlit-shadcn-ui/blob/52e74d116d397295ddd56d3ab0eccff100f6e68f/streamlit_shadcn_ui/components/packages/frontend/src/components/streamlit/textarea.tsx#L23-L26 | 52e74d116d397295ddd56d3ab0eccff100f6e68f |
streamlit-shadcn-ui | github_2023 | ObservedObserver | typescript | ArrowTable.serialize | public serialize(): ArrowTableProto {
return {
data: tableToIPC(this.dataTable),
index: tableToIPC(this.indexTable),
columns: tableToIPC(this.columnsTable )
};
} | /**
* Serialize arrow table.
*/ | https://github.com/ObservedObserver/streamlit-shadcn-ui/blob/52e74d116d397295ddd56d3ab0eccff100f6e68f/streamlit_shadcn_ui/components/packages/streamlit-component-lib/src/ArrowTable.ts#L228-L234 | 52e74d116d397295ddd56d3ab0eccff100f6e68f |
streamlit-shadcn-ui | github_2023 | ObservedObserver | typescript | ArrowTable.getColumnTypeId | private getColumnTypeId(table: Table, columnIndex: number): Type {
return table.schema.fields[columnIndex].type.typeId;
} | /**
* Returns apache-arrow specific typeId of column.
*/ | https://github.com/ObservedObserver/streamlit-shadcn-ui/blob/52e74d116d397295ddd56d3ab0eccff100f6e68f/streamlit_shadcn_ui/components/packages/streamlit-component-lib/src/ArrowTable.ts#L239-L241 | 52e74d116d397295ddd56d3ab0eccff100f6e68f |
streamlit-shadcn-ui | github_2023 | ObservedObserver | typescript | ComponentWrapper.getDerivedStateFromError | public static getDerivedStateFromError = (
error: Error
): Partial<WrapperState> => {
return { componentError: error };
} | /**
* Error boundary function. This will be called if our wrapped
* component throws an error. We store the caught error in our state,
* and display it in the next render().
*/ | https://github.com/ObservedObserver/streamlit-shadcn-ui/blob/52e74d116d397295ddd56d3ab0eccff100f6e68f/streamlit_shadcn_ui/components/packages/streamlit-component-lib/src/StreamlitReact.tsx | 52e74d116d397295ddd56d3ab0eccff100f6e68f |
streamlit-shadcn-ui | github_2023 | ObservedObserver | typescript | Streamlit.setComponentReady | public static setComponentReady = (): void => {
if (!Streamlit.registeredMessageListener) {
// Register for message events if we haven't already
window.addEventListener("message", Streamlit.onMessageEvent);
Streamlit.registeredMessageListener = true;
}
Streamlit.sendBackMsg(ComponentMessageType.COMPONENT_READY, {
apiVersion: Streamlit.API_VERSION
});
} | /**
* Set the component's value. This value will be returned to the Python
* script, and the script will be re-run.
*
* For example:
*
* JavaScript:
* Streamlit.setComponentValue("ahoy!")
*
* Python:
* value = st.my_component(...)
* st.write(value) # -> "ahoy!"
*
* The value must be an ArrowTable, a typed array, an ArrayBuffer, or be
* serializable to JSON.
*/ | https://github.com/ObservedObserver/streamlit-shadcn-ui/blob/52e74d116d397295ddd56d3ab0eccff100f6e68f/streamlit_shadcn_ui/components/packages/streamlit-component-lib/src/streamlit.ts | 52e74d116d397295ddd56d3ab0eccff100f6e68f |
streamlit-shadcn-ui | github_2023 | ObservedObserver | typescript | isTypedArray | function isTypedArray(value: any): value is TypedArray {
let isBigIntArray = false;
try {
isBigIntArray =
value instanceof BigInt64Array || value instanceof BigUint64Array;
} catch (e) {
// Ignore cause Safari does not support this
// https://caniuse.com/mdn-javascript_builtins_bigint64array
}
return (
value instanceof Int8Array ||
value instanceof Uint8Array ||
value instanceof Uint8ClampedArray ||
value instanceof Int16Array ||
value instanceof Uint16Array ||
value instanceof Int32Array ||
value instanceof Uint32Array ||
value instanceof Float32Array ||
value instanceof Float64Array ||
isBigIntArray
);
} | /** True if the value is a TypedArray. */ | https://github.com/ObservedObserver/streamlit-shadcn-ui/blob/52e74d116d397295ddd56d3ab0eccff100f6e68f/streamlit_shadcn_ui/components/packages/streamlit-component-lib/src/streamlit.ts#L270-L292 | 52e74d116d397295ddd56d3ab0eccff100f6e68f |
nostalgist | github_2023 | arianrhodsandlot | typescript | EmulatorOptions.retroarchConfig | get retroarchConfig() {
const options = {}
merge(options, getGlobalOptions().retroarchConfig, this.nostalgistOptions.retroarchConfig)
return options as typeof this.nostalgistOptions.retroarchConfig
} | /**
* RetroArch config.
* Not all options can make effects in browser.
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/emulator-options.ts#L51-L55 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | EmulatorOptions.retroarchCoreConfig | get retroarchCoreConfig() {
const options = {}
merge(options, getGlobalOptions().retroarchCoreConfig, this.nostalgistOptions.retroarchCoreConfig)
return options as typeof this.nostalgistOptions.retroarchCoreConfig
} | /**
* RetroArch core config.
* Not all options can make effects in browser.
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/emulator-options.ts#L61-L65 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Emulator.stdin | private stdin() {
const { messageQueue } = this
// Return ASCII code of character, or null if no input
while (messageQueue.length > 0) {
const msg = messageQueue[0][0]
const index = messageQueue[0][1]
if (index >= msg.length) {
messageQueue.shift()
} else {
messageQueue[0][1] = index + 1
// assumption: msg is a uint8array
return msg[index]
}
}
return null
} | // copied from https://github.com/libretro/RetroArch/pull/15017 | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/emulator.ts#L473-L488 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.configure | static configure(options: NostalgistOptionsPartial) {
updateGlobalOptions(options)
} | /**
* Update the global options for `Nostalgist`, so everytime the `Nostalgist.launch` method or shortcuts like `Nostalgist.nes` is called, the default options specified here will be used.
*
* You may want to specify how to resolve ROMs and RetroArch cores here.
*
* @see {@link https://nostalgist.js.org/apis/configure/}
*
* @example
* ```js
* Nostalgist.configure({
* resolveRom({ file }) {
* return `https://example.com/roms/${file}`
* },
* // other configuation can also be specified here
* })
* ```
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L47-L49 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.gb | static async gb(options: NostalgistLaunchRomOptions | ResolvableFileInput) {
return await Nostalgist.launchSystem('gb', options)
} | /**
* A shortcut method for Nostalgist.launch method, with some additional default options for GB emulation.
*
* It will use mgba as the default core for emulation.
*
* @see {@link https://nostalgist.js.org/apis/gb/}
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L58-L60 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.gba | static async gba(options: NostalgistLaunchRomOptions | ResolvableFileInput) {
return await Nostalgist.launchSystem('gba', options)
} | /**
* A shortcut method for Nostalgist.launch method, with some additional default options for GBA emulation.
*
* It will use mgba as the default core for emulation.
*
* @see {@link https://nostalgist.js.org/apis/gba/}
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L69-L71 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.gbc | static async gbc(options: NostalgistLaunchRomOptions | ResolvableFileInput) {
return await Nostalgist.launchSystem('gbc', options)
} | /**
* A shortcut method for Nostalgist.launch method, with some additional default options for GBC emulation.
*
* It will use mgba as the default core for emulation.
*
* @see {@link https://nostalgist.js.org/apis/gbc/}
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L80-L82 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.launch | static async launch(options: NostalgistLaunchOptions) {
const nostalgist = new Nostalgist(options)
await nostalgist.load()
return nostalgist
} | /**
* Launch an emulator and return a `Promise` of the instance of the emulator.
*
* @see {@link https://nostalgist.js.org/apis/launch/}
*
* @example
* A simple example:
* ```js
* const nostalgist = await Nostalgist.launch({
* core: 'fceumm',
* rom: 'flappybird.nes',
* })
* ```
*
* @example
* A more complex one:
* ```js
* const nostalgist = await Nostalgist.launch({
* element: document.querySelector('.emulator-canvas'),
* core: 'fbneo',
* rom: ['mslug.zip'],
* bios: ['neogeo.zip'],
* retroarchConfig: {
* rewind_enable: true,
* savestate_thumbnail_enable: true,
* }
* runEmulatorManually: false,
* resolveCoreJs(core) {
* return `https://example.com/core/${core}_libretro.js`
* },
* resolveCoreWasm(core) {
* return `https://example.com/core/${core}_libretro.wasm`
* },
* resolveRom(file) {
* return `https://example.com/roms/${file}`
* },
* resolveBios(bios) {
* return `https://example.com/system/${bios}`
* },
* })
* ```
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L126-L130 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.megadrive | static async megadrive(options: NostalgistLaunchRomOptions | ResolvableFileInput) {
return await Nostalgist.launchSystem('megadrive', options)
} | /**
* A shortcut method for Nostalgist.launch method, with some additional default options for Sega Genesis / Megadrive emulation.
*
* It will use genesis_plus_gx as the default core for emulation.
*
* @see {@link https://nostalgist.js.org/apis/megadrive/}
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L139-L141 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.nes | static async nes(options: NostalgistLaunchRomOptions | ResolvableFileInput) {
return await Nostalgist.launchSystem('nes', options)
} | /**
* A shortcut method for Nostalgist.launch method, with some additional default options for NES emulation.
*
* It will use fceumm as the default core for emulation.
*
* @see {@link https://nostalgist.js.org/apis/nes/}
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L150-L152 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.resetToDefault | static resetToDefault() {
resetGlobalOptions()
} | /**
* Reset the global configuation set by `Nostalgist.configure` to default.
*
* @see {@link https://nostalgist.js.org/apis/reset-to-default/}
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L159-L161 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.snes | static async snes(options: NostalgistLaunchRomOptions | ResolvableFileInput) {
return await Nostalgist.launchSystem('snes', options)
} | /**
* A shortcut method for Nostalgist.launch method, with some additional default options for SNES emulation.
*
* It will use snes9x as the default core for emulation.
*
* @see {@link https://nostalgist.js.org/apis/snes/}
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L170-L172 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.exit | exit({ removeCanvas = true }: { removeCanvas?: boolean } = {}) {
this.getEmulator().exit()
if (removeCanvas) {
this.getCanvas().remove()
}
} | /**
* Exit the current running game and the emulator. Remove the canvas element used by the emulator if needed.
*
* @see {@link https://nostalgist.js.org/apis/exit/}
*
* @example
* ```js
* const nostalgist = await Nostalgist.nes('flappybird.nes')
*
* nostalgist.exit()
* ```
* ```js
* const nostalgist = await Nostalgist.nes('flappybird.nes')
*
* // the canvas element will not be removed
* nostalgist.exit({ removeCanvas: false })
* ```
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L198-L203 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.getCanvas | getCanvas() {
return this.getEmulatorOptions().element
} | /**
* Get the canvas DOM element that the current emulator is using.
*
* @see {@link https://nostalgist.js.org/apis/get-canvas/}
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L210-L212 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.getEmscripten | getEmscripten(): any {
const emulator = this.getEmulator()
return emulator.getEmscripten()
} | /**
* Get the Emscripten object exposed by RetroArch.
*
* @see {@link https://nostalgist.js.org/apis/get-emscripten-module/}
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L219-L222 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.getEmscriptenAL | getEmscriptenAL() {
const emulator = this.getEmulator()
return emulator.getEmscripten().AL
} | /**
* Get the Emscripten AL object exposed by RetroArch.
*
* @see {@link https://nostalgist.js.org/apis/get-emscripten-module/}
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L229-L232 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.getEmscriptenFS | getEmscriptenFS() {
const emulator = this.getEmulator()
const emscripten = emulator.getEmscripten()
return emscripten.Module.FS
} | /**
* Get the Emscripten FS object of the current running emulator.
*
* @see {@link https://nostalgist.js.org/apis/get-emscripten-fs/}
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L239-L243 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.getEmscriptenModule | getEmscriptenModule() {
const emulator = this.getEmulator()
const emscripten = emulator.getEmscripten()
return emscripten.Module
} | /**
* Get the Emscripten Module object of the current running emulator.
*
* @see {@link https://nostalgist.js.org/apis/get-emscripten-module/}
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L250-L254 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.launchEmulator | async launchEmulator() {
return await this.getEmulator().launch()
} | /**
* Launch the emulator, if it's not launched, because of the launch option `runEmulatorManually` being set to `true`.
*
* @see {@link https://nostalgist.js.org/apis/launch-emulator/}
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L280-L282 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.loadState | async loadState(state: Blob) {
const resolvable = await ResolvableFile.create(state)
await this.getEmulator().loadState(resolvable)
} | /**
* Load a state for the current running emulator and game.
*
* @see {@link https://nostalgist.js.org/apis/load-state/}
*
* @example
* ```js
* const nostalgist = await Nostalgist.nes('flappybird.nes')
*
* // save the state
* const { state } = await nostalgist.saveState()
*
* // load the state
* await nostalgist.loadState(state)
* ```
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L300-L303 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.pause | pause() {
this.getEmulator().pause()
} | /**
* Pause the current running game.
*
* @see {@link https://nostalgist.js.org/apis/pause/}
*
* @example
* ```js
* const nostalgist = await Nostalgist.nes('flappybird.nes')
*
* nostalgist.pause()
* ```
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L317-L319 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.press | async press(options: { button: string; player?: number; time?: number } | string) {
const emulator = this.getEmulator()
await (typeof options === 'string'
? emulator.press(options)
: emulator.press(options.button, options.player, options.time))
} | /**
* Press a button and then release it programmatically. Analog Joysticks are not supported by now.
*
* @see {@link https://nostalgist.js.org/apis/press/}
*
* @example
* ```js
* const nostalgist = await Nostalgist.nes('flappybird.nes')
*
* await nostalgist.press('start')
* ```
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L333-L338 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.pressDown | pressDown(options: { button: string; player?: number } | string) {
const emulator = this.getEmulator()
if (typeof options === 'string') {
return emulator.pressDown(options)
}
return emulator.pressDown(options.button, options.player)
} | /**
* Press a button programmatically. Analog Joysticks are not supported by now.
*
* @see {@link https://nostalgist.js.org/apis/press-down/}
*
* @example
* ```js
* const nostalgist = await Nostalgist.nes('flappybird.nes')
*
* nostalgist.pressDown('start')
* ```
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L352-L358 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.pressUp | pressUp(options: { button: string; player?: number } | string) {
const emulator = this.getEmulator()
if (typeof options === 'string') {
return emulator.pressUp(options)
}
return emulator.pressUp(options.button, options.player)
} | /**
* Release it programmatically. Analog Joysticks are not supported by now.
*
* @see {@link https://nostalgist.js.org/apis/press-up/}
*
* @example
* ```js
* const nostalgist = await Nostalgist.nes('flappybird.nes')
*
* nostalgist.pressUp('start')
* ```
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L372-L378 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.resize | resize(size: { height: number; width: number }) {
return this.getEmulator().resize(size)
} | /**
* Resize the canvas element of the emulator.
*
* @see {@link https://nostalgist.js.org/apis/resize/}
*
* @example
* ```js
* const nostalgist = await Nostalgist.nes('flappybird.nes')
*
* nostalgist.resize({ width: 1000, height: 800 })
* ```
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L392-L394 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.restart | restart() {
this.getEmulator().restart()
} | /**
* Restart the current running game.
*
* @see {@link https://nostalgist.js.org/apis/restart/}
*
* @example
* ```js
* const nostalgist = await Nostalgist.nes('flappybird.nes')
*
* nostalgist.restart()
* ```
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L408-L410 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.resume | resume() {
this.getEmulator().resume()
} | /**
* Resume the current running game, if it has been paused by `pause`.
*
* @see {@link https://nostalgist.js.org/apis/resume/}
*
* @example
* ```js
* const nostalgist = await Nostalgist.nes('flappybird.nes')
*
* nostalgist.pause()
* await new Promise(resolve => setTimeout(resolve, 1000))
* nostalgist.resume()
* ```
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L426-L428 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.saveSRAM | async saveSRAM() {
const emulator = this.getEmulator()
return await emulator.saveSRAM()
} | /**
* Save the SRAM of the current running game.
*
* @see {@link https://nostalgist.js.org/apis/save-sram/}
*
* @example
* ```js
* const nostalgist = await Nostalgist.nes('flappybird.nes')
*
* const sram = await nostalgist.saveSRAM()
* ```
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L442-L445 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.saveState | async saveState() {
return await this.getEmulator().saveState()
} | /**
* Save the state of the current running game.
*
* @see {@link https://nostalgist.js.org/apis/save-state/}
*
* @example
* ```js
* const nostalgist = await Nostalgist.nes('flappybird.nes')
*
* // save the state
* const { state } = await nostalgist.saveState()
*
* // load the state
* await nostalgist.loadState(state)
* ```
* @returns
* A Promise of the state of the current running game.
*
* Its type is like `Promise<{ state: Blob, thumbnail: Blob | undefined }>`.
*
* If RetroArch is launched with the option `savestate_thumbnail_enable` set to `true`, which is the default value inside Nostalgist.js, then the `thumbnail` will be a `Blob`. Otherwise the `thumbnail` will be `undefined`.
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L469-L471 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.screenshot | async screenshot() {
const emulator = this.getEmulator()
return await emulator.screenshot()
} | /**
* Take a screenshot for the current running game.
*
* @see {@link https://nostalgist.js.org/apis/screenshot/}
*
* @example
* ```js
* const nostalgist = await Nostalgist.nes('flappybird.nes')
*
* const blob = await nostalgist.screenshot()
* ```
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L485-L488 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.sendCommand | sendCommand(command: RetroArchCommand) {
const emulator = this.getEmulator()
return emulator.sendCommand(command)
} | /**
* Send a command to RetroArch.
* The commands are listed here: https://docs.libretro.com/development/retroarch/network-control-interface/#commands .
* But not all of them are supported inside a browser.
*
* @see {@link https://nostalgist.js.org/apis/send-command/}
*
* @example
* ```js
* const nostalgist = await Nostalgist.nes('flappybird.nes')
*
* nostalgist.sendCommand('FAST_FORWARD')
* ```
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L504-L507 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | Nostalgist.load | private async load(): Promise<void> {
this.emulatorOptions = await EmulatorOptions.create(this.options)
checkIsAborted(this.options.signal)
this.loadEmulator()
if (!this.options.runEmulatorManually) {
await this.launchEmulator()
}
} | /**
* Load options and then launch corresponding emulator if should
*/ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/nostalgist.ts#L512-L520 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | ResolvableFile.baseName | get baseName() {
return path.parse(this.name).name
} | /** The base name of the file, without its extension. */ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/resolvable-file.ts#L66-L68 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
nostalgist | github_2023 | arianrhodsandlot | typescript | ResolvableFile.extension | get extension() {
return path.parse(this.name).ext
} | /** The extension name of the file, with a leading ".". */ | https://github.com/arianrhodsandlot/nostalgist/blob/cb7ae947aafa534acdbc79457c238cf40c4b72d5/src/classes/resolvable-file.ts#L71-L73 | cb7ae947aafa534acdbc79457c238cf40c4b72d5 |
powersync-js | github_2023 | powersync-ja | typescript | EditLayout | const EditLayout = () => {
return <Stack />;
}; | /**
* Stack to edit a todo list from the todos view
*/ | https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/demos/django-react-native-todolist/app/views/todos/_layout.tsx#L7-L9 | e1904547f3641eb8fa505dbf0cbd21fae6233a49 |
powersync-js | github_2023 | powersync-ja | typescript | createWindow | const createWindow = () => {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600
});
mainWindow.webContents.inspectSharedWorker();
// and load the index.html of the app.
if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
mainWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
} else {
/**
* The PowerSync web SDK relies on SharedWorkers for multiple tab support.
* Multiple tab support in Electron is required if multiple `BrowserWindow`s
* require the PowerSync client simultaneously.
*
* The default solution of serving HTML assets from a file is sufficient if multiple
* tab support is not required.
*
* ```js
* mainWindow.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`));
* ```
*
* Extra steps are required if multiple tab support is required.
*
* Serving from a file results in `window.origin` being set as `file://`.
*
* Usually creating multiple `SharedWorker` instances from the same JS context should
* link to the same instance of the shared worker. However, multiple worker instances
* will be created if the origin is not the same. Apparently `file://` origins cause
* the latter.
*
* For example:
* ```js
* const worker1 = new SharedWorker('url');
* const worker2 = new SharedWorker('url');
*```
*
* Should only create 1 instance of a SharedWorker with `worker1` and `worker2`
* pointing to the same instance.
*
* When the content is served from a file `worker1` and `worker2` point to different
* (unique) instances of the shared worker code.
*
* The PowerSync SDK relies on a single shared worker instance being present.
*
* See: https://github.com/electron/electron/issues/13952
*
* This serves the production HTML assets via a HTTP server. This sets the Window
* origin to a the server address. This results in expected SharedWorker
* functionality.
*/
const expressApp = express();
// The Vite production output should all be here.
const bundleDir = path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}`);
// Serve the assets production assets
expressApp.use(express.static(bundleDir));
/**
* If the port used here is dynamic e.g. `0` then the session would be cleared
* if the port changes. A fixed port should be used in production.
* Care should be taken when selecting this port to avoid conflicts.
* This demo uses a random fixed port for demonstration purposes. More advanced
* port management should be implemented if using this in production.
*/
const port = process.env.PORT || 40031;
const server = expressApp.listen(port, () => {
mainWindow.loadURL(`http://127.0.0.1:${port}`);
});
app.on('quit', () => server.close());
}
// Open the DevTools.
mainWindow.webContents.openDevTools();
}; | // Handle creating/removing shortcuts on Windows when installing/uninstalling. | https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/demos/example-electron/src/main.ts#L13-L92 | e1904547f3641eb8fa505dbf0cbd21fae6233a49 |
powersync-js | github_2023 | powersync-ja | typescript | handleSave | async function handleSave() {
const addedContacts = new Set<string>();
const removedContacts = new Set<string>();
// Find removed contacts
for (const elem of members) {
if (!selectedContacts.has(elem)) {
removedContacts.add(elem);
}
}
// Find added contacts
for (const elem of selectedContacts) {
if (!members.has(elem)) {
addedContacts.add(elem);
}
}
await powerSync.writeTransaction(async (tx) => {
try {
await tx.execute('UPDATE groups SET name= ? WHERE id = ?', [name, groupId]);
for (const profileId of removedContacts) {
await tx.execute('DELETE FROM memberships WHERE group_id = ? AND profile_id = ?', [groupId, profileId]);
}
for (const profileId of addedContacts) {
const membershipId = uuid();
await tx.execute(
'INSERT INTO memberships (id, group_id, profile_id, created_at) VALUES (?, ?, ?, datetime())',
[membershipId, groupId, profileId]
);
}
router.back();
} catch (error) {
console.error('Error', error);
}
});
} | /* useEffect(() => {
async function loadMembers() {
const groups = await powerSync.execute(
"SELECT name FROM groups WHERE id = ?",
[groupId]
);
setName(groups.rows?._array[0]?.name);
const members = await powerSync.execute(
"SELECT profile_id FROM memberships WHERE group_id = ?",
[groupId]
);
const memberIds = members.rows?._array.map((obj) => obj.profile_id);
setMembers(new Set(memberIds));
setSelectedContacts(new Set(memberIds));
}
if (groupId) {
loadMembers();
}
}, [groupId]); */ | https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/demos/react-native-supabase-group-chat/src/app/(app)/(chats)/g/[group]/settings.tsx#L57-L93 | e1904547f3641eb8fa505dbf0cbd21fae6233a49 |
powersync-js | github_2023 | powersync-ja | typescript | App | const App: React.FC = () => {
const { supabaseConnector } = useSystem();
React.useEffect(() => {
Logger.useDefaults();
Logger.setLevel(Logger.DEBUG);
supabaseConnector.client.auth
.getSession()
.then(({ data }) => {
if (data.session) {
router.replace('views/todos/lists');
} else {
throw new Error('Signin required');
}
})
.catch(() => {
router.replace('signin');
});
}, []);
return (
<ThemeProvider theme={theme}>
<View key={`loader`} style={{ flex: 1, flexGrow: 1, alignContent: 'center', justifyContent: 'center' }}>
<ActivityIndicator />
</View>
</ThemeProvider>
);
}; | /**
* This is the entry point when the app loads.
* Checks for a Supabase session.
* - If one is present redirect to app views.
* - If not, reditect to login/register flow
*/ | https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/demos/react-native-supabase-todolist/app/index.tsx#L20-L47 | e1904547f3641eb8fa505dbf0cbd21fae6233a49 |
powersync-js | github_2023 | powersync-ja | typescript | EditLayout | const EditLayout = () => {
return <Stack />;
}; | /**
* Stack to edit a list from the todos view
*/ | https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/demos/react-native-supabase-todolist/app/views/todos/_layout.tsx#L6-L8 | e1904547f3641eb8fa505dbf0cbd21fae6233a49 |
powersync-js | github_2023 | powersync-ja | typescript | createSearchTermWithOptions | function createSearchTermWithOptions(searchTerm: string): string {
const searchTermWithOptions: string = `${searchTerm}*`;
return searchTermWithOptions;
} | /**
* adding * to the end of the search term will match any word that starts with the search term
* e.g. searching bl will match blue, black, etc.
* consult FTS5 Full-text Query Syntax documentation for more options
* @param searchTerm
* @returns a modified search term with options.
*/ | https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/demos/react-native-supabase-todolist/library/fts/fts_helpers.ts#L10-L13 | e1904547f3641eb8fa505dbf0cbd21fae6233a49 |
powersync-js | github_2023 | powersync-ja | typescript | createFtsTable | async function createFtsTable(
db: PowerSyncDatabase,
tableName: string,
columns: string[],
tokenizationMethod = 'unicode61'
): Promise<void> {
const internalName = AppSchema.tables.find((table) => table.name === tableName)?.internalName;
const stringColumns = columns.join(', ');
return await db.writeTransaction(async (tx) => {
// Add FTS table
await tx.execute(`
CREATE VIRTUAL TABLE IF NOT EXISTS fts_${tableName}
USING fts5(id UNINDEXED, ${stringColumns}, tokenize='${tokenizationMethod}');
`);
// Copy over records already in table
await tx.execute(`
INSERT OR REPLACE INTO fts_${tableName}(rowid, id, ${stringColumns})
SELECT rowid, id, ${generateJsonExtracts(ExtractType.columnOnly, 'data', columns)} FROM ${internalName};
`);
// Add INSERT, UPDATE and DELETE and triggers to keep fts table in sync with table
await tx.execute(`
CREATE TRIGGER IF NOT EXISTS fts_insert_trigger_${tableName} AFTER INSERT ON ${internalName}
BEGIN
INSERT INTO fts_${tableName}(rowid, id, ${stringColumns})
VALUES (
NEW.rowid,
NEW.id,
${generateJsonExtracts(ExtractType.columnOnly, 'NEW.data', columns)}
);
END;
`);
await tx.execute(`
CREATE TRIGGER IF NOT EXISTS fts_update_trigger_${tableName} AFTER UPDATE ON ${internalName} BEGIN
UPDATE fts_${tableName}
SET ${generateJsonExtracts(ExtractType.columnInOperation, 'NEW.data', columns)}
WHERE rowid = NEW.rowid;
END;
`);
await tx.execute(`
CREATE TRIGGER IF NOT EXISTS fts_delete_trigger_${tableName} AFTER DELETE ON ${internalName} BEGIN
DELETE FROM fts_${tableName} WHERE rowid = OLD.rowid;
END;
`);
});
} | /**
* Create a Full Text Search table for the given table and columns
* with an option to use a different tokenizer otherwise it defaults
* to unicode61. It also creates the triggers that keep the FTS table
* and the PowerSync table in sync.
* @param tableName
* @param columns
* @param tokenizationMethod
*/ | https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/demos/react-native-supabase-todolist/library/fts/fts_setup.ts#L14-L59 | e1904547f3641eb8fa505dbf0cbd21fae6233a49 |
powersync-js | github_2023 | powersync-ja | typescript | SupabaseStorageAdapter.base64ToArrayBuffer | async base64ToArrayBuffer(base64: string): Promise<ArrayBuffer> {
return decodeBase64(base64);
} | /**
* Converts a base64 string to an ArrayBuffer
*/ | https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/demos/react-native-supabase-todolist/library/storage/SupabaseStorageAdapter.ts#L125-L127 | e1904547f3641eb8fa505dbf0cbd21fae6233a49 |
powersync-js | github_2023 | powersync-ja | typescript | App | const App: React.FC = () => {
const { supabaseConnector } = useSystem();
React.useEffect(() => {
Logger.useDefaults();
Logger.setLevel(Logger.DEBUG);
supabaseConnector.client.auth
.getSession()
.then(({ data }) => {
if (data.session) {
router.replace('views/todos/lists');
} else {
throw new Error('Signin required');
}
})
.catch(() => {
router.replace('signin');
});
}, []);
return (
<View key={`loader`} style={{ flex: 1, flexGrow: 1, alignContent: 'center', justifyContent: 'center' }}>
<ActivityIndicator />
</View>
);
}; | /**
* This is the entry point when the app loads.
* Checks for a Supabase session.
* - If one is present redirect to app views.
* - If not, reditect to login/register flow
*/ | https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/demos/react-native-web-supabase-todolist/app/index.tsx#L14-L39 | e1904547f3641eb8fa505dbf0cbd21fae6233a49 |
powersync-js | github_2023 | powersync-ja | typescript | EditLayout | const EditLayout = () => {
return <Stack />;
}; | /**
* Stack to edit a list from the todos view
*/ | https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/demos/react-native-web-supabase-todolist/app/views/todos/_layout.tsx#L6-L8 | e1904547f3641eb8fa505dbf0cbd21fae6233a49 |
powersync-js | github_2023 | powersync-ja | typescript | SupabaseStorageAdapter.base64ToArrayBuffer | async base64ToArrayBuffer(base64: string): Promise<ArrayBuffer> {
return decodeBase64(base64);
} | /**
* Converts a base64 string to an ArrayBuffer
*/ | https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/demos/react-native-web-supabase-todolist/library/storage/SupabaseStorageAdapter.ts#L122-L124 | e1904547f3641eb8fa505dbf0cbd21fae6233a49 |
powersync-js | github_2023 | powersync-ja | typescript | createSearchTermWithOptions | function createSearchTermWithOptions(searchTerm: string): string {
const searchTermWithOptions: string = `${searchTerm}*`;
return searchTermWithOptions;
} | /**
* adding * to the end of the search term will match any word that starts with the search term
* e.g. searching bl will match blue, black, etc.
* consult FTS5 Full-text Query Syntax documentation for more options
* @param searchTerm
* @returns a modified search term with options.
*/ | https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/demos/react-supabase-todolist/src/app/utils/fts_helpers.ts#L10-L13 | e1904547f3641eb8fa505dbf0cbd21fae6233a49 |
powersync-js | github_2023 | powersync-ja | typescript | createFtsTable | async function createFtsTable(tableName: string, columns: string[], tokenizationMethod = 'unicode61'): Promise<void> {
const internalName = (AppSchema.tables as Table[]).find((table) => table.name === tableName)?.internalName;
const stringColumns = columns.join(', ');
return await db.writeTransaction(async (tx) => {
// Add FTS table
await tx.execute(`
CREATE VIRTUAL TABLE IF NOT EXISTS fts_${tableName}
USING fts5(id UNINDEXED, ${stringColumns}, tokenize='${tokenizationMethod}');
`);
// Copy over records already in table
await tx.execute(`
INSERT OR REPLACE INTO fts_${tableName}(rowid, id, ${stringColumns})
SELECT rowid, id, ${generateJsonExtracts(ExtractType.columnOnly, 'data', columns)} FROM ${internalName};
`);
// Add INSERT, UPDATE and DELETE and triggers to keep fts table in sync with table
await tx.execute(`
CREATE TRIGGER IF NOT EXISTS fts_insert_trigger_${tableName} AFTER INSERT ON ${internalName}
BEGIN
INSERT INTO fts_${tableName}(rowid, id, ${stringColumns})
VALUES (
NEW.rowid,
NEW.id,
${generateJsonExtracts(ExtractType.columnOnly, 'NEW.data', columns)}
);
END;
`);
await tx.execute(`
CREATE TRIGGER IF NOT EXISTS fts_update_trigger_${tableName} AFTER UPDATE ON ${internalName} BEGIN
UPDATE fts_${tableName}
SET ${generateJsonExtracts(ExtractType.columnInOperation, 'NEW.data', columns)}
WHERE rowid = NEW.rowid;
END;
`);
await tx.execute(`
CREATE TRIGGER IF NOT EXISTS fts_delete_trigger_${tableName} AFTER DELETE ON ${internalName} BEGIN
DELETE FROM fts_${tableName} WHERE rowid = OLD.rowid;
END;
`);
});
} | /**
* Create a Full Text Search table for the given table and columns
* with an option to use a different tokenizer otherwise it defaults
* to unicode61. It also creates the triggers that keep the FTS table
* and the PowerSync table in sync.
* @param tableName
* @param columns
* @param tokenizationMethod
*/ | https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/demos/react-supabase-todolist/src/app/utils/fts_setup.ts#L15-L55 | e1904547f3641eb8fa505dbf0cbd21fae6233a49 |
powersync-js | github_2023 | powersync-ja | typescript | PowerSyncYjsProvider.destroy | destroy() {
this.abortController.abort();
this.doc.off('updateV2', this._storeUpdate);
this.doc.off('destroy', this.destroy);
} | /**
* Destroy this persistence provider, removing any attached event listeners.
*/ | https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/demos/yjs-react-supabase-text-collab/src/library/powersync/PowerSyncYjsProvider.ts#L93-L97 | e1904547f3641eb8fa505dbf0cbd21fae6233a49 |
powersync-js | github_2023 | powersync-ja | typescript | PowerSyncYjsProvider.deleteData | async deleteData() {
await this.db.execute('DELETE FROM document_updates WHERE document_id = ?', [this.documentId]);
} | /**
* Delete data associated with this document from the database.
*
* Also call `destroy()` to remove any event listeners and prevent future updates to the database.
*/ | https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/demos/yjs-react-supabase-text-collab/src/library/powersync/PowerSyncYjsProvider.ts#L104-L106 | e1904547f3641eb8fa505dbf0cbd21fae6233a49 |
powersync-js | github_2023 | powersync-ja | typescript | CrudEntry.toJSON | toJSON(): CrudEntryOutputJSON {
return {
op_id: this.clientId,
op: this.op,
type: this.table,
id: this.id,
tx_id: this.transactionId,
data: this.opData
};
} | /**
* Converts the change to JSON format.
*/ | https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/common/src/client/sync/bucket/CrudEntry.ts#L98-L107 | e1904547f3641eb8fa505dbf0cbd21fae6233a49 |
powersync-js | github_2023 | powersync-ja | typescript | CrudEntry.hashCode | hashCode() {
return JSON.stringify(this.toComparisonArray());
} | /**
* The hash code for this object.
* @deprecated This should not be necessary in the JS SDK.
* Use the @see CrudEntry#equals method instead.
* TODO remove in the next major release.
*/ | https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/common/src/client/sync/bucket/CrudEntry.ts#L119-L121 | e1904547f3641eb8fa505dbf0cbd21fae6233a49 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.