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>>;
}[] = [];
const unchanged: WithSyncId<DirectusUnknownType>[] = [];
for (const sourceItem of data) {
const targetItem = await this.getTargetItem(sourceItem);
if (targetItem) {
const { hasDiff, diffObject } = await this.getDiffBetweenItems(
sourceItem,
targetItem,
);
if (hasDiff) {
toUpdate.push({ sourceItem, targetItem, diffItem: diffObject });
} else {
unchanged.push(targetItem);
}
} else {
toCreate.push(sourceItem);
}
}
// Get manually deleted ids
const dangling = await this.getDanglingIds();
// Get items to delete
const toDelete = await this.getIdsToDelete(unchanged, toUpdate, dangling);
return { toCreate, toUpdate, toDelete, unchanged, dangling };
} | /**
* 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.queryByPrimaryField(
idMap.local_id,
);
if (!targetItem) {
return undefined;
}
// Remove all fields that are not in the source item
const targetItemWithoutFields = Object.keys(sourceItem).reduce(
(acc, field) => {
acc[field] = targetItem[field];
return acc;
},
{} as DirectusUnknownType,
);
const withSyncId = {
...targetItemWithoutFields,
_syncId: sourceItem._syncId,
};
const [withMappedIds] =
await this.dataMapper.mapIdsToSyncIdAndRemoveIgnoredFields([
withSyncId,
]);
const primaryFieldName = await this.getPrimaryFieldName();
return {
...withMappedIds,
[primaryFieldName]: idMap.local_id,
} as WithSyncId<DirectusUnknownType>;
} catch (error) {
this.logger.warn(
{ error, idMap },
`Could not find item with id ${idMap.local_id}`,
);
return undefined;
}
} | /**
* 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 (const field of fieldsToIgnore) {
delete diffObject[field];
}
const diffFields = Object.keys(diffObject);
const sourceDiffObject = {} as Partial<WithSyncId<DirectusUnknownType>>;
for (const field of diffFields) {
sourceDiffObject[field] = sourceItem[field];
}
return {
diffObject: sourceDiffObject,
hasDiff: diffFields.length > 0,
};
} | /**
* 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.queryByPrimaryField(localIds, {
limit: -1,
fields: [primaryFieldName],
});
const existingIds = new Set<DirectusId>();
for (const item of existingItems) {
const primaryKey = await this.getPrimaryKey(item);
existingIds.add(primaryKey.toString());
}
return allIdsMap.filter((item) => !existingIds.has(item.local_id));
} | /**
* 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 toKeepIds = new Set([
...unchanged.map((item) => item._syncId),
...toUpdate.map(({ targetItem }) => targetItem._syncId),
...dangling.map((item) => item.sync_id),
]);
return allIdsMap.filter((item) => !toKeepIds.has(item.sync_id));
} | /**
* 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,
field,
);
this.idMappers[field] =
this.idMapperClientFactory.forCollection(targetModel);
}
this.initialized = true;
} | /**
* 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 Error(
`Unsupported Directus collection by seed command: ${collection}. Supported collections are: ${SupportedDirectusCollections.join(', ')}`,
);
}
return true;
}
return false;
} | /**
* 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;
existing.meta.preserve_ids =
existing.meta.preserve_ids || seed.meta.preserve_ids;
existing.meta.ignore_on_update = [
...existing.meta.ignore_on_update,
...seed.meta.ignore_on_update,
];
} | /**
* 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 ${numberOfFiles} file${numberOfFiles > 1 ? 's' : ''} to ${
this.dumpPath
}`,
);
} | /**
* 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${
collections.length > 1 ? 's' : ''
} in collections`,
);
} else {
this.logger.info('No changes in collections');
}
if (fields) {
this.logger.info(
`Found ${fields.length} change${
fields.length > 1 ? 's' : ''
} in fields`,
);
} else {
this.logger.info('No changes in fields');
}
if (relations) {
this.logger.info(
`Found ${relations.length} change${
relations.length > 1 ? 's' : ''
} in relations`,
);
} else {
this.logger.info('No changes in relations');
}
this.logger.debug(diff, 'Diff');
}
} | /**
* 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);
const dirPath = path.dirname(filePath);
mkdirpSync(dirPath);
writeJsonSync(filePath, file.content, { spaces: 2 });
}
return files.length;
} else {
const filePath = path.join(this.dumpPath, SNAPSHOT_JSON);
writeJsonSync(filePath, data, { spaces: 2 });
return 1;
}
} | /**
* 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 collections may have the same name (with different casing).
* Also, some file systems are case-insensitive.
*/
const existingCollections = new Set<string>();
for (const collection of collections) {
const suffix = this.getSuffix(collection.collection, existingCollections);
files.push({
path: `${COLLECTIONS_DIR}/${collection.collection}${suffix}.json`,
content: collection,
});
}
/*
* Split fields
* Groups and fields may have the same name (with different casing).
* Also, some file systems are case-insensitive.
* Therefore, inside a collection we have to deal with names conflicts.
*/
const existingFiles = new Set<string>();
for (const field of fields) {
const suffix = this.getSuffix(
`${field.collection}/${field.field}`,
existingFiles,
);
files.push({
path: `${FIELDS_DIR}/${field.collection}/${field.field}${suffix}.json`,
content: field,
});
}
/*
* Split relations
* There should not be any conflicts here, but we still split them for consistency.
*/
const existingRelations = new Set<string>();
for (const relation of relations) {
const suffix = this.getSuffix(
`${relation.collection}/${relation.field}`,
existingRelations,
);
files.push({
path: `${RELATIONS_DIR}/${relation.collection}/${relation.field}${suffix}.json`,
content: relation,
});
}
return files;
} | /**
* 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}`;
}
existing.add(`${base}${suffix}`);
return suffix;
} | /**
* 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())
: snapshot;
return (await directus.request(
schemaDiff(transformedSnapshot, this.force),
)) as SchemaDiffOutput | undefined;
} | /**
* 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 = loadJsonFilesRecursively<Relation>(
path.join(this.dumpPath, RELATIONS_DIR),
);
const info = readJsonSync(path.join(this.dumpPath, INFO_JSON)) as Omit<
Snapshot,
'collections' | 'fields' | 'relations'
>;
return { ...info, collections, fields, relations };
} else {
const filePath = path.join(this.dumpPath, SNAPSHOT_JSON);
return readJsonSync(filePath, 'utf-8') as Snapshot;
}
} | /**
* 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.saveGraphQLData(systemGraphQL, SYSTEM_GRAPHQL_FILENAME);
this.logger.debug(`Saved System GraphQL schema to ${this.dumpPath}`);
const openapi = await this.getOpenAPI();
this.saveOpenAPIData(openapi);
this.logger.debug(`Saved OpenAPI specification to ${this.dumpPath}`);
} | /**
* 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.name));
}
},
);
});
} | /*
* 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(name) as HTMLInputElement;
dropdown.value = settings[name];
dropdown.addEventListener('change', (event) => {
const target = event.target as HTMLInputElement;
if (!Object.values(SETTING_NAMES).includes(target.id as SettingsKeys)) {
return;
}
saveSettings(STORAGE, target.id as SettingsKeys, target.value.trim());
});
}
// Links won't open correctly within an extension popup. The following overwrite the default behaviour to open a new tab
for (const a of [...document.getElementsByTagName('a')]) {
a.addEventListener('click', (event) => {
event.preventDefault();
chrome.tabs.create({ url: a.href });
});
}
}; | // 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 markers) {
const key = marker.trim();
// Regex: Extract statement from marker(key) to next HotUpdater marker
const blockRegex = new RegExp(`${key}[\\s\\S]*?(?=--\\s*HotUpdater\\.|$)`);
const matchBlock = content.match(blockRegex);
if (matchBlock) {
resultMap.set(key, matchBlock[0].trim());
}
}
return resultMap;
} | /**
* 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 = await fs.readFile(filePath, "utf-8");
// Extract HotUpdater blocks from file content
const parsedBlocks = parseHotUpdaterContents(content);
// Store all extracted blocks in Map
for (const [key, block] of parsedBlocks.entries()) {
migrationMap.set(key, block);
}
}
return migrationMap;
} | /**
* 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 content = await fs.readFile(filePath, "utf-8");
const parsedBlocks = parseHotUpdaterContents(content);
for (const [key, block] of parsedBlocks.entries()) {
newMigrationMap.set(key, block);
}
}
return newMigrationMap;
} | /**
* 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, { recursive: true });
// Extract all HotUpdater blocks from existing migration .sql files
const existingMigrations = await readHotUpdaterBlocksFromDir(migrationsDir);
console.log(
pc.blue("Existing migration contents:"),
Array.from(existingMigrations.keys()),
);
// Extract all HotUpdater blocks from new SQL files
const newMigrations = await readNewMigrations(postgresPath);
console.log(
pc.blue("New migration contents:"),
Array.from(newMigrations.keys()),
);
// Collect blocks that differ from existing ones
const changedBlocks: string[] = [];
for (const [key, block] of newMigrations.entries()) {
const existingBlock = existingMigrations.get(key);
if (existingBlock !== block) {
changedBlocks.push(block);
}
}
// Create new migration file if there are changed blocks
if (changedBlocks.length > 0) {
const combinedSql = changedBlocks.join("\n\n");
const newFileName = `${dayjs().format("YYYYMMDDHHmmss")}.sql`;
await fs.writeFile(path.join(migrationsDir, newFileName), combinedSql);
console.log(pc.green("New migration file created:"), pc.bold(newFileName));
} else {
console.log(
pc.yellow("No changes detected. No new migration file created."),
);
}
} | /**
* 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');
}
const entry = metadata.data[0];
return ExifIO.convertMetadataToHierarchy(
entry,
runInAction(() => this.hierarchicalSeparator),
);
} | // ------------------ | 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');
}
const entry = metadata.data[0];
if (!entry.RegionInfo) {
return undefined;
}
return entry.RegionInfo;
} | /**
* 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 metadata or if no metadata entry is found.
*/ | 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,
]);
if (metadata.error || !metadata.data?.[0]) {
throw new Error(metadata.error || 'No metadata entry');
}
const entry = metadata.data[0];
const { ImageWidth, ImageHeight } = entry;
return { width: ImageWidth, height: ImageHeight };
} catch (e) {
console.error('Could not read image dimensions from ', filepath, e, metadata);
return { width: 0, height: 0 };
}
} | /**
* 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 = parseExifFieldAsString(entry.Subject);
const keywords = parseExifFieldAsString(entry.Keywords);
// these toString() methods are here because they are automatically parsed to numbers if they could be numbers :/
const splitHierarchy = tagHierarchy.map((h) => h.toString().split(separator));
const allPlainTags = Array.from(
new Set([...subject.map((s) => s.toString()), ...keywords.map((s) => s.toString())]),
);
// Filter out duplicates of tagHierarchy and the other plain tags:
const filteredTags = allPlainTags.filter((tag) =>
splitHierarchy.every((h) => h[h.length - 1] !== tag),
);
if (tagHierarchy.length + filteredTags.length > 0) {
console.debug('Parsed tags', { tagHierarchy, subject, keywords });
}
return [...splitHierarchy, ...filteredTags.map((t) => [t])];
} | /** 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.readMetadata(manualCommand);
// console.log(res);
// TODO: can also extract preview from RAW https://exiftool.org/forum/index.php?topic=7408.0
if (!this.isOpen()) {
return false;
}
const res = await ep.readMetadata(input, ['ThumbnailImage', 'PhotoshopThumbnail', 'b']);
let data = res.data?.[0]?.ThumbnailImage || res.data?.[0]?.PhotoshopThumbnail;
if (data) {
if (data.startsWith?.('base64')) {
data = data.replace('base64:', '');
await fse.writeFile(output, Buffer.from(data, 'base64'));
} else {
await fse.writeFile(output, data);
}
return true;
}
return false;
} | /**
* 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.log('CANCELLING!');
return;
}
if (jobsLeft <= 0) {
resolve(outcome);
} else if (i < collection.length) {
runJob(i);
i++;
} else {
return; // nothing to do here.
}
})
.catch((e) => {
if (rejected) {
return; // no op!
}
rejected = true;
reject(e);
return;
});
} | // 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 = Number(state.x);
state.y = Number(state.y);
state.width = Number(state.width);
state.height = Number(state.height);
state.isMaximized = Boolean(state.isMaximized);
const area = screen.getDisplayMatching(state).workArea;
// If the saved position still valid (the window is entirely inside the display area), use it.
if (
state.x >= area.x &&
state.y >= area.y &&
state.x + state.width <= area.x + area.width &&
state.y + state.height <= area.y + area.height
) {
options.x = state.x;
options.y = state.y;
}
// If the saved size is still valid, use it.
if (state.width <= area.width || state.height <= area.height) {
options.width = state.width;
options.height = state.height;
}
options.isMaximized = state.isMaximized;
} catch (e) {
console.error('Could not read window state file!', e);
// Fallback to primary display screen size
const { width, height } = screen.getPrimaryDisplay().workAreaSize;
options.width = width;
options.height = height;
}
return options;
} | // 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(),
);
console.debug('Filtering files...');
retainArray(files, (file) => !existingFilePaths.has(file.absolutePath));
console.debug('Creating files...');
this.#files.bulkAdd(files);
});
console.debug('Done!');
this.#notifyChange();
} | // 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 filterNumberWhere(where, crit);
case 'date':
return filterDateWhere(where, crit);
}
} | /////////////////////////////// | 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 not supported!');
}
setWin(externalWindow);
externalWindow.document.body.appendChild(containerEl);
// Copy style sheets from main window
copyStyles(document, externalWindow.document);
containerEl.setAttribute('data-os', PLATFORM);
// Hacky func for re-applying CSS to settings when changing that of the main window
(window as any).reapplyPopupStyles = () => {
copyStyles(document, externalWindow.document);
};
externalWindow.addEventListener('beforeunload', props.onClose);
if (props.closeOnEscape) {
externalWindow.addEventListener('keydown', (e) => {
if (e.key === 'Escape' || e.key === props.additionalCloseKey) {
props.onClose();
}
});
}
return function cleanup() {
externalWindow.close();
setWin(undefined);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
if (win) {
return ReactDOM.createPortal(
<>
{props.children}
<Overlay document={win.document} />
</>,
containerEl,
);
} | /**
* 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: createVec2(event.clientX, event.clientY) };
const index = pointers.findIndex((p) => p.id === id);
if (index > -1) {
pointers[index] = pointer;
} else {
pointers.push(pointer);
}
if (pointers.length === 2) {
this.lastPinchLength = getPinchLength(pointers[0].pos, pointers[1].pos);
this.lastPointerPosition = undefined;
} else if (pointers.length === 1) {
this.lastPinchLength = 0;
this.lastPointerPosition = getRelativePosition(pointers[0].pos, this.container);
if (event.pointerType === 'touch') {
tryPreventDefault(event); //suppress mouse events
}
}
} | //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] - this.lastPointerPosition[0];
const translateY = relativePosition[1] - this.lastPointerPosition[1];
this.lastPointerPosition = relativePosition;
this.setState((state, props) => {
const top = state.top + translateY;
const left = state.left + translateX;
const transform = createTransform(top, left, state.scale);
if (props.transitionEnd !== undefined) {
return transform;
} else {
return getCorrectedTransform(props, transform, 0) ?? transform;
}
});
} | //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.handlePointerMove,
onPointerUp: this.handlePointerUp,
onWheel: this.handleMouseWheel,
onDragStart: tryPreventDefault,
onContextMenu: tryPreventDefault,
style: imageStyle(this.state, this.props.upscaleMode),
})}
</div>
);
} | //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,
);
if (position === 'center') {
const top = (containerDimension[1] - imageDimension[1] * scale) / 2;
const left = (containerDimension[0] - imageDimension[0] * scale) / 2;
return createTransform(top, left, scale);
} else {
return createTransform(0, 0, scale);
}
} | //// 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, tolerance);
//get dimensions by which scaled image overflows container
const negativeSpaceWidth = containerDimension[0] - scale * imageDimension[0];
const negativeSpaceHeight = containerDimension[1] - scale * imageDimension[1];
const overflowWidth = Math.max(0, -negativeSpaceWidth);
const overflowHeight = Math.max(0, -negativeSpaceHeight);
//if image overflows container, prevent moving by more than the overflow
//example: overflow[1] = 100, tolerance = 0.05 => top is constrained between -105 and +5
const upperBoundFactor = 1.0 + tolerance;
const top =
overflowHeight > 0
? clamp(
requestedTransform.top,
-overflowHeight * upperBoundFactor,
overflowHeight * upperBoundFactor - overflowHeight,
)
: position === 'center'
? (containerDimension[1] - imageDimension[1] * scale) / 2
: 0;
const left =
overflowWidth > 0
? clamp(
requestedTransform.left,
-overflowWidth * upperBoundFactor,
overflowWidth * upperBoundFactor - overflowWidth,
)
: position === 'center'
? (containerDimension[0] - imageDimension[0] * scale) / 2
: 0;
const constrainedTransform = createTransform(top, left, scale);
if (isEqualTransform(constrainedTransform, requestedTransform)) {
return undefined;
} else {
return constrainedTransform;
}
} | // 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 dst = path.normalize(path.join(dir, file.name));
if (src !== dst) {
const alreadyExists = await fse.pathExists(dst);
if (alreadyExists && !isReplaceAllActive) {
const srcStats = await fse.stat(src);
const dstStats = await fse.stat(dst);
// if the file is already in the target location, prompt the user to confirm the move
// TODO: could also add option to rename with a number suffix?
const res = await RendererMessenger.showMessageBox({
type: 'question',
title: 'Replace or skip file?',
message: `"${file.name}" already exists in this folder. Replace or skip?`,
detail: `From "${path.dirname(file.absolutePath)}" (${humanFileSize(
srcStats.size,
)}) \nTo "${dir}" (${humanFileSize(
dstStats.size,
)})\nNote: The tags on the replaced image will be lost.`,
buttons: ['&Replace', '&Skip', '&Cancel'],
normalizeAccessKeys: true,
defaultId: 0,
cancelId: 2,
checkboxLabel: matches.length > 1 ? 'Apply to all' : undefined,
});
if (res.response === 0 && res.checkboxChecked) {
isReplaceAllActive = true; // replace all
} else if ((res.response === 1 && res.checkboxChecked) || res.response === 2) {
break; // skip all
} else if (res.response === 1) {
continue; // skip this file
}
}
// When replacing an existing file, no change is detected when moving the file
// The target file needs to be removed from disk and the DB first
if (alreadyExists) {
// - Remove the target file from disk
await fse.remove(dst);
// - Remove the target file from the store
// TODO: This removes the target file and its tags. Could merge them, but that's a bit more work
const dstFile = fileStore.fileList.find((f) => f.absolutePath === dst);
if (dstFile) {
await fileStore.deleteFiles([dstFile]);
}
// - Move the source file to the target path
// Now the DB and internal state have been prepared to be able to detect the moving of the file
// Will be done with the move operation below
// We need to wait a second for the UI to update, otherwise it will cause render issues for some reason (old and new are rendered simultaneously)
await new Promise((res) => setTimeout(res, 1000));
} else {
// Else, the file watcher process will detect the changes and update the File entity accordingly
}
await fse.move(src, dst, { overwrite: true });
}
}
}; | /**
* 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.toLowerCase();
const nameB = b.name.toLowerCase();
if (nameA < nameB) return direction === 'asc' ? -1 : 1;
if (nameA > nameB) return direction === 'asc' ? 1 : -1;
return 0;
});
}; | // 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(fullPath)).isDirectory()) {
return {
name: SysPath.basename(fullPath),
fullPath,
children: await getDirectoryTree(fullPath),
};
} else {
return NULL;
}
}),
);
retainArray(dirs, (dir) => dir !== NULL);
return dirs;
} catch (e) {
return [];
}
} | /**
* 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.availWidth && window.outerHeight === screen.availHeight,
);
};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return isWindowMaximized;
}; | /** 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 window !== 'undefined') {
window.localStorage.setItem(key, JSON.stringify(valueToStore));
}
} catch (error) {
// A more advanced implementation would handle the error case
console.log(error);
}
}; | // 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);
// Start observing the target node for configured mutations
observer.observe(ref.current, options);
return () => {
observer.disconnect();
};
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [callback, options]);
} | /**
*
* 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 {MutationCallback} callback Function that needs to be fired on mutation
* @param {MutationObserverInit} options
*/ | 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.split('?v=1')[0],
};
if (await fse.pathExists(thumbnailPath)) {
// Files like PSDs have a tendency to change: Check if thumbnail needs an update
const fileStats = await fse.stat(absolutePath);
const thumbStats = await fse.stat(thumbnailPath);
if (fileStats.mtime < thumbStats.ctime) {
return false; // if file mod date is before thumbnail creation date, keep using the same thumbnail
}
}
const handlerType = FormatHandlers[extension];
switch (handlerType) {
case 'web':
await generateThumbnailUsingWorker(file, thumbnailPath);
updateThumbnailPath(file, thumbnailPath);
break;
case 'tifLoader':
await generateThumbnail(this.tifLoader, absolutePath, thumbnailPath, thumbnailMaxSize);
updateThumbnailPath(file, thumbnailPath);
break;
case 'exrLoader':
await generateThumbnail(this.exrLoader, absolutePath, thumbnailPath, thumbnailMaxSize);
updateThumbnailPath(file, thumbnailPath);
break;
case 'extractEmbeddedThumbnailOnly':
let success = false;
// Custom logic for specific file formats
if (extension === 'kra') {
success = await this.extractKritaThumbnail(absolutePath, thumbnailPath);
} else {
// Fallback to extracting thumbnail using exiftool (works for PSD and some other formats)
success = await this.exifIO.extractThumbnail(absolutePath, thumbnailPath);
}
if (!success) {
// There might not be an embedded thumbnail
throw new Error('Could not generate or extract thumbnail');
} else {
updateThumbnailPath(file, thumbnailPath);
}
break;
case 'psdLoader':
await generateThumbnail(this.psdLoader, absolutePath, thumbnailPath, thumbnailMaxSize);
updateThumbnailPath(file, thumbnailPath);
break;
case 'heicLoader':
await generateThumbnail(this.heicLoader, absolutePath, thumbnailPath, thumbnailMaxSize);
updateThumbnailPath(file, thumbnailPath);
break;
case 'none':
// No thumbnail for this format
file.setThumbnailPath(file.absolutePath);
break;
default:
console.warn('Unsupported extension', file.absolutePath, file.extension);
throw new Error('Unsupported extension ' + file.absolutePath);
}
return true;
} | /**
* 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 reproduce myself, but putting a check in place anyway. Maybe due to old PSD format?
// Read the actual file using the PSD loader and get the resolution from there.
if (
absolutePath.toLowerCase().endsWith('psd') &&
(dimensions.width === 0 || dimensions.height === 0)
) {
try {
const psdData = await this.psdLoader.decode(await fse.readFile(absolutePath));
dimensions.width = psdData.width;
dimensions.height = psdData.height;
} catch (e) {}
}
return dimensions;
} | /** 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) {
continue;
}
// Actually the width and height is a an array with one element but pointer magic returns the
// correct value anyways.
const area = (img[BaselineTag.Width] as number) * (img[BaselineTag.Height] as number);
// Find the highest resolution entry
if (area > maxArea) {
maxArea = area;
page = img;
}
}
(UTIF.decodeImage as any)(buffer, page);
const rgba = UTIF.toRGBA8(page);
const { width, height } = page;
return Promise.resolve(new ImageData(new Uint8ClampedArray(rgba.buffer), width, height));
} | /**
* 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 * 3);
}
return [Math.floor((width - w) / 2), Math.floor((height - h) / 2), w, h];
} | /** 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 being added/changed/removed:
// Usually you'd include a glob in the watch argument, e.g. `directory/**/.{jpg|png|...}`, but we cannot use globs unfortunately (see disableGlobbing)
// Instead, we ignore everything but image files in the `ignored` option
this.watcher = chokidar.watch(directory, {
disableGlobbing: true, // needed in order to support directories with brackets, quotes, asterisks, etc.
alwaysStat: true, // we need stats anyways during importing
depth: RECURSIVE_DIR_WATCH_DEPTH, // not really needed: added as a safety measure for infinite recursion between symbolic links
ignored: (path: string, stats?: Stats) => {
// We used to set `ignored` with regex patterns, but ran into problem with directories that
// contain dots in their file name.
// We ignore everything except image files but chokidar also matches entire directories. If
// those contain a dot, they will be ignored since they don't end with an image extension.
// So now we have to use a callback function that also provides `stats` through which we can
// use to detect whether the path is a file or a directory.
const basename = SysPath.basename(path);
// Ignore .dot files and folders.
if (basename.startsWith('.')) {
return true;
}
// If the path doesn't have an extension (likely a directory), don't ignore it.
// In the unlikely situation it is a file, we'll filter it out later in the .on('add', ...)
const ext = SysPath.extname(path).toLowerCase().split('.')[1];
if (!ext) {
return false;
}
// If the path (file or directory) ends with an image extension, don't ignore it.
if (extensions.includes(ext as IMG_EXTENSIONS_TYPE)) {
return false;
}
// Otherwise, we need to know whether it is a file or a directory before making a decision.
// If we don't return anything, this callback will be called a second time, with the stats
// variable as second argument
if (stats) {
// Ignore if
// * dot directory like `/home/.hidden-directory/` but not `/home/directory.with.dots/` and
// * not a directory, and not an image file either.
return !stats.isDirectory() || SysPath.basename(path).startsWith('.');
}
return false;
},
});
const watcher = this.watcher;
// Make a list of all files in this directory, which will be returned when all subdirs have been traversed
const initialFiles: FileStats[] = [];
return new Promise<FileStats[]>((resolve) => {
watcher
// we can assume stats exist since we passed alwaysStat: true to chokidar
.on('add', async (path, stats: Stats | BigIntStats) => {
if (this.isCancelled) {
console.log('Cancelling file watching');
await watcher.close();
this.isCancelled = false;
}
const ext = SysPath.extname(path).toLowerCase().split('.')[1];
if (extensions.includes(ext as IMG_EXTENSIONS_TYPE)) {
/**
* Chokidar doesn't detect renames as a unique event, it detects a "remove" and "add" event.
* We use the "ino" field of file stats to detect whether a new file is a previously detected file that was moved/renamed
* Relevant issue https://github.com/paulmillr/chokidar/issues/303#issuecomment-127039892
* Inspiration for using "ino" from https://github.com/chrismaltby/gb-studio/pull/576
* The stats given by chokidar is supposedly BigIntStats for Windows (since the ino is a 64 bit integer),
* https://github.com/paulmillr/chokidar/issues/844
* But my tests don't confirm this: console.log('ino', stats.ino, typeof stats.ino); -> type is number
*/
const fileStats: FileStats = {
absolutePath: path,
dateCreated: stats.birthtime,
dateModified: stats.mtime,
size: Number(stats.size),
ino: stats.ino.toString(),
};
if (this.isReady) {
ctx.postMessage({ type: 'add', value: fileStats });
} else {
initialFiles.push(fileStats);
}
}
})
// .on('change', (path: string) => console.debug(`File ${path} has been changed`))
// TODO: on directory change: update location hierarchy list
.on('unlink', (path: string) => ctx.postMessage({ type: 'remove', value: path }))
.on('ready', () => {
this.isReady = true;
resolve(initialFiles);
// Clear memory: initialFiles no longer needed
// Doing this immediately after resolving will resolve with an empty list for some reason
// So, do it with a timeout. Would be nicer to do it after an acknowledgement from the main thread
setTimeout(() => initialFiles.splice(0, initialFiles.length), 5000);
})
.on('error', (error) => {
console.error('Error fired in watcher', directory, error);
ctx.postMessage({ type: 'error', value: error });
});
});
} | /** 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`
let width = img.width;
let height = img.height;
if (img.width >= img.height) {
width = thumbnailMaxSize;
height = (thumbnailMaxSize * img.height) / img.width;
} else {
height = thumbnailMaxSize;
width = (thumbnailMaxSize * img.width) / img.height;
}
const canvas = new OffscreenCanvas(width, height);
const ctx2D = canvas.getContext('2d');
if (!ctx2D) {
console.warn('No canvas context 2D (should never happen)');
return null;
}
// Todo: Take into account rotation. Can be found with https://www.npmjs.com/package/node-exiftool
// TODO: Could maybe use https://www.electronjs.org/docs/api/native-image#imageresizeoptions
ctx2D.drawImage(img, 0, 0, width, height);
const thumbBlob = await canvas.convertToBlob({
type: `image/${thumbnailFormat}`,
quality: 0.75,
});
// TODO: is canvas.toDataURL faster?
const reader = new FileReaderSync();
const buffer = reader.readAsArrayBuffer(thumbBlob);
return buffer;
}; | // 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-null-assertion
const optionIndex = parseInt(row.getAttribute('aria-rowindex')!) - 1;
let options;
// Option Groups
if ('label' in matches[0] && 'options' in matches[0]) {
options = matches.flatMap((optgroup: OptionGroup) => optgroup.options);
}
// Options
else {
options = matches;
}
const option = options[optionIndex];
// Set value
setQuery(labelFromOption(option));
onChange(option);
}
}; | // 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;
const x = bounds.get(0) as number;
const y = bounds.get(1) as number;
const width = bounds.get(2) as number;
const height = bounds.get(3) as number;
return {
x,
y,
width,
height,
};
} | /**
* 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.getLayerBoundingBox('Layer 1');
*
* if (boundingBox) {
* const { x, y, width, height } = boundingBox;
* context.strokeRect(x, y, width, height);
* }
* });
* ```
*/ | 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`;
console.warn(`Primary WASM load failed from ${this._wasmURL}. Error: ${(initialError as Error).message}`);
console.warn(`Attempting to load WASM from backup URL: ${backupUrl}`);
try {
return await this._tryLoad(backupUrl);
} catch (backupError) {
console.error(`Primary WASM URL failed: ${(initialError as Error).message}`);
console.error(`Backup WASM URL failed: ${(backupError as Error).message}`);
throw new Error('WASM loading failed from all sources.');
}
});
}
return this._ModulePromise;
} | /**
* 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_PLUGIN_PATH \
is not set.');
return;
}
const npm: string = UIX_USE_PNPM ? 'pnpm' : 'npm';
let installPath: string = path.resolve(__dirname, '..', '..');
this.log.debug(`custom plugin path - ${UIX_CUSTOM_PLUGIN_PATH}`);
this.log.debug(`install path - ${installPath}`);
const installOptions: string[] = !UIX_USE_PNPM
? [
'--no-audit',
'--no-fund',
]
: [];
// check to see if custom plugin path is using a package.json file
if (
installPath === UIX_CUSTOM_PLUGIN_PATH &&
pathExistsSync(path.resolve(installPath, '../package.json')) === true
) {
installOptions.push('--save');
}
// install path is one level up
installPath = path.resolve(installPath, '..');
const args: string[] = ['install', ...installOptions, `homebridge-appletv-enhanced@${version}`];
this.log.info(`CMD: ${npm} "${args.join('" "')}" (cwd: ${installPath})`);
const [, , exitCode]: [string, string, number | null] = await runCommand(this.log, npm, args, { cwd: installPath });
if (exitCode === 0) {
this.log.success(`AppleTV Enhanced has successfully been updated to ${version}. Restarting now ...`);
process.exit(0);
} else {
this.log.error(`An error has occurred while updating AppleTV Enhanced. Exit code: ${exitCode}.`);
}
} | // 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,
this.platform.api.hap.encode(DisplayOrderTypes.ARRAY_ELEMENT_END, Buffer.alloc(0)),
]);
}
const element: Buffer = Buffer.alloc(4);
element.writeUInt32LE(identifier, 0);
identifiersTLV = Buffer.concat([
identifiersTLV,
this.platform.api.hap.encode(DisplayOrderTypes.ARRAY_ELEMENT_START, element),
]);
});
return identifiersTLV.toString('base64');
} | // 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.