repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
directus-sync
github_2023
tractr
typescript
SeedDataClient.delete
async delete<T extends DirectusUnknownType>(key: DirectusId): Promise<void> { const directus = await this.migrationClient.get(); await directus.request<T>(deleteOne(this.collection, key)); }
/** * Delete an item from the collection */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/data-client.ts#L94-L97
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedDataDiffer.getDiff
async getDiff(data: WithSyncId<DirectusUnknownType>[]) { const toCreate: WithSyncId<DirectusUnknownType>[] = []; const toUpdate: { sourceItem: WithSyncId<DirectusUnknownType>; targetItem: WithSyncId<DirectusUnknownType>; diffItem: Partial<WithSyncId<DirectusUnknownType>>; }[] = []; con...
/** * Get the diff between source data and target data */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/data-differ.ts#L53-L86
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedDataDiffer.getTargetItem
protected async getTargetItem( sourceItem: WithSyncId<DirectusUnknownType>, ): Promise<WithSyncId<DirectusUnknownType> | undefined> { const idMap = await this.idMapper.getBySyncId(sourceItem._syncId); if (!idMap) { return undefined; } try { const [targetItem] = await this.dataClient.q...
/** * Get the target item from the idMapper then from the target table */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/data-differ.ts#L91-L137
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedDataDiffer.getDiffBetweenItems
protected async getDiffBetweenItems( sourceItem: WithSyncId<DirectusUnknownType>, targetItem: WithSyncId<DirectusUnknownType>, ) { const diffObject = diff(targetItem, sourceItem) as Partial< WithSyncId<DirectusUnknownType> >; const fieldsToIgnore = await this.getFieldsToIgnore(); for (c...
/** * Get the diff between two items and returns the source item with only the diff fields */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/data-differ.ts#L142-L166
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedDataDiffer.getDanglingIds
async getDanglingIds(): Promise<IdMap[]> { const allIdsMap = await this.idMapper.getAll(); const localIds = allIdsMap.map((item) => item.local_id); if (!localIds.length) { return []; } const primaryFieldName = await this.getPrimaryFieldName(); const existingItems = await this.dataClient....
/** * Get manually deleted items */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/data-differ.ts#L171-L191
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedDataDiffer.getIdsToDelete
protected async getIdsToDelete( unchanged: WithSyncId<DirectusUnknownType>[], toUpdate: { sourceItem: WithSyncId<DirectusUnknownType>; targetItem: WithSyncId<DirectusUnknownType>; }[], dangling: IdMap[], ): Promise<IdMap[]> { const allIdsMap = await this.idMapper.getAll(); const to...
/** * Get items that should be deleted */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/data-differ.ts#L196-L212
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedDataDiffer.getPrimaryKey
protected async getPrimaryKey( item: DirectusUnknownType, ): Promise<DirectusId> { const primaryFieldName = await this.getPrimaryFieldName(); return item[primaryFieldName] as DirectusId; }
/** * Get the primary key from an item */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/data-differ.ts#L217-L222
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedDataDiffer.getPrimaryFieldName
protected async getPrimaryFieldName(): Promise<string> { return (await this.schemaClient.getPrimaryField(this.collection)).name; }
/** * Get the primary field name from the collection */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/data-differ.ts#L227-L229
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedDataMapper.initialize
async initialize(): Promise<void> { if (this.initialized) { return; } const relationFields = await this.schemaClient.getRelationFields( this.collection, ); for (const field of relationFields) { const targetModel = await this.schemaClient.getTargetModel( this.collection, ...
/** * Initialize the id mappers by getting the relation fields from the snapshot * and creating a new SeedIdMapperClient for each relation */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/collections/data-mapper.ts#L34-L54
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SchemaClient.isDirectusCollection
protected isDirectusCollection( collection: string, ): collection is SupportedDirectusCollections { if (collection.startsWith(DIRECTUS_COLLECTIONS_PREFIX)) { if ( !SupportedDirectusCollections.includes( collection as SupportedDirectusCollections, ) ) { throw new E...
/** * Denotes if the collection is a directus collection. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/global/schema-client.ts#L90-L106
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SchemaClient.getDirectusCollectionRelationFields
protected getDirectusCollectionRelationFields( model: SupportedDirectusCollections, ): string[] { const structure = DirectusNativeStructure[model]; return structure.relations.map((r) => r.field); }
/** * Returns the list of fields of type "many-to-one" of a directus collection. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/global/schema-client.ts#L111-L116
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SchemaClient.getDirectusCollectionTargetModel
protected getDirectusCollectionTargetModel( model: SupportedDirectusCollections, field: string, ): string | undefined { const structure = DirectusNativeStructure[model]; return structure.relations.find((r) => r.field === field)?.collection; }
/** * Returns the target model of a directus collection. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/global/schema-client.ts#L121-L127
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SchemaClient.getDirectusCollectionPrimaryField
protected getDirectusCollectionPrimaryField( model: SupportedDirectusCollections, ): { name: string; type: Type; } { const structure = DirectusNativeStructure[model]; return structure.primaryField; }
/** * Returns the primary field type of a directus model. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/global/schema-client.ts#L132-L140
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedClient.hasSeeds
hasSeeds(): boolean { const seeds = this.seedLoader.loadFromFiles(); return seeds.length > 0; }
/** * Denotes if seeds exist */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/global/seed-client.ts#L24-L27
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedClient.diff
async diff(): Promise<void> { const seeds = this.seedLoader.loadFromFiles(); if (!seeds.length) { this.logger.warn('No seeds found'); } for (const seed of seeds) { await this.diffSeed(seed); } }
/** * Display diff for all seeds */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/global/seed-client.ts#L32-L40
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedClient.diffSeed
protected async diffSeed(seed: Seed): Promise<void> { const container = await this.createContainer(seed); const seedCollection = container.get(SeedCollection); await seedCollection.diff(seed.data); container.reset(); }
/** * Display diff for a seed */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/global/seed-client.ts#L45-L50
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedClient.push
async push(): Promise<boolean> { const seeds = this.seedLoader.loadFromFiles(); if (!seeds.length) { this.logger.warn('No seeds found'); return false; } let retry = false; for (const seed of seeds) { retry = (await this.pushSeed(seed)) || retry; } return retry; }
/** * Push all seeds */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/global/seed-client.ts#L55-L68
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedLoader.mergeSeeds
protected mergeSeeds(existing: Seed, seed: Seed): void { existing.data = [...existing.data, ...seed.data]; existing.meta.create = existing.meta.create && seed.meta.create; existing.meta.update = existing.meta.update && seed.meta.update; existing.meta.delete = existing.meta.delete && seed.meta.delete; ...
/** * Merge two seeds * - merge data with concat * - merge meta.create, meta.update, meta.delete with AND logic * - merge meta.preserve_ids with OR logic */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/global/seed-loader.ts#L84-L95
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedLoader.applyDirectusCollectionDefaults
protected applyDirectusCollectionDefaults(seed: Seed): void { if (this.isDirectusCollection(seed.collection)) { const structure = DirectusNativeStructure[seed.collection]; seed.meta.ignore_on_update = [ ...structure.ignoreOnUpdate, ...seed.meta.ignore_on_update, ]; } }
/** * Applies the defaults for directus collections. * - ignore_on_update: add the fields that are ignored on update in the Directus structure */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/global/seed-loader.ts#L101-L109
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SeedLoader.isDirectusCollection
protected isDirectusCollection( collection: string, ): collection is SupportedDirectusCollections { return SupportedDirectusCollections.includes( collection as SupportedDirectusCollections, ); }
/** * Denotes if the collection is a directus collection. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/seed/global/seed-loader.ts#L114-L120
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SnapshotClient.pull
async pull() { const snapshot = await this.getSnapshot(); const { onSave } = this.hooks; const transformedSnapshot = onSave ? await onSave(snapshot, await this.migrationClient.get()) : snapshot; const numberOfFiles = this.saveData(transformedSnapshot); this.logger.debug( `Saved ${n...
/** * Save the snapshot locally */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/snapshot/snapshot-client.ts#L54-L66
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SnapshotClient.push
async push() { const diff = await this.diffSnapshot(); if (!diff?.diff) { this.logger.debug('No changes to apply'); } else { const directus = await this.migrationClient.get(); await directus.request(schemaApply(diff as RawSchemaDiffOutput)); this.logger.info('Changes applied'); }...
/** * Apply the snapshot from the dump files. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/snapshot/snapshot-client.ts#L71-L80
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SnapshotClient.diff
async diff() { const diff = await this.diffSnapshot(); if (!diff?.diff) { this.logger.debug('No changes to apply'); } else { const { collections, fields, relations } = diff.diff; if (collections) { this.logger.info( `Found ${collections.length} change${ collec...
/** * Diff the snapshot from the dump file. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/snapshot/snapshot-client.ts#L85-L120
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SnapshotClient.saveData
protected saveData(data: Snapshot): number { // Clean directory removeSync(this.dumpPath); mkdirpSync(this.dumpPath); // Save data if (this.splitFiles) { const files = this.decomposeData(data); for (const file of files) { const filePath = path.join(this.dumpPath, file.path); ...
/** * Save the data to the dump file. The data is passed through the data transformer. * Returns the number of saved items. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/snapshot/snapshot-client.ts#L135-L154
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SnapshotClient.decomposeData
protected decomposeData( data: Snapshot, ): { path: string; content: unknown }[] { const { collections, fields, relations, ...info } = data; const files: { path: string; content: unknown }[] = [ { path: INFO_JSON, content: info }, ]; /* * Split collections * Folder and collection...
/** * Decompose the snapshot into a collection of files. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/snapshot/snapshot-client.ts#L159-L217
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SnapshotClient.getSuffix
protected getSuffix(baseName: string, existing: Set<string>): string { const base = baseName.toLowerCase(); // Some file systems are case-insensitive let suffix = ''; if (existing.has(base)) { let i = 2; while (existing.has(`${base}_${i}`)) { i++; } suffix = `_${i}`; } ...
/** * Get the suffix that should be added to the field name in order to avoid conflicts. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/snapshot/snapshot-client.ts#L222-L236
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SnapshotClient.diffSnapshot
protected async diffSnapshot(): Promise<SchemaDiffOutput | null | undefined> { const directus = await this.migrationClient.get(); const { onLoad } = this.hooks; const snapshot = this.loadData(); const transformedSnapshot = onLoad ? await onLoad(snapshot, await this.migrationClient.get()) : s...
/** * Get the diff from Directus instance * From Directus 11.4.1, the diff is not returned if there are no changes. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/snapshot/snapshot-client.ts#L242-L252
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SnapshotClient.loadData
protected loadData(): Snapshot { if (this.splitFiles) { const collections = loadJsonFilesRecursively<Collection>( path.join(this.dumpPath, COLLECTIONS_DIR), ); const fields = loadJsonFilesRecursively<Field>( path.join(this.dumpPath, FIELDS_DIR), ); const relations = loa...
/** * Load the snapshot from the dump file or the decomposed files. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/snapshot/snapshot-client.ts#L257-L277
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SpecificationsClient.pull
async pull() { if (!this.enabled) { return; } const itemGraphQL = await this.getGraphQL('item'); this.saveGraphQLData(itemGraphQL, ITEM_GRAPHQL_FILENAME); this.logger.debug(`Saved Item GraphQL schema to ${this.dumpPath}`); const systemGraphQL = await this.getGraphQL('system'); this.s...
/** * Save the snapshot locally */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/specifications/specifications-client.ts#L42-L58
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SpecificationsClient.getGraphQL
protected async getGraphQL(scope?: 'item' | 'system') { const directus = await this.migrationClient.get(); const response = await directus.request<Response>(readGraphqlSdl(scope)); return await response.text(); }
/** * Get GraphQL SDL from the server */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/specifications/specifications-client.ts#L63-L67
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SpecificationsClient.getOpenAPI
protected async getOpenAPI() { const directus = await this.migrationClient.get(); return await directus.request(readOpenApiSpec()); }
/** * Get OpenAPI specifications from the server */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/specifications/specifications-client.ts#L72-L75
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SpecificationsClient.saveGraphQLData
protected saveGraphQLData(data: string, filename: string): void { mkdirpSync(this.dumpPath); const filePath = path.join(this.dumpPath, filename); removeSync(filePath); writeFileSync(filePath, data); }
/** * Save the GraphQL data to the dump file. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/specifications/specifications-client.ts#L80-L85
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SpecificationsClient.saveOpenAPIData
protected saveOpenAPIData(data: OpenApiSpecOutput): void { mkdirpSync(this.dumpPath); const filePath = path.join(this.dumpPath, OPENAPI_FILENAME); removeSync(filePath); writeJsonSync(filePath, data, { spaces: 2 }); }
/** * Save the OpenAPI JSON data to the dump file. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/cli/src/lib/services/specifications/specifications-client.ts#L90-L95
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
expectCount
const expectCount = (collection: string) => { return collectionsToExclude.includes(collection) ? 0 : 1; };
// --------------------------------------------------------------------
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/e2e/spec/exclude-include/exclude-some-collections.ts#L48-L50
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
expectCount
const expectCount = (collection: SystemCollection) => { return excludedCollections.includes(collection) ? 0 : 1 + getDefaultItemsCount(collection); };
// --------------------------------------------------------------------
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/e2e/spec/exclude-include/include-some-collections.ts#L62-L66
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
SqliteClient.reset
async reset() { const baseTables = await getTables(this.baseDb); const testTables = await getTables(this.testDb); await truncateTables(this.testDb, testTables); await copyTables(this.baseDb, this.testDb, baseTables); }
/** * This method read all tables from the base database and copy them to the test database. * At the end the test database should be a clone of the base database. */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/e2e/spec/helpers/sdk/sqlite-client.ts#L32-L37
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
getTables
function getTables(db: sqlite3.Database) { return new Promise<string[]>((resolve, reject) => { db.all( `SELECT name FROM sqlite_master WHERE type='table'`, (error, rows: Row<{ name: string }>[]) => { if (error) { reject(error); } else { resolve(rows.map((row) => row...
/* * Helper functions */
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/e2e/spec/helpers/sdk/sqlite-client.ts#L44-L57
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
expectCount
const expectCount = (collection: string) => ['operations', 'panels', 'permissions', 'settings'].includes(collection) ? 0 : 1;
// Analyze the output
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/e2e/spec/pull-diff-push/pull-and-push-with-deletions.ts#L62-L65
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
roleAndSort
const roleAndSort = (role: string, sort: number) => (access: { role: string; sort: number }) => access.role === role && access.sort === sort;
// Helpers
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/e2e/spec/pull-diff-push/push-with-role-policy-assignment-changes.ts#L19-L22
20afa386e3c75e7eedfd6b629b323b8a34636e9f
directus-sync
github_2023
tractr
typescript
extractPolicyId
const extractPolicyId = (p: { policy: string }) => p.policy;
// Helpers
https://github.com/tractr/directus-sync/blob/20afa386e3c75e7eedfd6b629b323b8a34636e9f/packages/e2e/spec/pull-diff-push/push-with-user-policy-assignment.ts#L12-L12
20afa386e3c75e7eedfd6b629b323b8a34636e9f
pp-browser-extension
github_2023
cloudflare
typescript
onload
const onload = async () => { // Load current settings from sync storage const settings = await getRawSettings(STORAGE); // Every setting has a dedicated input which we need to set the default value, and onchange behaviour for (const name in settings) { const dropdown = document.getElementById(n...
// When the popup is loaded, load component that are stored in local/sync storage
https://github.com/cloudflare/pp-browser-extension/blob/2f0b6f50a673984f22a2f35ba1b8157a20eecdc8/src/options/index.ts#L6-L31
2f0b6f50a673984f22a2f35ba1b8157a20eecdc8
hot-updater
github_2023
gronxb
typescript
parseHotUpdaterContents
function parseHotUpdaterContents(content: string) { const markerRegex = /--\s*HotUpdater\.[^\n]*/g; const resultMap = new Map(); // Extract HotUpdater markers const markers = content.match(markerRegex); if (!markers) return resultMap; // Find blocks for each marker and store in Map for (const marker of ...
/** * Find markers in the format '-- HotUpdater.xxxx' from content and * extract SQL statements from each marker to the next marker into a Map * @param {string} content - SQL file content * @returns {Map<string, string>} - key is HotUpdater marker, value is the block */
https://github.com/gronxb/hot-updater/blob/51cde5b5110574df8ee59c609bedcd68417705a7/plugins/supabase/scripts/make-migrations.ts#L12-L32
51cde5b5110574df8ee59c609bedcd68417705a7
hot-updater
github_2023
gronxb
typescript
readHotUpdaterBlocksFromDir
async function readHotUpdaterBlocksFromDir(dirPath: string) { const files = (await fs.readdir(dirPath)).sort((a, b) => a.localeCompare(b)); const migrationMap = new Map(); for (const file of files) { if (!file.endsWith(".sql")) continue; const filePath = path.join(dirPath, file); const content = awa...
/** * Read all .sql files from a directory, extract HotUpdater blocks * and combine them into a single Map * @param {string} dirPath - Migration directory path * @returns {Promise<Map<string, string>>} - key: HotUpdater marker, value: block */
https://github.com/gronxb/hot-updater/blob/51cde5b5110574df8ee59c609bedcd68417705a7/plugins/supabase/scripts/make-migrations.ts#L40-L59
51cde5b5110574df8ee59c609bedcd68417705a7
hot-updater
github_2023
gronxb
typescript
readNewMigrations
async function readNewMigrations(dirPath: string) { const files = await fs.readdir(dirPath); const newMigrationMap = new Map(); // Select .sql files and extract HotUpdater blocks for (const file of files) { if (!file.endsWith(".sql")) continue; const filePath = path.join(dirPath, file); const cont...
/** * Extract HotUpdater blocks from new SQL files (@hot-updater/postgres/sql) into a Map * @param {string} dirPath - @hot-updater/postgres/sql directory path * @returns {Promise<Map<string, string>>} */
https://github.com/gronxb/hot-updater/blob/51cde5b5110574df8ee59c609bedcd68417705a7/plugins/supabase/scripts/make-migrations.ts#L66-L84
51cde5b5110574df8ee59c609bedcd68417705a7
hot-updater
github_2023
gronxb
typescript
main
async function main() { // @hot-updater/postgres/sql path const postgresPath = import.meta .resolve("@hot-updater/postgres/sql") .replace("file://", ""); // Create migrations directory (skip if exists) const migrationsDir = path.join(process.cwd(), "supabase/migrations"); await fs.mkdir(migrationsDir...
/** * Main function responsible for actual migration file creation */
https://github.com/gronxb/hot-updater/blob/51cde5b5110574df8ee59c609bedcd68417705a7/plugins/supabase/scripts/make-migrations.ts#L89-L134
51cde5b5110574df8ee59c609bedcd68417705a7
OneFolder
github_2023
OneFolderApp
typescript
ExifIO.readTags
async readTags(filepath: string): Promise<string[][]> { const metadata = await ep.readMetadata(filepath, [ 'HierarchicalSubject', 'Subject', 'Keywords', ...this.extraArgs, ]); if (metadata.error || !metadata.data?.[0]) { throw new Error(metadata.error || 'No metadata entry'); ...
// ------------------
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/common/ExifIO.ts#L119-L134
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
ExifIO.readFacesAnnotations
async readFacesAnnotations(filepath: string): Promise<MWGRegionInfo | undefined> { const metadata = await ep.readMetadata(filepath, [ 'struct', 'XMP:regionInfo', ...this.extraArgs, ]); if (metadata.error || !metadata.data?.[0]) { throw new Error(metadata.error || 'No metadata entry')...
/** * Reads the faces annotations from the specified file path. * @param filepath - The path of the file to read. * @returns A promise that resolves to the MWGRegionInfo object representing the faces annotations, or undefined if no annotations are found. * @throws An error if there is an error reading the m...
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/common/ExifIO.ts#L142-L156
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
ExifIO.getDimensions
async getDimensions(filepath: string): Promise<{ width: number; height: number }> { let metadata: Awaited<ReturnType<typeof ep.readMetadata>> | undefined = undefined; try { metadata = await ep.readMetadata(filepath, [ 's3', 'ImageWidth', 'ImageHeight', ...this.extraArgs, ...
/** * Extracts the width and height resolution of an image file from its exif data. * @param filepath The file to read the resolution from * @returns The width and height of the image, or width and height as 0 if the resolution could not be determined. */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/common/ExifIO.ts#L199-L218
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
ExifIO.convertMetadataToHierarchy
static convertMetadataToHierarchy(entry: exiftool.IMetadata, separator: string): string[][] { const parseExifFieldAsString = (val: any) => Array.isArray(val) ? val : val?.toString() ? [val.toString()] : []; const tagHierarchy = parseExifFieldAsString(entry.HierarchicalSubject); const subject = parseE...
/** Merges the HierarchicalSubject, Subject and Keywords into one list of tags, removing any duplicates */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/common/ExifIO.ts#L403-L426
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
ExifIO.extractThumbnail
async extractThumbnail(input: string, output: string): Promise<boolean> { // TODO: should be possible to pipe it immediately. Node-exiftool doesn't seem to allow that // const manualCommand = `"${input}" -PhotoshopThumbnail -b > "${output}"`; // console.log(manualCommand); // const res = await ep.readMe...
/** * Extracts the embedded thumbnail of a file into its own separate image file * @param input * @param output * @returns Whether the thumbnail could be extracted successfully */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/common/ExifIO.ts#L434-L460
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
runJob
function runJob(j: number) { collection[j]() .then((result) => { if (rejected) { return; // no op! } jobsLeft--; outcome[j] = result; progressCallback?.(1 - jobsLeft / collection.length); if (cancel?.()) { rejected = true; console....
// execute the j'th thunk
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/common/promise.ts#L46-L79
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
getPreviousWindowState
function getPreviousWindowState(): Electron.Rectangle & { isMaximized?: boolean } { const options: Electron.Rectangle & { isMaximized?: boolean } = { x: 0, y: 0, width: MIN_WINDOW_WIDTH, height: MIN_WINDOW_HEIGHT, }; try { const state = fse.readJSONSync(windowStateFilePath); state.x = Numb...
// Based on https://github.com/electron/electron/issues/526
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/main.ts#L708-L748
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
Backend.createFilesFromPath
async createFilesFromPath(path: string, files: FileDTO[]): Promise<void> { console.info('IndexedDB: Creating files...', path, files); await this.#db.transaction('rw', this.#files, async () => { const existingFilePaths = new Set( await this.#files.where('absolutePath').startsWith(path).keys(), ...
// Creates many files at once, and checks for duplicates in the path they are in
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/backend/backend.ts#L262-L275
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
filterWhere
function filterWhere<T>( where: WhereClause<T, string>, crit: ConditionDTO<T>, ): Collection<T, string> | ((val: T) => boolean) { switch (crit.valueType) { case 'array': return filterArrayWhere(where, crit); case 'string': return filterStringWhere(where, crit); case 'number': return ...
///////////////////////////////
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/backend/backend.ts#L351-L365
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
getToday
function getToday(): Date { const today = new Date(); today.setHours(0); today.setMinutes(0); today.setSeconds(0, 0); return today; }
/** Returns the date at 00:00 today */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/backend/backup-scheduler.ts#L11-L17
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
getWeekStart
function getWeekStart(): Date { const date = getToday(); const dayOfWeek = date.getDay(); date.setDate(date.getDate() - dayOfWeek); return date; }
/** Returns the date at the start of the current week (Sunday at 00:00) */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/backend/backup-scheduler.ts#L20-L25
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
ExternalLink
const ExternalLink = ({ url, children }: ExternalLinkProps) => { return ( <a href={url} title={url} rel="noreferrer" target="_blank" onClickCapture={(event) => { event.preventDefault(); shell.openExternal(url); }} > {children} </a> ); };
/** Opens link in default app. */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/components/ExternalLink.tsx#L10-L25
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
stopPropagation
const stopPropagation = (e: React.KeyboardEvent<HTMLTextAreaElement>) => e.stopPropagation();
// type ExifField = { label: string; modifiable?: boolean; format?: (val: string) => ReactNode };
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/components/ImageDescription.tsx#L19-L19
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
stopPropagation
const stopPropagation = (e: React.KeyboardEvent<HTMLTextAreaElement>) => e.stopPropagation();
// type ExifField = { label: string; modifiable?: boolean; format?: (val: string) => ReactNode };
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/components/ImageParameters.tsx#L19-L19
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
PopupWindow
const PopupWindow: React.FC<PopupWindowProps> = (props) => { const [containerEl] = useState(document.createElement('div')); const [win, setWin] = useState<Window>(); useEffect(() => { const externalWindow = window.open('', props.windowName); if (!externalWindow) { throw new Error('External window n...
/** * Creates a new external browser window, that renders whatever you pass as children */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/components/PopupWindow.tsx#L17-L64
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
handleToggleSelect
const handleToggleSelect = () => { // selectionCount === fileCount ? uiStore.clearFileSelection() : uiStore.selectAllFiles(); };
// If everything is selected, deselect all. Else, select all
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/containers/AppToolbar/PrimaryCommands.tsx#L96-L98
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
handleMouseMove
const handleMouseMove = (e: MouseEvent) => { if (!isDragging.current || header.current === null) { return; } const boundingRect = header.current.getBoundingClientRect(); onResize(boundingRect.width + (e.clientX - boundingRect.right)); };
// Do it for list reference
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/containers/ContentView/ListGallery.tsx#L269-L276
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
MasonryWorkerAdapter.getTransform
getTransform(index: number): ITransform { if (this.worker === undefined || this.memory === undefined) { throw new Error('Worker is uninitialized.'); } const ptr = this.worker.get_transform(index); return new Uint32Array(this.memory.buffer, ptr, 4) as unknown as ITransform; }
// This method will be available in the custom VirtualizedRenderer component as layout.getItemLayout
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/containers/ContentView/Masonry/MasonryWorkerAdapter.tsx#L92-L98
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
ZoomPan.handlePointerDown
handlePointerDown = (event: React.PointerEvent) => { // Only apply panning and pinching to left mouse button/touch or pen contact if (event.button !== 0) { return; } this.stopAnimation(); const pointers = this.activePointers; const id = event.pointerId; const pointer = { id, pos: crea...
//event handlers
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/containers/ContentView/SlideMode/ZoomPan.tsx
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
ZoomPan.pan
pan(position: Vec2): void { const relativePosition = getRelativePosition(position, this.container); if (this.lastPointerPosition === undefined) { //if we were pinching and lifted a finger this.lastPointerPosition = relativePosition; return; } const translateX = relativePosition[0] - th...
//actions
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/containers/ContentView/SlideMode/ZoomPan.tsx#L170-L191
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
ZoomPan.render
render() { return ( <div ref={this.containerRef} style={{ ...CONTAINER_DEFAULT_STYLE, touchAction: browserPanActions(this.state, this.props), }} > {this.props.children({ onPointerDown: this.handlePointerDown, onPointerMove: this.han...
//lifecycle methods
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/containers/ContentView/SlideMode/ZoomPan.tsx#L283-L303
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
getTransform
function getTransform(props: Readonly<ZoomPanProps>): Transform { const { position, initialScale, minScale, maxScale, imageDimension, containerDimension } = props; const scale = clamp( initialScale === 'auto' ? getAutofitScale(containerDimension, imageDimension) : initialScale, minScale, maxScale, );...
//// ANIMATION
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/containers/ContentView/SlideMode/ZoomPan.tsx#L343-L359
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
getCorrectedTransform
function getCorrectedTransform( props: Readonly<ZoomPanProps>, requestedTransform: Transform, tolerance: number, ): Transform | undefined { const { containerDimension, imageDimension, position, minScale, maxScale } = props; const scale = getConstrainedScale(requestedTransform.scale, minScale, maxScale, tolera...
// Returns constrained transform when requested transform is outside constraints with tolerance, otherwise returns null
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/containers/ContentView/SlideMode/ZoomPan.tsx#L362-L409
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
testImage
async function testImage(url: string, timeout: number = 2000): Promise<boolean> { try { const blob = await timeoutPromise(timeout, fetch(url)); return IMG_EXTENSIONS.some((ext) => blob.type.endsWith(ext)); } catch (e) { return false; } }
/** Tests whether a URL points to an image */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/containers/Outliner/LocationsPanel/dnd.ts#L102-L109
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
handleMove
const handleMove = async ( fileStore: FileStore, matches: ClientFile[], loc: ClientLocation, dir: string, ) => { let isReplaceAllActive = false; // If it's a file being dropped that's already in OneFolder, move it for (const file of matches) { const src = path.normalize(file.absolutePath); const ...
/** * Either moves or downloads a dropped file into the target directory * @param fileStore * @param matches * @param dir */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/containers/Outliner/LocationsPanel/useFileDnD.ts#L31-L101
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
sortTags
const sortTags = (tags: ClientTag[]) => { // First, sort children of each tag tags.forEach(tag => { if (tag.subTags && tag.subTags.length > 0) { sortTags(tag.subTags); } }); // Then sort the array in place tags.sort((a, b) => { const nameA = a.name.toLower...
// Recursive sorting function
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/containers/Outliner/TagsPanel/TagsTree.tsx#L550-L565
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
sort
const sort = (a: SubLocationDTO, b: SubLocationDTO) => a.name.localeCompare(b.name, undefined, { numeric: true });
/** Sorts alphanumerically, "natural" sort */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/entities/Location.ts#L16-L17
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
ClientLocation.drop
async drop(): Promise<void> { return this.worker?.close(); }
/** Cleanup resources */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/entities/Location.ts#L230-L232
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
getDirectoryTree
async function getDirectoryTree(path: string): Promise<IDirectoryTreeItem[]> { try { const NULL = { name: '', fullPath: '', children: [] }; const dirs = await Promise.all( Array.from(await fse.readdir(path), async (file) => { const fullPath = SysPath.join(path, file); if ((await fse.stat...
/** * Recursive function that returns the dir list for a given path */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/entities/Location.ts#L333-L355
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
ClientTagSearchCriteria.isSystemTag
@action.bound isSystemTag = (): boolean => { return !this.value && !this.operator.toLowerCase().includes('not'); }
/** * A flag for when the tag may be interpreted as a real tag, but contains text created by the application. * (this makes is so that "Untagged images" can be italicized) **/
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/entities/SearchCriteria.ts
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
ClientFileSearchItem.constructor
constructor(id: ID, name: string, criteria: SearchCriteria[], matchAny: boolean, index: number) { this.id = id; this.name = name; this.criteria = observable(criteria.map((c) => ClientFileSearchCriteria.deserialize(c))); this.matchAny = matchAny; this.index = index; makeObservable(this); }
// Then it wouldn't be a "Saved Search", but a "Saved view" maybe?
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/entities/SearchItem.ts#L21-L29
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
copyPresets
async function copyPresets(themeDir: string) { try { const presetDir = getExtraResourcePath('themes'); const files = await fse.readdir(presetDir); for (const file of files) { await fse.copy(`${presetDir}/${file}`, `${themeDir}/${file}`); } } catch (e) { console.error(e); } }
/** Copies preset themes from /resources/themes into the user's custom theme directory */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/hooks/useCustomTheme.tsx#L27-L37
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
useIsWindowMaximized
const useIsWindowMaximized = () => { const [isWindowMaximized, setIsWindowMaximized] = useState( window.outerWidth === screen.availWidth && window.outerHeight === screen.availHeight, ); useEffect(() => { const handleResize = () => { setIsWindowMaximized( window.outerWidth === screen.availWi...
/** Returns whether the window is maximized; when it takes up the available width and height of the screen */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/hooks/useIsWindowMaximized.ts#L4-L21
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
setValue
const setValue = (value: T | ((val: T) => T)) => { try { // Allow value to be a function so we have same API as useState const valueToStore = value instanceof Function ? value(storedValue) : value; // Save state setStoredValue(valueToStore); // Save to local storage if (typeof wi...
// Return a wrapped version of useState's setter function that ...
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/hooks/useLocalStorage.ts#L27-L41
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
useMutationObserver
function useMutationObserver( ref: MutableRefObject<HTMLElement | null>, callback: MutationCallback, options: MutationObserverInit = config, ): void { useEffect(() => { // Create an observer instance linked to the callback function if (ref.current) { const observer = new MutationObserver(callback)...
/** * * useMutationObserver hook, from https://github.com/imbhargav5/rooks/blob/main/src/hooks/useMutationObserver.ts * * Returns a mutation observer for a React Ref and fires a callback * * @param {MutableRefObject<HTMLElement | null>} ref React ref on which mutations are to be observed * @param {MutationCallba...
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/hooks/useMutationObserver.ts#L21-L40
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
ImageLoader.ensureThumbnail
async ensureThumbnail(file: ClientFile): Promise<boolean> { const { extension, absolutePath, thumbnailPath } = { extension: file.extension, absolutePath: file.absolutePath, // remove ?v=1 that might have been added after the thumbnail was generated earlier thumbnailPath: file.thumbnailPath.s...
/** * Ensures a thumbnail exists, will return instantly if already exists. * @param file The file to generate a thumbnail for * @returns Whether a thumbnail had to be generated * @throws When a thumbnail does not exist and cannot be generated */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/image/ImageLoader.ts#L98-L162
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
ImageLoader.getImageResolution
async getImageResolution(absolutePath: string): Promise<{ width: number; height: number }> { // ExifTool should be able to read the resolution from any image file const dimensions = await this.exifIO.getDimensions(absolutePath); // User report: Resolution can't be found for PSD files. // Can't reproduc...
/** Returns 0 for width and height if they can't be determined */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/image/ImageLoader.ts#L206-L225
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
TifLoader.decode
decode(buffer: ArrayBuffer): Promise<ImageData> { const ifds = UTIF.decode(buffer); const vsns = ifds[0].subIFD ? ifds.concat(ifds[0].subIFD as any) : ifds; let page = vsns[0]; let maxArea = 0; for (const img of vsns) { if ((img[BaselineTag.BitsPerSample] as number[]).length < 3) { co...
/** * Based on: https://github.com/photopea/UTIF.js/blob/master/UTIF.js#L1119 * @param buffer Image buffer (e.g. from fse.readFile) */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/image/TifLoader.ts#L20-L45
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
computeQuality
function computeQuality(canvas: HTMLCanvasElement, targetSize: number): number { const minSize = Math.min(canvas.width, canvas.height); // A low minimum size needs to correspond to a high quality, to retain details when it is displayed as cropped return clamp(1 - minSize / targetSize, 0.5, 0.9); }
/** Dynamically computes the compression quality for a thumbnail based on how much it is scaled compared to the maximum target size */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/image/util.ts#L71-L75
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
getScaledSize
function getScaledSize( width: number, height: number, targetSize: number, ): [width: number, height: number] { const widthScale = targetSize / width; const heightScale = targetSize / height; const scale = Math.min(widthScale, heightScale); return [Math.floor(width * scale), Math.floor(height * scale)]; }
/** Scales the width and height to be the targetSize in the largest dimension, while retaining the aspect ratio */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/image/util.ts#L78-L87
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
getAreaOfInterest
function getAreaOfInterest( width: number, height: number, ): [sx: number, sy: number, swidth: number, sheight: number] { const aspectRatio = width / height; let w = width; let h = height; if (aspectRatio > 3) { w = Math.floor(height * 3); } else if (aspectRatio < 1 / 3) { h = Math.floor(width * ...
/** Cut out rectangle in center if image has extreme aspect ratios. */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/image/util.ts#L90-L104
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
FileStore.refetchFileCounts
async refetchFileCounts(): Promise<void> { const [numTotalFiles, numUntaggedFiles] = await this.backend.countFiles(); runInAction(() => { this.numUntaggedFiles = numUntaggedFiles; this.numTotalFiles = numTotalFiles; }); }
/** Initializes the total and untagged file counters by querying the database with count operations */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/stores/FileStore.ts#L723-L729
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
areFilesIdenticalBesidesName
function areFilesIdenticalBesidesName(a: FileDTO, b: FileDTO): boolean { return ( a.ino === b.ino || (a.width === b.width && a.height === b.height && a.dateCreated.getTime() === b.dateCreated.getTime()) ); }
/** * Compares metadata of two files to determine whether the files are (likely to be) identical * Note: note comparing size, since it can change, e.g. when writing tags to file metadata. * Could still include it, but just to check whether it's in the same ballpark */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/stores/LocationStore.ts#L28-L35
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
deepEqual
const deepEqual = (a: any, b: any) => JSON.stringify(a) === JSON.stringify(b);
// TODO: can be improved
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/stores/UiStore.ts#L765-L765
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
FolderWatcherWorker.watch
async watch(directory: string, extensions: IMG_EXTENSIONS_TYPE[]) { this.isCancelled = false; // Replace backslash with forward slash, recommended by chokidar // See docs for the .watch method: https://github.com/paulmillr/chokidar#api directory = directory.replace(/\\/g, '/'); // Watch for files ...
/** Returns all supported image files in the given directly, and callbacks for new or removed files */
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/workers/folderWatcher.worker.ts#L27-L137
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
generateThumbnailData
const generateThumbnailData = async (filePath: string): Promise<ArrayBuffer | null> => { const inputBuffer = await fse.readFile(filePath); const inputBlob = new Blob([inputBuffer]); const img = await createImageBitmap(inputBlob); // Scale the image so that either width or height becomes `thumbnailMaxSize` le...
// TODO: Merge this with the generateThumbnail func from frontend/image/utils.ts, it's duplicate code
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/src/frontend/workers/thumbnailGenerator.worker.ts#L7-L45
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
setTabFocus
const setTabFocus = (element: HTMLElement, preventScroll = true) => { element.setAttribute('tabIndex', '0'); element.focus({ preventScroll }); // CHROME BUG: Option is ignored, probably fixed in Electron 9. };
// --- Helper function for tree items ---
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/widgets/tree.tsx#L6-L9
247e51d183bc5600ad131b20a4654015e6ecd3e2
OneFolder
github_2023
OneFolderApp
typescript
handleMousedown
const handleMousedown = (e: React.MouseEvent<HTMLElement>) => { if (!(e.target instanceof Element) || matches.length === 0) { return; } const row = e.target.closest('[role="row"][aria-rowindex]') as HTMLElement | null; if (row !== null) { // eslint-disable-next-line @typescript-eslint/no-non...
// Select option
https://github.com/OneFolderApp/OneFolder/blob/247e51d183bc5600ad131b20a4654015e6ecd3e2/widgets/combobox/GridCombobox.tsx#L216-L239
247e51d183bc5600ad131b20a4654015e6ecd3e2
dotlottie-web
github_2023
LottieFiles
typescript
DotLottie.getLayerBoundingBox
public getLayerBoundingBox(layerName: string): | { height: number; width: number; x: number; y: number; } | undefined { const bounds = this._dotLottieCore?.getLayerBounds(layerName); if (!bounds) return undefined; if (bounds.size() !== 4) return undefined; ...
/** * Get the bounds of a layer by its name * @param layerName - The name of the layer * @returns The bounds of the layer * * @example * ```typescript * // Draw a rectangle around the layer 'Layer 1' * dotLottie.addEventListener('render', () => { * const boundingBox = dotLottie.getLayerBoun...
https://github.com/LottieFiles/dotlottie-web/blob/c05e0751b1ada77cb6643fc2883d244aa2474ecd/packages/web/src/dotlottie.ts#L1043-L1068
c05e0751b1ada77cb6643fc2883d244aa2474ecd
dotlottie-web
github_2023
LottieFiles
typescript
DotLottieWasmLoader._loadWithBackup
private static async _loadWithBackup(): Promise<MainModule> { if (!this._ModulePromise) { this._ModulePromise = this._tryLoad(this._wasmURL).catch(async (initialError): Promise<MainModule> => { const backupUrl = `https://unpkg.com/${PACKAGE_NAME}@${PACKAGE_VERSION}/dist/dotlottie-player.wasm`; ...
/** * Tries to load the WASM module from the primary URL, falling back to a backup URL if necessary. * Throws an error if both URLs fail to load the module. * @returns Promise<Module> - A promise that resolves to the loaded module. */
https://github.com/LottieFiles/dotlottie-web/blob/c05e0751b1ada77cb6643fc2883d244aa2474ecd/packages/web/src/core/dotlottie-wasm-loader.ts#L29-L48
c05e0751b1ada77cb6643fc2883d244aa2474ecd
dotlottie-web
github_2023
LottieFiles
typescript
DotLottieWasmLoader.load
public static async load(): Promise<MainModule> { return this._loadWithBackup(); }
/** * Public method to load the WebAssembly module. * Utilizes a primary and backup URL for robustness. * @returns Promise<Module> - A promise that resolves to the loaded module. */
https://github.com/LottieFiles/dotlottie-web/blob/c05e0751b1ada77cb6643fc2883d244aa2474ecd/packages/web/src/core/dotlottie-wasm-loader.ts#L55-L57
c05e0751b1ada77cb6643fc2883d244aa2474ecd
dotlottie-web
github_2023
LottieFiles
typescript
DotLottieWasmLoader.setWasmUrl
public static setWasmUrl(url: string): void { if (url === this._wasmURL) return; this._wasmURL = url; // Invalidate current module promise this._ModulePromise = null; }
/** * Sets a new URL for the WASM file and invalidates the current module promise. * * @param string - The new URL for the WASM file. */
https://github.com/LottieFiles/dotlottie-web/blob/c05e0751b1ada77cb6643fc2883d244aa2474ecd/packages/web/src/core/dotlottie-wasm-loader.ts#L64-L70
c05e0751b1ada77cb6643fc2883d244aa2474ecd
homebridge-appletv-enhanced
github_2023
maxileith
typescript
UpdateChecker.update
private async update(version: string): Promise<void> { this.log.info(`Attempting to update AppleTV Enhanced to version ${version}`); if (UIX_CUSTOM_PLUGIN_PATH === undefined) { this.log.error('Could not determine the path where to install the plugin since the environment variable UIX_CUSTOM...
// https://github.com/homebridge/homebridge-config-ui-x/blob/01a008227b8b8f3650b23eaac3e9370347cec4f8/src/modules/plugins/plugins.service.ts#L384-L493
https://github.com/maxileith/homebridge-appletv-enhanced/blob/94633e9bd19b47d6fb9cdc419d5465e7c6382a0a/src/UpdateChecker.ts#L251-L295
94633e9bd19b47d6fb9cdc419d5465e7c6382a0a
homebridge-appletv-enhanced
github_2023
maxileith
typescript
AppleTVEnhancedAccessory.appIdentifiersOrderToTLV8
private appIdentifiersOrderToTLV8(listOfIdentifiers: number[]): string { let identifiersTLV: Buffer = Buffer.alloc(0); listOfIdentifiers.forEach((identifier: number, index: number) => { if (index !== 0) { identifiersTLV = Buffer.concat([ identifiersTLV, ...
// https://github.com/homebridge/HAP-NodeJS/issues/644#issue-409099368
https://github.com/maxileith/homebridge-appletv-enhanced/blob/94633e9bd19b47d6fb9cdc419d5465e7c6382a0a/src/appleTVEnhancedAccessory.ts#L200-L218
94633e9bd19b47d6fb9cdc419d5465e7c6382a0a
homebridge-appletv-enhanced
github_2023
maxileith
typescript
AppleTVEnhancedPlatform.configureAccessory
public configureAccessory(_accessory: PlatformAccessory): void {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-function
https://github.com/maxileith/homebridge-appletv-enhanced/blob/94633e9bd19b47d6fb9cdc419d5465e7c6382a0a/src/appleTVEnhancedPlatform.ts#L98-L98
94633e9bd19b47d6fb9cdc419d5465e7c6382a0a