prefix
stringlengths 82
32.6k
| middle
stringlengths 5
470
| suffix
stringlengths 0
81.2k
| file_path
stringlengths 6
168
| repo_name
stringlengths 16
77
| context
listlengths 5
5
| lang
stringclasses 4
values | ground_truth
stringlengths 5
470
|
---|---|---|---|---|---|---|---|
import { getAddress } from '@ethersproject/address';
import { splitSignature } from '@ethersproject/bytes';
import { FormatTypes, Interface } from '@ethersproject/abi';
import { fetchSpace } from '../../helpers/snapshot';
import { signer, validateDeployInput, validateSpace } from './utils';
import spaceCollectionAbi from './spaceCollectionImplementationAbi.json';
import spaceFactoryAbi from './spaceFactoryAbi.json';
const DeployType = {
Deploy: [
{ name: 'implementation', type: 'address' },
{ name: 'initializer', type: 'bytes' },
{ name: 'salt', type: 'uint256' }
]
};
const VERIFYING_CONTRACT = getAddress(process.env.NFT_CLAIMER_DEPLOY_VERIFYING_CONTRACT as string);
const IMPLEMENTATION_ADDRESS = getAddress(
process.env.NFT_CLAIMER_DEPLOY_IMPLEMENTATION_ADDRESS as string
);
const NFT_CLAIMER_NETWORK = process.env.NFT_CLAIMER_NETWORK;
const INITIALIZE_SELECTOR = process.env.NFT_CLAIMER_DEPLOY_INITIALIZE_SELECTOR;
export default async function payload(input: {
spaceOwner: string;
id: string;
maxSupply: string;
mintPrice: string;
proposerFee: string;
salt: string;
spaceTreasury: string;
}) {
const params = await validateDeployInput(input);
const space = await fetchSpace(params.id);
await validateSpace(params.spaceOwner, space);
const initializer = getInitializer({
spaceOwner: params.spaceOwner,
spaceId: space?.id as string,
maxSupply: params.maxSupply,
mintPrice: params.mintPrice,
proposerFee: params.proposerFee,
spaceTreasury: params.spaceTreasury
});
const result = {
initializer,
salt: params.salt,
abi: new Interface(spaceFactoryAbi).getFunction('deployProxy').format(FormatTypes.full),
verifyingContract: VERIFYING_CONTRACT,
implementation: IMPLEMENTATION_ADDRESS,
signature: await generateSignature(IMPLEMENTATION_ADDRESS, initializer, params.salt)
};
console.debug('Signer', signer.address);
console.debug('Payload', result);
return result;
}
function getInitializer(args: {
spaceId: string;
maxSupply: number;
mintPrice: string;
proposerFee: number;
spaceTreasury: string;
spaceOwner: string;
}) {
const params = [
args.spaceId,
'0.1',
args.maxSupply,
BigInt(args.mintPrice),
args.proposerFee,
getAddress(args.spaceTreasury),
getAddress(args.spaceOwner)
];
// This encodeFunctionData should ignore the last 4 params compared to
// the smart contract version
// NOTE Do not forget to remove the last 4 params in the ABI when copy/pasting
// from the smart contract
const initializer | = new Interface(spaceCollectionAbi).encodeFunctionData('initialize', params); |
const result = `${INITIALIZE_SELECTOR}${initializer.slice(10)}`;
console.debug('Initializer params', params);
return result;
}
async function generateSignature(implementation: string, initializer: string, salt: string) {
const params = {
domain: {
name: 'SpaceCollectionFactory',
version: '0.1',
chainId: NFT_CLAIMER_NETWORK,
verifyingContract: VERIFYING_CONTRACT
},
types: DeployType,
value: {
implementation,
initializer,
salt: BigInt(salt)
}
};
return splitSignature(await signer._signTypedData(params.domain, params.types, params.value));
}
| src/lib/nftClaimer/deploy.ts | snapshot-labs-snapshot-sidekick-800dacf | [
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " );\n return contract.snapshotFee();\n } catch (e: any) {\n capture(e);\n throw 'Unable to retrieve the snapshotFee';\n }\n}",
"score": 40.615423306442615
},
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " salt: params.salt\n });\n await validateProposerFee(parseInt(params.proposerFee));\n return {\n spaceOwner: getAddress(params.spaceOwner),\n spaceTreasury: getAddress(params.spaceTreasury),\n proposerFee: parseInt(params.proposerFee),\n maxSupply: parseInt(params.maxSupply),\n mintPrice: parseInt(params.mintPrice),\n ...params",
"score": 37.981724222677144
},
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " throw new Error(`proposerFee should not be greater than ${100 - sFee}`);\n }\n return true;\n}\nexport async function validateDeployInput(params: any) {\n validateAddresses({ spaceOwner: params.spaceOwner, spaceTreasury: params.spaceTreasury });\n validateNumbers({\n maxSupply: params.maxSupply,\n proposerFee: params.proposerFee,\n mintPrice: params.mintPrice,",
"score": 34.78725393444398
},
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " if (NFT_CLAIMER_NETWORK !== 5 && !(await isSpaceOwner(space.id, address))) {\n throw new Error('Address is not the space owner');\n }\n const contract = await getSpaceCollection(space.id);\n if (contract) {\n throw new Error(`SpaceCollection contract already exist (${contract.id})`);\n }\n}\nasync function isSpaceOwner(spaceId: string, address: string) {\n return (await snapshot.utils.getSpaceController(spaceId, HUB_NETWORK)) === getAddress(address);",
"score": 31.911352421524693
},
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " };\n}\nexport async function validateMintInput(params: any) {\n validateAddresses({ proposalAuthor: params.proposalAuthor, recipient: params.recipient });\n validateNumbers({\n salt: params.salt\n });\n return {\n proposalAuthor: getAddress(params.proposalAuthor),\n recipient: getAddress(params.recipient),",
"score": 23.283240880400157
}
] | typescript | = new Interface(spaceCollectionAbi).encodeFunctionData('initialize', params); |
import { getAddress } from '@ethersproject/address';
import { splitSignature } from '@ethersproject/bytes';
import { FormatTypes, Interface } from '@ethersproject/abi';
import { fetchSpace } from '../../helpers/snapshot';
import { signer, validateDeployInput, validateSpace } from './utils';
import spaceCollectionAbi from './spaceCollectionImplementationAbi.json';
import spaceFactoryAbi from './spaceFactoryAbi.json';
const DeployType = {
Deploy: [
{ name: 'implementation', type: 'address' },
{ name: 'initializer', type: 'bytes' },
{ name: 'salt', type: 'uint256' }
]
};
const VERIFYING_CONTRACT = getAddress(process.env.NFT_CLAIMER_DEPLOY_VERIFYING_CONTRACT as string);
const IMPLEMENTATION_ADDRESS = getAddress(
process.env.NFT_CLAIMER_DEPLOY_IMPLEMENTATION_ADDRESS as string
);
const NFT_CLAIMER_NETWORK = process.env.NFT_CLAIMER_NETWORK;
const INITIALIZE_SELECTOR = process.env.NFT_CLAIMER_DEPLOY_INITIALIZE_SELECTOR;
export default async function payload(input: {
spaceOwner: string;
id: string;
maxSupply: string;
mintPrice: string;
proposerFee: string;
salt: string;
spaceTreasury: string;
}) {
const params = await validateDeployInput(input);
const space = await fetchSpace(params.id);
await validateSpace(params.spaceOwner, space);
const initializer = getInitializer({
spaceOwner: params.spaceOwner,
spaceId: space?.id as string,
maxSupply: params.maxSupply,
mintPrice: params.mintPrice,
proposerFee: params.proposerFee,
spaceTreasury: params.spaceTreasury
});
const result = {
initializer,
salt: params.salt,
abi: new Interface(spaceFactoryAbi).getFunction('deployProxy').format(FormatTypes.full),
verifyingContract: VERIFYING_CONTRACT,
implementation: IMPLEMENTATION_ADDRESS,
signature: await generateSignature(IMPLEMENTATION_ADDRESS, initializer, params.salt)
};
| console.debug('Signer', signer.address); |
console.debug('Payload', result);
return result;
}
function getInitializer(args: {
spaceId: string;
maxSupply: number;
mintPrice: string;
proposerFee: number;
spaceTreasury: string;
spaceOwner: string;
}) {
const params = [
args.spaceId,
'0.1',
args.maxSupply,
BigInt(args.mintPrice),
args.proposerFee,
getAddress(args.spaceTreasury),
getAddress(args.spaceOwner)
];
// This encodeFunctionData should ignore the last 4 params compared to
// the smart contract version
// NOTE Do not forget to remove the last 4 params in the ABI when copy/pasting
// from the smart contract
const initializer = new Interface(spaceCollectionAbi).encodeFunctionData('initialize', params);
const result = `${INITIALIZE_SELECTOR}${initializer.slice(10)}`;
console.debug('Initializer params', params);
return result;
}
async function generateSignature(implementation: string, initializer: string, salt: string) {
const params = {
domain: {
name: 'SpaceCollectionFactory',
version: '0.1',
chainId: NFT_CLAIMER_NETWORK,
verifyingContract: VERIFYING_CONTRACT
},
types: DeployType,
value: {
implementation,
initializer,
salt: BigInt(salt)
}
};
return splitSignature(await signer._signTypedData(params.domain, params.types, params.value));
}
| src/lib/nftClaimer/deploy.ts | snapshot-labs-snapshot-sidekick-800dacf | [
{
"filename": "src/lib/nftClaimer/mint.ts",
"retrieved_chunk": " };\n return {\n signature: await generateSignature(verifyingContract, spaceId, message),\n contractAddress: verifyingContract,\n spaceId: proposal?.space.id,\n ...message,\n salt: params.salt,\n abi: new Interface(abi).getFunction('mint').format(FormatTypes.full)\n };\n}",
"score": 58.17505770612161
},
{
"filename": "src/lib/nftClaimer/mint.ts",
"retrieved_chunk": "import abi from './spaceCollectionImplementationAbi.json';\nimport { FormatTypes, Interface } from '@ethersproject/abi';\nconst MintType = {\n Mint: [\n { name: 'proposer', type: 'address' },\n { name: 'recipient', type: 'address' },\n { name: 'proposalId', type: 'uint256' },\n { name: 'salt', type: 'uint256' }\n ]\n};",
"score": 23.529784638055336
},
{
"filename": "src/lib/nftClaimer/mint.ts",
"retrieved_chunk": " const spaceId = proposal?.space.id as string;\n const verifyingContract = await getProposalContract(spaceId);\n if (!mintingAllowed(proposal?.space as Space)) {\n throw new Error('Space has closed minting');\n }\n const message = {\n proposer: params.proposalAuthor,\n recipient: params.recipient,\n proposalId: numberizeProposalId(params.id),\n salt: BigInt(params.salt)",
"score": 21.85080268061786
},
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " salt: params.salt\n });\n await validateProposerFee(parseInt(params.proposerFee));\n return {\n spaceOwner: getAddress(params.spaceOwner),\n spaceTreasury: getAddress(params.spaceTreasury),\n proposerFee: parseInt(params.proposerFee),\n maxSupply: parseInt(params.maxSupply),\n mintPrice: parseInt(params.mintPrice),\n ...params",
"score": 21.38000736271085
},
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " };\n}\nexport async function validateMintInput(params: any) {\n validateAddresses({ proposalAuthor: params.proposalAuthor, recipient: params.recipient });\n validateNumbers({\n salt: params.salt\n });\n return {\n proposalAuthor: getAddress(params.proposalAuthor),\n recipient: getAddress(params.recipient),",
"score": 20.530954130897012
}
] | typescript | console.debug('Signer', signer.address); |
import { fetchProposal, fetchVotes, Proposal, Vote } from '../helpers/snapshot';
import type { IStorage } from './storage/types';
import Cache from './cache';
class VotesReport extends Cache {
proposal?: Proposal | null;
constructor(id: string, storage: IStorage) {
super(id, storage);
this.filename = `snapshot-votes-report-${this.id}.csv`;
}
async isCacheable() {
this.proposal = await fetchProposal(this.id);
if (!this.proposal || this.proposal.state !== 'closed') {
return Promise.reject('RECORD_NOT_FOUND');
}
return true;
}
getContent = async () => {
this.isCacheable();
const votes = await this.fetchAllVotes();
let content = '';
console.log(`[votes-report] Generating report for ${this.id}`);
const headers = [
'address',
votes.length === 0 || typeof votes[0].choice === 'number'
? 'choice'
: this.proposal && this.proposal.choices.map((_choice, index) => `choice.${index + 1}`),
'voting_power',
'timestamp',
'author_ipfs_hash',
'reason'
].flat();
content += headers.join(',');
content += `\n${votes.map(vote => this.#formatCsvLine(vote)).join('\n')}`;
console.log(`[votes-report] Report for ${this.id} ready with ${votes.length} items`);
return content;
};
fetchAllVotes = async () => {
let votes: Vote[] = [];
let page = 0;
let createdPivot = 0;
const pageSize = 1000;
let resultsSize = 0;
const maxPage = 5;
do {
let newVotes = | await fetchVotes(this.id, { |
first: pageSize,
skip: page * pageSize,
created_gte: createdPivot,
orderBy: 'created',
orderDirection: 'asc'
});
resultsSize = newVotes.length;
if (page === 0 && createdPivot > 0) {
// Loosely assuming that there will never be more than 1000 duplicates
const existingIpfs = votes.slice(-pageSize).map(vote => vote.ipfs);
newVotes = newVotes.filter(vote => {
return !existingIpfs.includes(vote.ipfs);
});
}
if (page === maxPage) {
page = 0;
createdPivot = newVotes[newVotes.length - 1].created;
} else {
page++;
}
votes = votes.concat(newVotes);
this.generationProgress = Number(
((votes.length / (this.proposal?.votes as number)) * 100).toFixed(2)
);
} while (resultsSize === pageSize);
return votes;
};
toString() {
return `VotesReport#${this.id}`;
}
#formatCsvLine = (vote: Vote) => {
let choices: Vote['choice'][] = [];
if (typeof vote.choice !== 'number' && this.proposal) {
choices = Array.from({ length: this.proposal.choices.length });
for (const [key, value] of Object.entries(vote.choice)) {
choices[parseInt(key) - 1] = value;
}
} else {
choices.push(vote.choice);
}
return [
vote.voter,
...choices,
vote.vp,
vote.created,
vote.ipfs,
`"${vote.reason.replace(/(\r\n|\n|\r)/gm, '')}"`
]
.flat()
.join(',');
};
}
export default VotesReport;
| src/lib/votesReport.ts | snapshot-labs-snapshot-sidekick-800dacf | [
{
"filename": "src/helpers/snapshot.ts",
"retrieved_chunk": "export async function fetchVotes(\n id: string,\n { first = 1000, skip = 0, orderBy = 'created_gte', orderDirection = 'asc', created_gte = 0 } = {}\n) {\n const {\n data: { votes }\n }: { data: { votes: Vote[] } } = await client.query({\n query: VOTES_QUERY,\n variables: {\n id,",
"score": 26.46027548688808
},
{
"filename": "src/lib/moderationList.ts",
"retrieved_chunk": " const list: Partial<MODERATION_LIST> = {};\n const reverseMapping: Record<string, keyof MODERATION_LIST> = {};\n const queryWhereStatement: string[] = [];\n let queryWhereArgs: string[] = [];\n fields.forEach(field => {\n if (FIELDS.has(field)) {\n const args = FIELDS.get(field) as Record<string, string>;\n if (!args.file) {\n list[field] = [];\n reverseMapping[`${args.action}-${args.type}`] = field;",
"score": 18.018085228658666
},
{
"filename": "src/lib/cache.ts",
"retrieved_chunk": " this.generationProgress = 0;\n }\n async getContent(): Promise<string | Buffer> {\n return '';\n }\n getCache() {\n return this.storage.get(this.filename);\n }\n async isCacheable() {\n return true;",
"score": 11.090546261142388
},
{
"filename": "src/lib/nftClaimer/utils.ts",
"retrieved_chunk": " }\n });\n return true;\n}\nexport async function validateProposerFee(fee: number) {\n if (fee < 0 || fee > 100) {\n throw new Error('proposerFee should be between 0 and 100');\n }\n const sFee = await snapshotFee();\n if (sFee + fee > 100) {",
"score": 9.076634364487667
},
{
"filename": "src/helpers/utils.ts",
"retrieved_chunk": " jsonrpc: '2.0',\n result,\n id\n });\n}\nexport function rpcError(res: Response, e: Error | string, id: string | number) {\n const errorMessage = e instanceof Error ? e.message : e;\n const errorCode = ERROR_CODES[errorMessage] ? ERROR_CODES[errorMessage] : -32603;\n res.status(errorCode > 0 ? errorCode : 500).json({\n jsonrpc: '2.0',",
"score": 8.846125507888043
}
] | typescript | await fetchVotes(this.id, { |
/**
* A custom exception that represents a BadRequest error.
*/
// Import required modules
import { ApiHideProperty, ApiProperty } from '@nestjs/swagger';
import { HttpException, HttpStatus } from '@nestjs/common';
// Import internal modules
import { ExceptionConstants } from './exceptions.constants';
import { IException, IHttpBadRequestExceptionResponse } from './exceptions.interface';
export class BadRequestException extends HttpException {
@ApiProperty({
enum: ExceptionConstants.BadRequestCodes,
description: 'A unique code identifying the error.',
example: ExceptionConstants.BadRequestCodes.VALIDATION_ERROR,
})
code: number; // Internal status code
@ApiHideProperty()
cause: Error; // Error object causing the exception
@ApiProperty({
description: 'Message for the exception',
example: 'Bad Request',
})
message: string; // Message for the exception
@ApiProperty({
description: 'A description of the error message.',
example: 'The input provided was invalid',
})
description: string; // Description of the exception
@ApiProperty({
description: 'Timestamp of the exception',
format: 'date-time',
example: '2022-12-31T23:59:59.999Z',
})
timestamp: string; // Timestamp of the exception
@ApiProperty({
description: 'Trace ID of the request',
example: '65b5f773-df95-4ce5-a917-62ee832fcdd0',
})
traceId: string; // Trace ID of the request
/**
* Constructs a new BadRequestException object.
* @param exception An object containing the exception details.
* - message: A string representing the error message.
* - cause: An object representing the cause of the error.
* - description: A string describing the error in detail.
* - code: A number representing internal status code which helpful in future for frontend
*/
constructor(exception: IException) {
super(exception. | message, HttpStatus.BAD_REQUEST, { |
cause: exception.cause,
description: exception.description,
});
this.message = exception.message;
this.cause = exception.cause;
this.description = exception.description;
this.code = exception.code;
this.timestamp = new Date().toISOString();
}
/**
* Set the Trace ID of the BadRequestException instance.
* @param traceId A string representing the Trace ID.
*/
setTraceId = (traceId: string) => {
this.traceId = traceId;
};
/**
* Generate an HTTP response body representing the BadRequestException instance.
* @param message A string representing the message to include in the response body.
* @returns An object representing the HTTP response body.
*/
generateHttpResponseBody = (message?: string): IHttpBadRequestExceptionResponse => {
return {
code: this.code,
message: message || this.message,
description: this.description,
timestamp: this.timestamp,
traceId: this.traceId,
};
};
/**
* Returns a new instance of BadRequestException representing an HTTP Request Timeout error.
* @returns An instance of BadRequestException representing the error.
*/
static HTTP_REQUEST_TIMEOUT = () => {
return new BadRequestException({
message: 'HTTP Request Timeout',
code: ExceptionConstants.BadRequestCodes.HTTP_REQUEST_TIMEOUT,
});
};
/**
* Create a BadRequestException for when a resource already exists.
* @param {string} [msg] - Optional message for the exception.
* @returns {BadRequestException} - A BadRequestException with the appropriate error code and message.
*/
static RESOURCE_ALREADY_EXISTS = (msg?: string) => {
return new BadRequestException({
message: msg || 'Resource Already Exists',
code: ExceptionConstants.BadRequestCodes.RESOURCE_ALREADY_EXISTS,
});
};
/**
* Create a BadRequestException for when a resource is not found.
* @param {string} [msg] - Optional message for the exception.
* @returns {BadRequestException} - A BadRequestException with the appropriate error code and message.
*/
static RESOURCE_NOT_FOUND = (msg?: string) => {
return new BadRequestException({
message: msg || 'Resource Not Found',
code: ExceptionConstants.BadRequestCodes.RESOURCE_NOT_FOUND,
});
};
/**
* Returns a new instance of BadRequestException representing a Validation Error.
* @param msg A string representing the error message.
* @returns An instance of BadRequestException representing the error.
*/
static VALIDATION_ERROR = (msg?: string) => {
return new BadRequestException({
message: msg || 'Validation Error',
code: ExceptionConstants.BadRequestCodes.VALIDATION_ERROR,
});
};
/**
* Returns a new instance of BadRequestException representing an Unexpected Error.
* @param msg A string representing the error message.
* @returns An instance of BadRequestException representing the error.
*/
static UNEXPECTED = (msg?: string) => {
return new BadRequestException({
message: msg || 'Unexpected Error',
code: ExceptionConstants.BadRequestCodes.UNEXPECTED_ERROR,
});
};
/**
* Returns a new instance of BadRequestException representing an Invalid Input.
* @param msg A string representing the error message.
* @returns An instance of BadRequestException representing the error.
*/
static INVALID_INPUT = (msg?: string) => {
return new BadRequestException({
message: msg || 'Invalid Input',
code: ExceptionConstants.BadRequestCodes.INVALID_INPUT,
});
};
}
| src/exceptions/bad-request.exception.ts | piyush-kacha-nestjs-starter-kit-821cfdd | [
{
"filename": "src/exceptions/unauthorized.exception.ts",
"retrieved_chunk": " * @param exception An object containing the exception details.\n * - message: A string representing the error message.\n * - cause: An object representing the cause of the error.\n * - description: A string describing the error in detail.\n * - code: A number representing internal status code which helpful in future for frontend\n */\n constructor(exception: IException) {\n super(exception.message, HttpStatus.UNAUTHORIZED, {\n cause: exception.cause,\n description: exception.description,",
"score": 89.56236427024032
},
{
"filename": "src/exceptions/internal-server-error.exception.ts",
"retrieved_chunk": " * - message: A string representing the error message.\n * - cause: An object representing the cause of the error.\n * - description: A string describing the error in detail.\n * - code: A number representing internal status code which helpful in future for frontend\n */\n constructor(exception: IException) {\n super(exception.message, HttpStatus.INTERNAL_SERVER_ERROR, {\n cause: exception.cause,\n description: exception.description,\n });",
"score": 84.79309561341069
},
{
"filename": "src/exceptions/forbidden.exception.ts",
"retrieved_chunk": " * - message: A string representing the error message.\n * - cause: An object representing the cause of the error.\n * - description: A string describing the error in detail.\n * - code: A number representing internal status code which helpful in future for frontend\n */\n constructor(exception: IException) {\n super(exception.message, HttpStatus.FORBIDDEN, {\n cause: exception.cause,\n description: exception.description,\n });",
"score": 84.79309561341069
},
{
"filename": "src/exceptions/unauthorized.exception.ts",
"retrieved_chunk": " */\n setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the BadRequestException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */\n generateHttpResponseBody = (message?: string): IHttpUnauthorizedExceptionResponse => {",
"score": 41.79664328363277
},
{
"filename": "src/exceptions/internal-server-error.exception.ts",
"retrieved_chunk": " setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the BadRequestException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */\n generateHttpResponseBody = (message?: string): IHttpInternalServerErrorExceptionResponse => {\n return {",
"score": 41.458888439846476
}
] | typescript | message, HttpStatus.BAD_REQUEST, { |
import { ApiHideProperty, ApiProperty } from '@nestjs/swagger';
import { HttpException, HttpStatus } from '@nestjs/common';
// Import internal files & modules
import { ExceptionConstants } from './exceptions.constants';
import { IException, IHttpInternalServerErrorExceptionResponse } from './exceptions.interface';
// Exception class for Internal Server Error
export class InternalServerErrorException extends HttpException {
@ApiProperty({
enum: ExceptionConstants.InternalServerErrorCodes,
description: 'A unique code identifying the error.',
example: ExceptionConstants.InternalServerErrorCodes.INTERNAL_SERVER_ERROR,
})
code: number; // Internal status code
@ApiHideProperty()
cause: Error; // Error object causing the exception
@ApiProperty({
description: 'Message for the exception',
example: 'An unexpected error occurred while processing your request.',
})
message: string; // Message for the exception
@ApiProperty({
description: 'A description of the error message.',
example:
'The server encountered an unexpected condition that prevented it from fulfilling the request. This could be due to an error in the application code, a misconfiguration in the server, or an issue with the underlying infrastructure. Please try again later or contact the server administrator if the problem persists.',
})
description: string; // Description of the exception
@ApiProperty({
description: 'Timestamp of the exception',
format: 'date-time',
example: '2022-12-31T23:59:59.999Z',
})
timestamp: string; // Timestamp of the exception
@ApiProperty({
description: 'Trace ID of the request',
example: '65b5f773-df95-4ce5-a917-62ee832fcdd0',
})
traceId: string; // Trace ID of the request
/**
* Constructs a new InternalServerErrorException object.
* @param exception An object containing the exception details.
* - message: A string representing the error message.
* - cause: An object representing the cause of the error.
* - description: A string describing the error in detail.
* - code: A number representing internal status code which helpful in future for frontend
*/
constructor(exception: IException) {
super | (exception.message, HttpStatus.INTERNAL_SERVER_ERROR, { |
cause: exception.cause,
description: exception.description,
});
this.message = exception.message;
this.cause = exception.cause;
this.description = exception.description;
this.code = exception.code;
this.timestamp = new Date().toISOString();
}
/**
* Set the Trace ID of the BadRequestException instance.
* @param traceId A string representing the Trace ID.
*/
setTraceId = (traceId: string) => {
this.traceId = traceId;
};
/**
* Generate an HTTP response body representing the BadRequestException instance.
* @param message A string representing the message to include in the response body.
* @returns An object representing the HTTP response body.
*/
generateHttpResponseBody = (message?: string): IHttpInternalServerErrorExceptionResponse => {
return {
code: this.code,
message: message || this.message,
description: this.description,
timestamp: this.timestamp,
traceId: this.traceId,
};
};
/**
* Returns a new instance of InternalServerErrorException with a standard error message and code
* @param error Error object causing the exception
* @returns A new instance of InternalServerErrorException
*/
static INTERNAL_SERVER_ERROR = (error: any) => {
return new InternalServerErrorException({
message: 'We are sorry, something went wrong on our end. Please try again later or contact our support team for assistance.',
code: ExceptionConstants.InternalServerErrorCodes.INTERNAL_SERVER_ERROR,
cause: error,
});
};
/**
* Returns a new instance of InternalServerErrorException with a custom error message and code
* @param error Error object causing the exception
* @returns A new instance of InternalServerErrorException
*/
static UNEXPECTED_ERROR = (error: any) => {
return new InternalServerErrorException({
message: 'An unexpected error occurred while processing the request.',
code: ExceptionConstants.InternalServerErrorCodes.UNEXPECTED_ERROR,
cause: error,
});
};
}
| src/exceptions/internal-server-error.exception.ts | piyush-kacha-nestjs-starter-kit-821cfdd | [
{
"filename": "src/exceptions/bad-request.exception.ts",
"retrieved_chunk": " * Constructs a new BadRequestException object.\n * @param exception An object containing the exception details.\n * - message: A string representing the error message.\n * - cause: An object representing the cause of the error.\n * - description: A string describing the error in detail.\n * - code: A number representing internal status code which helpful in future for frontend\n */\n constructor(exception: IException) {\n super(exception.message, HttpStatus.BAD_REQUEST, {\n cause: exception.cause,",
"score": 92.28154472186738
},
{
"filename": "src/exceptions/unauthorized.exception.ts",
"retrieved_chunk": " * @param exception An object containing the exception details.\n * - message: A string representing the error message.\n * - cause: An object representing the cause of the error.\n * - description: A string describing the error in detail.\n * - code: A number representing internal status code which helpful in future for frontend\n */\n constructor(exception: IException) {\n super(exception.message, HttpStatus.UNAUTHORIZED, {\n cause: exception.cause,\n description: exception.description,",
"score": 89.57729992090741
},
{
"filename": "src/exceptions/forbidden.exception.ts",
"retrieved_chunk": " * - message: A string representing the error message.\n * - cause: An object representing the cause of the error.\n * - description: A string describing the error in detail.\n * - code: A number representing internal status code which helpful in future for frontend\n */\n constructor(exception: IException) {\n super(exception.message, HttpStatus.FORBIDDEN, {\n cause: exception.cause,\n description: exception.description,\n });",
"score": 84.55764559638925
},
{
"filename": "src/exceptions/bad-request.exception.ts",
"retrieved_chunk": " * @param traceId A string representing the Trace ID.\n */\n setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the BadRequestException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */",
"score": 39.765051791926
},
{
"filename": "src/exceptions/unauthorized.exception.ts",
"retrieved_chunk": " */\n setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the BadRequestException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */\n generateHttpResponseBody = (message?: string): IHttpUnauthorizedExceptionResponse => {",
"score": 38.28575638055939
}
] | typescript | (exception.message, HttpStatus.INTERNAL_SERVER_ERROR, { |
import { ApiHideProperty, ApiProperty } from '@nestjs/swagger';
import { HttpException, HttpStatus } from '@nestjs/common';
// Import internal files & modules
import { ExceptionConstants } from './exceptions.constants';
import { IException, IHttpInternalServerErrorExceptionResponse } from './exceptions.interface';
// Exception class for Internal Server Error
export class InternalServerErrorException extends HttpException {
@ApiProperty({
enum: ExceptionConstants.InternalServerErrorCodes,
description: 'A unique code identifying the error.',
example: ExceptionConstants.InternalServerErrorCodes.INTERNAL_SERVER_ERROR,
})
code: number; // Internal status code
@ApiHideProperty()
cause: Error; // Error object causing the exception
@ApiProperty({
description: 'Message for the exception',
example: 'An unexpected error occurred while processing your request.',
})
message: string; // Message for the exception
@ApiProperty({
description: 'A description of the error message.',
example:
'The server encountered an unexpected condition that prevented it from fulfilling the request. This could be due to an error in the application code, a misconfiguration in the server, or an issue with the underlying infrastructure. Please try again later or contact the server administrator if the problem persists.',
})
description: string; // Description of the exception
@ApiProperty({
description: 'Timestamp of the exception',
format: 'date-time',
example: '2022-12-31T23:59:59.999Z',
})
timestamp: string; // Timestamp of the exception
@ApiProperty({
description: 'Trace ID of the request',
example: '65b5f773-df95-4ce5-a917-62ee832fcdd0',
})
traceId: string; // Trace ID of the request
/**
* Constructs a new InternalServerErrorException object.
* @param exception An object containing the exception details.
* - message: A string representing the error message.
* - cause: An object representing the cause of the error.
* - description: A string describing the error in detail.
* - code: A number representing internal status code which helpful in future for frontend
*/
constructor(exception: IException) {
super(exception.message, HttpStatus.INTERNAL_SERVER_ERROR, {
cause: exception.cause,
description: exception.description,
});
this.message = exception.message;
this.cause = exception.cause;
this.description = exception.description;
this.code = exception.code;
this.timestamp = new Date().toISOString();
}
/**
* Set the Trace ID of the BadRequestException instance.
* @param traceId A string representing the Trace ID.
*/
setTraceId = (traceId: string) => {
this.traceId = traceId;
};
/**
* Generate an HTTP response body representing the BadRequestException instance.
* @param message A string representing the message to include in the response body.
* @returns An object representing the HTTP response body.
*/
generateHttpResponseBody = (message?: string) | : IHttpInternalServerErrorExceptionResponse => { |
return {
code: this.code,
message: message || this.message,
description: this.description,
timestamp: this.timestamp,
traceId: this.traceId,
};
};
/**
* Returns a new instance of InternalServerErrorException with a standard error message and code
* @param error Error object causing the exception
* @returns A new instance of InternalServerErrorException
*/
static INTERNAL_SERVER_ERROR = (error: any) => {
return new InternalServerErrorException({
message: 'We are sorry, something went wrong on our end. Please try again later or contact our support team for assistance.',
code: ExceptionConstants.InternalServerErrorCodes.INTERNAL_SERVER_ERROR,
cause: error,
});
};
/**
* Returns a new instance of InternalServerErrorException with a custom error message and code
* @param error Error object causing the exception
* @returns A new instance of InternalServerErrorException
*/
static UNEXPECTED_ERROR = (error: any) => {
return new InternalServerErrorException({
message: 'An unexpected error occurred while processing the request.',
code: ExceptionConstants.InternalServerErrorCodes.UNEXPECTED_ERROR,
cause: error,
});
};
}
| src/exceptions/internal-server-error.exception.ts | piyush-kacha-nestjs-starter-kit-821cfdd | [
{
"filename": "src/exceptions/unauthorized.exception.ts",
"retrieved_chunk": " */\n setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the BadRequestException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */\n generateHttpResponseBody = (message?: string): IHttpUnauthorizedExceptionResponse => {",
"score": 80.6303473640721
},
{
"filename": "src/exceptions/forbidden.exception.ts",
"retrieved_chunk": " setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the ForbiddenException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */\n generateHttpResponseBody = (message?: string): IHttpForbiddenExceptionResponse => {\n return {",
"score": 78.47284384445742
},
{
"filename": "src/exceptions/bad-request.exception.ts",
"retrieved_chunk": " * @param traceId A string representing the Trace ID.\n */\n setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the BadRequestException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */",
"score": 78.25117640075672
},
{
"filename": "src/filters/bad-request-exception.filter.ts",
"retrieved_chunk": " const request = ctx.getRequest();\n // Sets the trace ID from the request object to the exception.\n exception.setTraceId(request.id);\n // Constructs the response body object.\n const responseBody = exception.generateHttpResponseBody();\n // Uses the HTTP adapter to send the response with the constructed response body\n // and the HTTP status code.\n httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);\n }\n}",
"score": 34.70452299986263
},
{
"filename": "src/filters/internal-server-error-exception.filter.ts",
"retrieved_chunk": " // Retrieves the request object from the HTTP context.\n const request = ctx.getRequest();\n // Sets the trace ID from the request object to the exception.\n exception.setTraceId(request.id);\n // Constructs the response body object.\n const responseBody = exception.generateHttpResponseBody();\n // Uses the HTTP adapter to send the response with the constructed response body\n // and the HTTP status code.\n httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);\n }",
"score": 34.39454667275439
}
] | typescript | : IHttpInternalServerErrorExceptionResponse => { |
/**
* A custom exception that represents a Unauthorized error.
*/
// Import required modules
import { ApiHideProperty, ApiProperty } from '@nestjs/swagger';
import { HttpException, HttpStatus } from '@nestjs/common';
// Import internal modules
import { ExceptionConstants } from './exceptions.constants';
import { IException, IHttpUnauthorizedExceptionResponse } from './exceptions.interface';
/**
* A custom exception for unauthorized access errors.
*/
export class UnauthorizedException extends HttpException {
/** The error code. */
@ApiProperty({
enum: ExceptionConstants.UnauthorizedCodes,
description: 'A unique code identifying the error.',
example: ExceptionConstants.UnauthorizedCodes.TOKEN_EXPIRED_ERROR,
})
code: number;
/** The error that caused this exception. */
@ApiHideProperty()
cause: Error;
/** The error message. */
@ApiProperty({
description: 'Message for the exception',
example: 'The authentication token provided has expired.',
})
message: string;
/** The detailed description of the error. */
@ApiProperty({
description: 'A description of the error message.',
example: 'This error message indicates that the authentication token provided with the request has expired, and therefore the server cannot verify the users identity.',
})
description: string;
/** Timestamp of the exception */
@ApiProperty({
description: 'Timestamp of the exception',
format: 'date-time',
example: '2022-12-31T23:59:59.999Z',
})
timestamp: string;
/** Trace ID of the request */
@ApiProperty({
description: 'Trace ID of the request',
example: '65b5f773-df95-4ce5-a917-62ee832fcdd0',
})
traceId: string; // Trace ID of the request
/**
* Constructs a new UnauthorizedException object.
* @param exception An object containing the exception details.
* - message: A string representing the error message.
* - cause: An object representing the cause of the error.
* - description: A string describing the error in detail.
* - code: A number representing internal status code which helpful in future for frontend
*/
constructor(exception: IException) {
super(exception.message, HttpStatus.UNAUTHORIZED, {
cause: exception.cause,
description: exception.description,
});
this.message = exception.message;
this.cause = exception.cause;
this.description = exception.description;
this.code = exception.code;
this.timestamp = new Date().toISOString();
}
/**
* Set the Trace ID of the BadRequestException instance.
* @param traceId A string representing the Trace ID.
*/
setTraceId = (traceId: string) => {
this.traceId = traceId;
};
/**
* Generate an HTTP response body representing the BadRequestException instance.
* @param message A string representing the message to include in the response body.
* @returns An object representing the HTTP response body.
*/
| generateHttpResponseBody = (message?: string): IHttpUnauthorizedExceptionResponse => { |
return {
code: this.code,
message: message || this.message,
description: this.description,
timestamp: this.timestamp,
traceId: this.traceId,
};
};
/**
* A static method to generate an exception for token expiration error.
* @param msg - An optional error message.
* @returns An instance of the UnauthorizedException class.
*/
static TOKEN_EXPIRED_ERROR = (msg?: string) => {
return new UnauthorizedException({
message: msg || 'The authentication token provided has expired.',
code: ExceptionConstants.UnauthorizedCodes.TOKEN_EXPIRED_ERROR,
});
};
/**
* A static method to generate an exception for invalid JSON web token.
* @param msg - An optional error message.
* @returns An instance of the UnauthorizedException class.
*/
static JSON_WEB_TOKEN_ERROR = (msg?: string) => {
return new UnauthorizedException({
message: msg || 'Invalid token specified.',
code: ExceptionConstants.UnauthorizedCodes.JSON_WEB_TOKEN_ERROR,
});
};
/**
* A static method to generate an exception for unauthorized access to a resource.
* @param description - An optional detailed description of the error.
* @returns An instance of the UnauthorizedException class.
*/
static UNAUTHORIZED_ACCESS = (description?: string) => {
return new UnauthorizedException({
message: 'Access to the requested resource is unauthorized.',
code: ExceptionConstants.UnauthorizedCodes.UNAUTHORIZED_ACCESS,
description,
});
};
/**
* Create a UnauthorizedException for when a resource is not found.
* @param {string} [msg] - Optional message for the exception.
* @returns {BadRequestException} - A UnauthorizedException with the appropriate error code and message.
*/
static RESOURCE_NOT_FOUND = (msg?: string) => {
return new UnauthorizedException({
message: msg || 'Resource Not Found',
code: ExceptionConstants.UnauthorizedCodes.RESOURCE_NOT_FOUND,
});
};
/**
* Create a UnauthorizedException for when a resource is not found.
* @param {string} [msg] - Optional message for the exception.
* @returns {BadRequestException} - A UnauthorizedException with the appropriate error code and message.
*/
static USER_NOT_VERIFIED = (msg?: string) => {
return new UnauthorizedException({
message: msg || 'User not verified. Please complete verification process before attempting this action.',
code: ExceptionConstants.UnauthorizedCodes.USER_NOT_VERIFIED,
});
};
/**
* A static method to generate an exception for unexpected errors.
* @param error - The error that caused this exception.
* @returns An instance of the UnauthorizedException class.
*/
static UNEXPECTED_ERROR = (error: any) => {
return new UnauthorizedException({
message: 'An unexpected error occurred while processing the request. Please try again later.',
code: ExceptionConstants.UnauthorizedCodes.UNEXPECTED_ERROR,
cause: error,
});
};
/**
* A static method to generate an exception for when a forgot or change password time previous login token needs to be re-issued.
* @param msg - An optional error message.
* @returns - An instance of the UnauthorizedException class.
*/
static REQUIRED_RE_AUTHENTICATION = (msg?: string) => {
return new UnauthorizedException({
message: msg || 'Your previous login session has been terminated due to a password change or reset. Please log in again with your new password.',
code: ExceptionConstants.UnauthorizedCodes.REQUIRED_RE_AUTHENTICATION,
});
};
/**
* A static method to generate an exception for reset password token is invalid.
* @param msg - An optional error message.
* @returns - An instance of the UnauthorizedException class.
*/
static INVALID_RESET_PASSWORD_TOKEN = (msg?: string) => {
return new UnauthorizedException({
message: msg || 'The reset password token provided is invalid. Please request a new reset password token.',
code: ExceptionConstants.UnauthorizedCodes.INVALID_RESET_PASSWORD_TOKEN,
});
};
}
| src/exceptions/unauthorized.exception.ts | piyush-kacha-nestjs-starter-kit-821cfdd | [
{
"filename": "src/exceptions/internal-server-error.exception.ts",
"retrieved_chunk": " setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the BadRequestException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */\n generateHttpResponseBody = (message?: string): IHttpInternalServerErrorExceptionResponse => {\n return {",
"score": 80.49907146145085
},
{
"filename": "src/exceptions/forbidden.exception.ts",
"retrieved_chunk": " setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the ForbiddenException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */\n generateHttpResponseBody = (message?: string): IHttpForbiddenExceptionResponse => {\n return {",
"score": 78.95255585686263
},
{
"filename": "src/exceptions/bad-request.exception.ts",
"retrieved_chunk": " * @param traceId A string representing the Trace ID.\n */\n setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the BadRequestException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */",
"score": 78.79657040214082
},
{
"filename": "src/exceptions/bad-request.exception.ts",
"retrieved_chunk": " });\n };\n /**\n * Returns a new instance of BadRequestException representing an Unexpected Error.\n * @param msg A string representing the error message.\n * @returns An instance of BadRequestException representing the error.\n */\n static UNEXPECTED = (msg?: string) => {\n return new BadRequestException({\n message: msg || 'Unexpected Error',",
"score": 34.40937646705685
},
{
"filename": "src/exceptions/bad-request.exception.ts",
"retrieved_chunk": " code: ExceptionConstants.BadRequestCodes.UNEXPECTED_ERROR,\n });\n };\n /**\n * Returns a new instance of BadRequestException representing an Invalid Input.\n * @param msg A string representing the error message.\n * @returns An instance of BadRequestException representing the error.\n */\n static INVALID_INPUT = (msg?: string) => {\n return new BadRequestException({",
"score": 33.508937976123626
}
] | typescript | generateHttpResponseBody = (message?: string): IHttpUnauthorizedExceptionResponse => { |
/**
* A custom exception that represents a BadRequest error.
*/
// Import required modules
import { ApiHideProperty, ApiProperty } from '@nestjs/swagger';
import { HttpException, HttpStatus } from '@nestjs/common';
// Import internal modules
import { ExceptionConstants } from './exceptions.constants';
import { IException, IHttpBadRequestExceptionResponse } from './exceptions.interface';
export class BadRequestException extends HttpException {
@ApiProperty({
enum: ExceptionConstants.BadRequestCodes,
description: 'A unique code identifying the error.',
example: ExceptionConstants.BadRequestCodes.VALIDATION_ERROR,
})
code: number; // Internal status code
@ApiHideProperty()
cause: Error; // Error object causing the exception
@ApiProperty({
description: 'Message for the exception',
example: 'Bad Request',
})
message: string; // Message for the exception
@ApiProperty({
description: 'A description of the error message.',
example: 'The input provided was invalid',
})
description: string; // Description of the exception
@ApiProperty({
description: 'Timestamp of the exception',
format: 'date-time',
example: '2022-12-31T23:59:59.999Z',
})
timestamp: string; // Timestamp of the exception
@ApiProperty({
description: 'Trace ID of the request',
example: '65b5f773-df95-4ce5-a917-62ee832fcdd0',
})
traceId: string; // Trace ID of the request
/**
* Constructs a new BadRequestException object.
* @param exception An object containing the exception details.
* - message: A string representing the error message.
* - cause: An object representing the cause of the error.
* - description: A string describing the error in detail.
* - code: A number representing internal status code which helpful in future for frontend
*/
constructor(exception: IException) {
super(exception.message, HttpStatus.BAD_REQUEST, {
cause: exception.cause,
description: exception.description,
});
this.message = exception.message;
this.cause = exception.cause;
this.description = exception.description;
this.code = exception.code;
this.timestamp = new Date().toISOString();
}
/**
* Set the Trace ID of the BadRequestException instance.
* @param traceId A string representing the Trace ID.
*/
setTraceId = (traceId: string) => {
this.traceId = traceId;
};
/**
* Generate an HTTP response body representing the BadRequestException instance.
* @param message A string representing the message to include in the response body.
* @returns An object representing the HTTP response body.
*/
| generateHttpResponseBody = (message?: string): IHttpBadRequestExceptionResponse => { |
return {
code: this.code,
message: message || this.message,
description: this.description,
timestamp: this.timestamp,
traceId: this.traceId,
};
};
/**
* Returns a new instance of BadRequestException representing an HTTP Request Timeout error.
* @returns An instance of BadRequestException representing the error.
*/
static HTTP_REQUEST_TIMEOUT = () => {
return new BadRequestException({
message: 'HTTP Request Timeout',
code: ExceptionConstants.BadRequestCodes.HTTP_REQUEST_TIMEOUT,
});
};
/**
* Create a BadRequestException for when a resource already exists.
* @param {string} [msg] - Optional message for the exception.
* @returns {BadRequestException} - A BadRequestException with the appropriate error code and message.
*/
static RESOURCE_ALREADY_EXISTS = (msg?: string) => {
return new BadRequestException({
message: msg || 'Resource Already Exists',
code: ExceptionConstants.BadRequestCodes.RESOURCE_ALREADY_EXISTS,
});
};
/**
* Create a BadRequestException for when a resource is not found.
* @param {string} [msg] - Optional message for the exception.
* @returns {BadRequestException} - A BadRequestException with the appropriate error code and message.
*/
static RESOURCE_NOT_FOUND = (msg?: string) => {
return new BadRequestException({
message: msg || 'Resource Not Found',
code: ExceptionConstants.BadRequestCodes.RESOURCE_NOT_FOUND,
});
};
/**
* Returns a new instance of BadRequestException representing a Validation Error.
* @param msg A string representing the error message.
* @returns An instance of BadRequestException representing the error.
*/
static VALIDATION_ERROR = (msg?: string) => {
return new BadRequestException({
message: msg || 'Validation Error',
code: ExceptionConstants.BadRequestCodes.VALIDATION_ERROR,
});
};
/**
* Returns a new instance of BadRequestException representing an Unexpected Error.
* @param msg A string representing the error message.
* @returns An instance of BadRequestException representing the error.
*/
static UNEXPECTED = (msg?: string) => {
return new BadRequestException({
message: msg || 'Unexpected Error',
code: ExceptionConstants.BadRequestCodes.UNEXPECTED_ERROR,
});
};
/**
* Returns a new instance of BadRequestException representing an Invalid Input.
* @param msg A string representing the error message.
* @returns An instance of BadRequestException representing the error.
*/
static INVALID_INPUT = (msg?: string) => {
return new BadRequestException({
message: msg || 'Invalid Input',
code: ExceptionConstants.BadRequestCodes.INVALID_INPUT,
});
};
}
| src/exceptions/bad-request.exception.ts | piyush-kacha-nestjs-starter-kit-821cfdd | [
{
"filename": "src/exceptions/unauthorized.exception.ts",
"retrieved_chunk": " */\n setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the BadRequestException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */\n generateHttpResponseBody = (message?: string): IHttpUnauthorizedExceptionResponse => {",
"score": 82.39197357480762
},
{
"filename": "src/exceptions/internal-server-error.exception.ts",
"retrieved_chunk": " setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the BadRequestException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */\n generateHttpResponseBody = (message?: string): IHttpInternalServerErrorExceptionResponse => {\n return {",
"score": 81.736491183598
},
{
"filename": "src/exceptions/forbidden.exception.ts",
"retrieved_chunk": " setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the ForbiddenException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */\n generateHttpResponseBody = (message?: string): IHttpForbiddenExceptionResponse => {\n return {",
"score": 79.70167134442015
},
{
"filename": "src/filters/bad-request-exception.filter.ts",
"retrieved_chunk": " const request = ctx.getRequest();\n // Sets the trace ID from the request object to the exception.\n exception.setTraceId(request.id);\n // Constructs the response body object.\n const responseBody = exception.generateHttpResponseBody();\n // Uses the HTTP adapter to send the response with the constructed response body\n // and the HTTP status code.\n httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);\n }\n}",
"score": 33.94522967976564
},
{
"filename": "src/filters/internal-server-error-exception.filter.ts",
"retrieved_chunk": " // Retrieves the request object from the HTTP context.\n const request = ctx.getRequest();\n // Sets the trace ID from the request object to the exception.\n exception.setTraceId(request.id);\n // Constructs the response body object.\n const responseBody = exception.generateHttpResponseBody();\n // Uses the HTTP adapter to send the response with the constructed response body\n // and the HTTP status code.\n httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);\n }",
"score": 33.626086086167525
}
] | typescript | generateHttpResponseBody = (message?: string): IHttpBadRequestExceptionResponse => { |
import { ApiHideProperty, ApiProperty } from '@nestjs/swagger';
import { HttpException, HttpStatus } from '@nestjs/common';
// Import internal files & modules
import { ExceptionConstants } from './exceptions.constants';
import { IException, IHttpInternalServerErrorExceptionResponse } from './exceptions.interface';
// Exception class for Internal Server Error
export class InternalServerErrorException extends HttpException {
@ApiProperty({
enum: ExceptionConstants.InternalServerErrorCodes,
description: 'A unique code identifying the error.',
example: ExceptionConstants.InternalServerErrorCodes.INTERNAL_SERVER_ERROR,
})
code: number; // Internal status code
@ApiHideProperty()
cause: Error; // Error object causing the exception
@ApiProperty({
description: 'Message for the exception',
example: 'An unexpected error occurred while processing your request.',
})
message: string; // Message for the exception
@ApiProperty({
description: 'A description of the error message.',
example:
'The server encountered an unexpected condition that prevented it from fulfilling the request. This could be due to an error in the application code, a misconfiguration in the server, or an issue with the underlying infrastructure. Please try again later or contact the server administrator if the problem persists.',
})
description: string; // Description of the exception
@ApiProperty({
description: 'Timestamp of the exception',
format: 'date-time',
example: '2022-12-31T23:59:59.999Z',
})
timestamp: string; // Timestamp of the exception
@ApiProperty({
description: 'Trace ID of the request',
example: '65b5f773-df95-4ce5-a917-62ee832fcdd0',
})
traceId: string; // Trace ID of the request
/**
* Constructs a new InternalServerErrorException object.
* @param exception An object containing the exception details.
* - message: A string representing the error message.
* - cause: An object representing the cause of the error.
* - description: A string describing the error in detail.
* - code: A number representing internal status code which helpful in future for frontend
*/
constructor(exception: IException) {
super(exception.message, HttpStatus.INTERNAL_SERVER_ERROR, {
cause: exception.cause,
description: exception.description,
});
this.message = exception.message;
this.cause = exception.cause;
this.description = exception.description;
this.code = exception.code;
this.timestamp = new Date().toISOString();
}
/**
* Set the Trace ID of the BadRequestException instance.
* @param traceId A string representing the Trace ID.
*/
setTraceId = (traceId: string) => {
this.traceId = traceId;
};
/**
* Generate an HTTP response body representing the BadRequestException instance.
* @param message A string representing the message to include in the response body.
* @returns An object representing the HTTP response body.
*/
| generateHttpResponseBody = (message?: string): IHttpInternalServerErrorExceptionResponse => { |
return {
code: this.code,
message: message || this.message,
description: this.description,
timestamp: this.timestamp,
traceId: this.traceId,
};
};
/**
* Returns a new instance of InternalServerErrorException with a standard error message and code
* @param error Error object causing the exception
* @returns A new instance of InternalServerErrorException
*/
static INTERNAL_SERVER_ERROR = (error: any) => {
return new InternalServerErrorException({
message: 'We are sorry, something went wrong on our end. Please try again later or contact our support team for assistance.',
code: ExceptionConstants.InternalServerErrorCodes.INTERNAL_SERVER_ERROR,
cause: error,
});
};
/**
* Returns a new instance of InternalServerErrorException with a custom error message and code
* @param error Error object causing the exception
* @returns A new instance of InternalServerErrorException
*/
static UNEXPECTED_ERROR = (error: any) => {
return new InternalServerErrorException({
message: 'An unexpected error occurred while processing the request.',
code: ExceptionConstants.InternalServerErrorCodes.UNEXPECTED_ERROR,
cause: error,
});
};
}
| src/exceptions/internal-server-error.exception.ts | piyush-kacha-nestjs-starter-kit-821cfdd | [
{
"filename": "src/exceptions/unauthorized.exception.ts",
"retrieved_chunk": " */\n setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the BadRequestException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */\n generateHttpResponseBody = (message?: string): IHttpUnauthorizedExceptionResponse => {",
"score": 80.6303473640721
},
{
"filename": "src/exceptions/forbidden.exception.ts",
"retrieved_chunk": " setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the ForbiddenException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */\n generateHttpResponseBody = (message?: string): IHttpForbiddenExceptionResponse => {\n return {",
"score": 78.47284384445742
},
{
"filename": "src/exceptions/bad-request.exception.ts",
"retrieved_chunk": " * @param traceId A string representing the Trace ID.\n */\n setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the BadRequestException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */",
"score": 78.25117640075672
},
{
"filename": "src/filters/bad-request-exception.filter.ts",
"retrieved_chunk": " const request = ctx.getRequest();\n // Sets the trace ID from the request object to the exception.\n exception.setTraceId(request.id);\n // Constructs the response body object.\n const responseBody = exception.generateHttpResponseBody();\n // Uses the HTTP adapter to send the response with the constructed response body\n // and the HTTP status code.\n httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);\n }\n}",
"score": 34.70452299986263
},
{
"filename": "src/filters/internal-server-error-exception.filter.ts",
"retrieved_chunk": " // Retrieves the request object from the HTTP context.\n const request = ctx.getRequest();\n // Sets the trace ID from the request object to the exception.\n exception.setTraceId(request.id);\n // Constructs the response body object.\n const responseBody = exception.generateHttpResponseBody();\n // Uses the HTTP adapter to send the response with the constructed response body\n // and the HTTP status code.\n httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);\n }",
"score": 34.39454667275439
}
] | typescript | generateHttpResponseBody = (message?: string): IHttpInternalServerErrorExceptionResponse => { |
/**
* A custom exception that represents a Forbidden error.
*/
// Import required modules
import { ApiHideProperty, ApiProperty } from '@nestjs/swagger';
import { HttpException, HttpStatus } from '@nestjs/common';
// Import internal modules
import { ExceptionConstants } from './exceptions.constants';
import { IException, IHttpForbiddenExceptionResponse } from './exceptions.interface';
/**
* A custom exception for forbidden errors.
*/
export class ForbiddenException extends HttpException {
/** The error code. */
@ApiProperty({
enum: ExceptionConstants.ForbiddenCodes,
description: 'You do not have permission to perform this action.',
example: ExceptionConstants.ForbiddenCodes.MISSING_PERMISSIONS,
})
code: number;
/** The error that caused this exception. */
@ApiHideProperty()
cause: Error;
/** The error message. */
@ApiProperty({
description: 'Message for the exception',
example: 'You do not have permission to perform this action.',
})
message: string;
/** The detailed description of the error. */
@ApiProperty({
description: 'A description of the error message.',
})
description: string;
/** Timestamp of the exception */
@ApiProperty({
description: 'Timestamp of the exception',
format: 'date-time',
example: '2022-12-31T23:59:59.999Z',
})
timestamp: string;
/** Trace ID of the request */
@ApiProperty({
description: 'Trace ID of the request',
example: '65b5f773-df95-4ce5-a917-62ee832fcdd0',
})
traceId: string; // Trace ID of the request
/**
* Constructs a new ForbiddenException object.
* @param exception An object containing the exception details.
* - message: A string representing the error message.
* - cause: An object representing the cause of the error.
* - description: A string describing the error in detail.
* - code: A number representing internal status code which helpful in future for frontend
*/
constructor(exception: IException) {
super(exception.message, HttpStatus.FORBIDDEN, {
cause: exception.cause,
description: exception.description,
});
this.message = exception.message;
this.cause = exception.cause;
this.description = exception.description;
this.code = exception.code;
this.timestamp = new Date().toISOString();
}
/**
* Set the Trace ID of the ForbiddenException instance.
* @param traceId A string representing the Trace ID.
*/
setTraceId = (traceId: string) => {
this.traceId = traceId;
};
/**
* Generate an HTTP response body representing the ForbiddenException instance.
* @param message A string representing the message to include in the response body.
* @returns An object representing the HTTP response body.
*/
| generateHttpResponseBody = (message?: string): IHttpForbiddenExceptionResponse => { |
return {
code: this.code,
message: message || this.message,
description: this.description,
timestamp: this.timestamp,
traceId: this.traceId,
};
};
/**
* A static method to generate an exception forbidden error.
* @param msg - An optional error message.
* @returns An instance of the ForbiddenException class.
*/
static FORBIDDEN = (msg?: string) => {
return new ForbiddenException({
message: msg || 'Access to this resource is forbidden.',
code: ExceptionConstants.ForbiddenCodes.FORBIDDEN,
});
};
/**
* A static method to generate an exception missing permissions error.
* @param msg - An optional error message.
* @returns An instance of the ForbiddenException class.
*/
static MISSING_PERMISSIONS = (msg?: string) => {
return new ForbiddenException({
message: msg || 'You do not have permission to perform this action.',
code: ExceptionConstants.ForbiddenCodes.MISSING_PERMISSIONS,
});
};
}
| src/exceptions/forbidden.exception.ts | piyush-kacha-nestjs-starter-kit-821cfdd | [
{
"filename": "src/exceptions/unauthorized.exception.ts",
"retrieved_chunk": " */\n setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the BadRequestException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */\n generateHttpResponseBody = (message?: string): IHttpUnauthorizedExceptionResponse => {",
"score": 79.72169400804567
},
{
"filename": "src/exceptions/internal-server-error.exception.ts",
"retrieved_chunk": " setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the BadRequestException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */\n generateHttpResponseBody = (message?: string): IHttpInternalServerErrorExceptionResponse => {\n return {",
"score": 79.09038850135406
},
{
"filename": "src/exceptions/bad-request.exception.ts",
"retrieved_chunk": " * @param traceId A string representing the Trace ID.\n */\n setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the BadRequestException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */",
"score": 77.40203271525783
},
{
"filename": "src/filters/bad-request-exception.filter.ts",
"retrieved_chunk": " const request = ctx.getRequest();\n // Sets the trace ID from the request object to the exception.\n exception.setTraceId(request.id);\n // Constructs the response body object.\n const responseBody = exception.generateHttpResponseBody();\n // Uses the HTTP adapter to send the response with the constructed response body\n // and the HTTP status code.\n httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);\n }\n}",
"score": 34.74565027429557
},
{
"filename": "src/filters/internal-server-error-exception.filter.ts",
"retrieved_chunk": " // Retrieves the request object from the HTTP context.\n const request = ctx.getRequest();\n // Sets the trace ID from the request object to the exception.\n exception.setTraceId(request.id);\n // Constructs the response body object.\n const responseBody = exception.generateHttpResponseBody();\n // Uses the HTTP adapter to send the response with the constructed response body\n // and the HTTP status code.\n httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);\n }",
"score": 34.39246890272486
}
] | typescript | generateHttpResponseBody = (message?: string): IHttpForbiddenExceptionResponse => { |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
private domListener: DomListener,
private searchHistory: SearchHistory,
private theme: Theme,
) {
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
this.domListener.onSearch(async (keyword: string) => {
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string): Array<SearchJSItem> | null | undefined {
const items = this.app.config.data
return items.filter((item) => {
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
return this.app.config.element ?? document.body
}
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) {
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance | = new Item()
itemInstance.renderList({ |
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
icon: hashIcon(),
})
this.handleItemClickListener()
}
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
icon: historyIcon(),
})
this.handleItemClickListener()
}
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this.domListener.onItemClick(
(data: any) => {
this.searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => {
this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
}
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " * @param {Array<SearchJSItem>} items\n * @returns {void}\n */\n public renderList({ id, items, hideRemoveButton, notFoundLabel, icon }: ListRenderPayload): void {\n const element = document.getElementById(id)\n element.innerHTML = ``\n let html = `<div class=\"${CLASS_ITEMS}\">`\n if (items.length == 0) {\n html += `<div class=\"not-found-label\">${notFoundLabel}</div>`\n }",
"score": 22.0067219440711
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " id: string\n items?: Array<SearchJSItem>\n icon: string\n hideRemoveButton: boolean\n notFoundLabel: string\n}\nexport class Item {\n /**\n * render item list\n *",
"score": 19.96152363141206
},
{
"filename": "src/types/index.ts",
"retrieved_chunk": " icon?: string\n placeholder?: string\n }\n onSearchDelay?: number\n onSearch?: (keyword: string) => Array<SearchJSItem> | Promise<Array<SearchJSItem>>\n onSelected: (data: SearchJSItem) => void\n}",
"score": 15.383094941612615
},
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": " public onItemClick(\n onSelected: (item: SearchJSItem) => void,\n onRemove: (item: SearchJSItem) => void,\n ): void {\n const items = document.querySelectorAll(`#${ID} .${CLASS_ITEM}`)\n items.forEach((el) =>\n // item click to select\n el.addEventListener(this.EVENT_CLICK, (event: any) => {\n const closeElements = event.target.closest(`.${CLASS_ITEM_CLOSE} *`)\n if (event.target == closeElements) {",
"score": 14.907726177943564
},
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": " constructor() {\n this.db = window.localStorage\n }\n /**\n * get list of items store in history\n *\n * @returns {Array<SearchJSItem> | undefined | null}\n */\n public getList(): Array<SearchJSItem> | undefined | null {\n let data = this.db.getItem(this.storageKey)",
"score": 14.883946316233212
}
] | typescript | = new Item()
itemInstance.renderList({ |
import { SearchJSTheme } from '../types'
export const CssBackdropBackground = '--search-js-backdrop-bg'
export const CssModalBackground = '--search-js-modal-bg'
export const CssModalBoxShadow = '--search-js-modal-box-shadow'
export const CssModalFooterBoxShadow = '--search-js-modal-footer-box-shadow'
export const CssKeyboardButtonBoxShadow = '--search-js-keyboard-button-box-shadow'
export const CssKeyboardButtonBackground = '--search-js-keyboard-button-bg'
export const CssInputBackground = '--search-js-search-input-bg'
export const CssInputPlaceholderColor = '--search-js-input-placeholder-color'
export const CssItemBackground = '--search-js-item-bg'
export const CssItemBoxShadow = '--search-js-item-box-shadow'
export const CssTextColor = '--search-js-text-color'
export const CssTheme = '--search-js-theme'
export const CssWidth = '--search-js-width'
export const CssHeight = '--search-js-height'
export const CssFontFamily = '--search-js-font-family'
export const CssPositionTop = '--search-js-top'
export const AvailableThemes: any = {
[SearchJSTheme.ThemeDark]: {
[CssBackdropBackground]: 'rgba(47, 55, 69, 0.7)',
[CssModalBackground]: '#1b1b1d',
[CssModalBoxShadow]: 'inset 1px 1px 0 0 #2c2e40, 0 3px 8px 0 #000309',
[CssModalFooterBoxShadow]:
'inset 0 1px 0 0 rgba(73, 76, 106, 0.5), 0 -4px 8px 0 rgba(0, 0, 0, 0.2)',
[CssKeyboardButtonBoxShadow]:
'inset 0 -2px 0 0 #282d55, inset 0 0 1px 1px #51577d, 0 2px 2px 0 rgba(3, 4, 9, 0.3)',
[CssKeyboardButtonBackground]: 'linear-gradient(-26.5deg, transparent 0%, transparent 100%)',
[CssInputBackground]: 'black',
[CssInputPlaceholderColor]: '#aeaeae',
[CssItemBackground]: '#1c1e21',
[CssItemBoxShadow]: 'none',
[CssTextColor]: '#b3b3b3',
},
[SearchJSTheme.ThemeLight]: {
[CssBackdropBackground]: 'rgba(101, 108, 133, 0.8)',
[CssModalBackground]: '#f5f6f7',
[CssModalBoxShadow]: 'inset 1px 1px 0 0 hsla(0, 0%, 100%, 0.5), 0 3px 8px 0 #555a64',
[CssModalFooterBoxShadow]: '0 -1px 0 0 #e0e3e8, 0 -3px 6px 0 rgba(69, 98, 155, 0.12)',
[CssKeyboardButtonBoxShadow]:
'inset 0 -2px 0 0 #cdcde6, inset 0 0 1px 1px #fff, 0 1px 2px 1px rgba(30, 35, 90, 0.4)',
[CssKeyboardButtonBackground]: 'linear-gradient(-225deg, #d5dbe4, #f8f8f8)',
[CssInputBackground]: 'white',
[CssInputPlaceholderColor]: '#969faf',
[CssItemBackground]: 'white',
[CssItemBoxShadow]: '0 1px 3px 0 #d4d9e1',
[CssTextColor]: '#969faf',
},
[SearchJSTheme.ThemeGithubDark]: {
[CssBackdropBackground]: 'rgba(1,4,9,0.8)',
[CssModalBackground]: '#0D1116',
[CssModalBoxShadow]: 'none',
[CssModalFooterBoxShadow]: 'none',
[CssKeyboardButtonBoxShadow]: 'none',
[CssKeyboardButtonBackground]: 'none',
[CssInputBackground]: 'transparent',
[CssInputPlaceholderColor]: '#6D7681',
[CssItemBackground]: 'transparent',
[CssItemBoxShadow]: 'none',
[CssTextColor]: '#C5CED6',
[CssTheme]: 'transparent',
},
| [SearchJSTheme.ThemeGithubLight]: { |
[CssBackdropBackground]: 'rgba(27,31,36,0.5)',
[CssModalBackground]: '#FFFFFF',
[CssModalBoxShadow]: 'none',
[CssModalFooterBoxShadow]: 'none',
[CssKeyboardButtonBoxShadow]: 'none',
[CssKeyboardButtonBackground]: 'none',
[CssInputBackground]: 'transparent',
[CssInputPlaceholderColor]: '#6E7781',
[CssItemBackground]: 'transparent',
[CssItemBoxShadow]: 'none',
[CssTextColor]: '#1F2329',
[CssTheme]: 'transparent',
},
}
| src/themes/AvailableThemes.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/utils/SearchComponent.ts",
"retrieved_chunk": " private hideLoading(): void {\n document.getElementById(ID_LOADING).style.display = 'none'\n }\n}",
"score": 9.580582359580914
},
{
"filename": "src/utils/SearchComponent.ts",
"retrieved_chunk": " this.handleItemClickListener()\n }\n /**\n * hide history\n *\n * @returns {void}\n */\n private hideHistories(): void {\n document.getElementById(ID_HISTORIES).style.display = 'none'\n }",
"score": 8.524736476822293
},
{
"filename": "src/themes/index.ts",
"retrieved_chunk": " return [SearchJSTheme.ThemeGithubLight, SearchJSTheme.ThemeGithubDark]\n }\n /**\n * get theme css string from config\n *\n * @param {SearchJSConfig} config\n * @returns {string}\n */\n private getTheme(config: SearchJSConfig): string {\n const defaultTheme = config.darkMode ? SearchJSTheme.ThemeDark : SearchJSTheme.ThemeLight",
"score": 7.8875800797741835
},
{
"filename": "src/utils/SearchComponent.ts",
"retrieved_chunk": " * @returns {void}\n */\n private hideSearchResult(): void {\n document.getElementById(ID_RESULTS).style.display = 'none'\n }\n /**\n * show history list\n *\n * @param {Array<SearchJSItem>} items\n * @returns {void}",
"score": 7.807686020875064
},
{
"filename": "src/index.ts",
"retrieved_chunk": " * @returns {void}\n */\n public close(): void {\n this.component.element.style.display = 'none'\n }\n /**\n * private function to focus on search input when modal open\n *\n * @returns {void}\n */",
"score": 7.43257542735441
}
] | typescript | [SearchJSTheme.ThemeGithubLight]: { |
/**
* A custom exception that represents a Forbidden error.
*/
// Import required modules
import { ApiHideProperty, ApiProperty } from '@nestjs/swagger';
import { HttpException, HttpStatus } from '@nestjs/common';
// Import internal modules
import { ExceptionConstants } from './exceptions.constants';
import { IException, IHttpForbiddenExceptionResponse } from './exceptions.interface';
/**
* A custom exception for forbidden errors.
*/
export class ForbiddenException extends HttpException {
/** The error code. */
@ApiProperty({
enum: ExceptionConstants.ForbiddenCodes,
description: 'You do not have permission to perform this action.',
example: ExceptionConstants.ForbiddenCodes.MISSING_PERMISSIONS,
})
code: number;
/** The error that caused this exception. */
@ApiHideProperty()
cause: Error;
/** The error message. */
@ApiProperty({
description: 'Message for the exception',
example: 'You do not have permission to perform this action.',
})
message: string;
/** The detailed description of the error. */
@ApiProperty({
description: 'A description of the error message.',
})
description: string;
/** Timestamp of the exception */
@ApiProperty({
description: 'Timestamp of the exception',
format: 'date-time',
example: '2022-12-31T23:59:59.999Z',
})
timestamp: string;
/** Trace ID of the request */
@ApiProperty({
description: 'Trace ID of the request',
example: '65b5f773-df95-4ce5-a917-62ee832fcdd0',
})
traceId: string; // Trace ID of the request
/**
* Constructs a new ForbiddenException object.
* @param exception An object containing the exception details.
* - message: A string representing the error message.
* - cause: An object representing the cause of the error.
* - description: A string describing the error in detail.
* - code: A number representing internal status code which helpful in future for frontend
*/
constructor(exception: IException) {
super(exception. | message, HttpStatus.FORBIDDEN, { |
cause: exception.cause,
description: exception.description,
});
this.message = exception.message;
this.cause = exception.cause;
this.description = exception.description;
this.code = exception.code;
this.timestamp = new Date().toISOString();
}
/**
* Set the Trace ID of the ForbiddenException instance.
* @param traceId A string representing the Trace ID.
*/
setTraceId = (traceId: string) => {
this.traceId = traceId;
};
/**
* Generate an HTTP response body representing the ForbiddenException instance.
* @param message A string representing the message to include in the response body.
* @returns An object representing the HTTP response body.
*/
generateHttpResponseBody = (message?: string): IHttpForbiddenExceptionResponse => {
return {
code: this.code,
message: message || this.message,
description: this.description,
timestamp: this.timestamp,
traceId: this.traceId,
};
};
/**
* A static method to generate an exception forbidden error.
* @param msg - An optional error message.
* @returns An instance of the ForbiddenException class.
*/
static FORBIDDEN = (msg?: string) => {
return new ForbiddenException({
message: msg || 'Access to this resource is forbidden.',
code: ExceptionConstants.ForbiddenCodes.FORBIDDEN,
});
};
/**
* A static method to generate an exception missing permissions error.
* @param msg - An optional error message.
* @returns An instance of the ForbiddenException class.
*/
static MISSING_PERMISSIONS = (msg?: string) => {
return new ForbiddenException({
message: msg || 'You do not have permission to perform this action.',
code: ExceptionConstants.ForbiddenCodes.MISSING_PERMISSIONS,
});
};
}
| src/exceptions/forbidden.exception.ts | piyush-kacha-nestjs-starter-kit-821cfdd | [
{
"filename": "src/exceptions/bad-request.exception.ts",
"retrieved_chunk": " * Constructs a new BadRequestException object.\n * @param exception An object containing the exception details.\n * - message: A string representing the error message.\n * - cause: An object representing the cause of the error.\n * - description: A string describing the error in detail.\n * - code: A number representing internal status code which helpful in future for frontend\n */\n constructor(exception: IException) {\n super(exception.message, HttpStatus.BAD_REQUEST, {\n cause: exception.cause,",
"score": 91.5578102825912
},
{
"filename": "src/exceptions/unauthorized.exception.ts",
"retrieved_chunk": " * @param exception An object containing the exception details.\n * - message: A string representing the error message.\n * - cause: An object representing the cause of the error.\n * - description: A string describing the error in detail.\n * - code: A number representing internal status code which helpful in future for frontend\n */\n constructor(exception: IException) {\n super(exception.message, HttpStatus.UNAUTHORIZED, {\n cause: exception.cause,\n description: exception.description,",
"score": 89.09536810114463
},
{
"filename": "src/exceptions/internal-server-error.exception.ts",
"retrieved_chunk": " * - message: A string representing the error message.\n * - cause: An object representing the cause of the error.\n * - description: A string describing the error in detail.\n * - code: A number representing internal status code which helpful in future for frontend\n */\n constructor(exception: IException) {\n super(exception.message, HttpStatus.INTERNAL_SERVER_ERROR, {\n cause: exception.cause,\n description: exception.description,\n });",
"score": 84.11677853636122
},
{
"filename": "src/exceptions/bad-request.exception.ts",
"retrieved_chunk": " * @param traceId A string representing the Trace ID.\n */\n setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the BadRequestException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */",
"score": 39.5852345228499
},
{
"filename": "src/exceptions/unauthorized.exception.ts",
"retrieved_chunk": " */\n setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the BadRequestException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */\n generateHttpResponseBody = (message?: string): IHttpUnauthorizedExceptionResponse => {",
"score": 38.04352018807659
}
] | typescript | message, HttpStatus.FORBIDDEN, { |
import {
CLASS_CLEAR_ICON,
CLASS_CONTAINER,
ATTR_DATA_PAYLOAD,
ID,
CLASS_INPUT,
CLASS_ITEM,
CLASS_ITEM_CLOSE,
} from '../constant'
import { SearchJSItem } from '../types'
import { Encoder } from './Encoder'
export class DomListener {
/**
* @var {string} EVENT_CLICK
*/
private EVENT_CLICK = 'click'
/**
* @var {string} EVENT_KEYUP
*/
private EVENT_KEYUP = 'keyup'
/**
* listen for on back drop click to hide modal
*
* @param {Function} callback
* @returns {void}
*/
public onBackDropClick(callback: () => void): void {
const element = document.querySelector(`#${ID}.${CLASS_CONTAINER}`)
element.addEventListener(this.EVENT_CLICK, (event) => {
if (event.target === element) {
callback()
}
})
}
/**
* listen for on search
*
* @param {Function} callback
* @returns {void}
*/
public onSearch(callback: (keyword: string) => void): void {
const element: HTMLInputElement = document.querySelector(`#${ID} .${CLASS_INPUT}`)
// search input keyup
element.addEventListener(this.EVENT_KEYUP, (event: any) => {
const keyword = event.target.value.toLowerCase()
callback(keyword)
})
// clear icon
document.querySelector(`.${CLASS_CLEAR_ICON}`).addEventListener(this.EVENT_CLICK, () => {
element.value = ''
callback(null)
})
}
/**
* listen for on item click
*
* @param {Function} onSelected
* @param {Function} onRemove
* @returns {void}
*/
public onItemClick(
onSelected | : (item: SearchJSItem) => void,
onRemove: (item: SearchJSItem) => void,
): void { |
const items = document.querySelectorAll(`#${ID} .${CLASS_ITEM}`)
items.forEach((el) =>
// item click to select
el.addEventListener(this.EVENT_CLICK, (event: any) => {
const closeElements = event.target.closest(`.${CLASS_ITEM_CLOSE} *`)
if (event.target == closeElements) {
return
}
const parentElement = event.target.closest(`.${CLASS_ITEM}`)
const data = parentElement.getAttribute(ATTR_DATA_PAYLOAD)
onSelected(Encoder.decode(data))
}),
)
const closeItems = document.querySelectorAll(`#${ID} .${CLASS_ITEM_CLOSE}`)
closeItems.forEach((el) =>
// item click to remove from history
el.addEventListener(this.EVENT_CLICK, (event: any) => {
const parentElement = event.target.closest(`.${CLASS_ITEM_CLOSE}`)
const data = parentElement.getAttribute(ATTR_DATA_PAYLOAD)
onRemove(Encoder.decode(data))
}),
)
}
}
| src/utils/DomListener.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": " public clear(): void {\n this.db.setItem(this.storageKey, '[]')\n }\n /**\n * remove item stored\n *\n * @param {SearchJSItem} item\n * @returns {void}\n */\n public remove(item: SearchJSItem): void {",
"score": 23.983693361701928
},
{
"filename": "src/utils/SearchComponent.ts",
"retrieved_chunk": " /**\n * listen on select and on remove event on item\n *\n * @return {void}\n */\n private handleItemClickListener(): void {\n this.domListener.onItemClick(\n (data: any) => {\n this.searchHistory.add(data)\n this.app.config.onSelected(data)",
"score": 22.341232278023792
},
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": " }\n this.db.setItem(this.storageKey, JSON.stringify(arrayItems))\n }\n /**\n * add item to history\n *\n * @param {SearchJSItem} item\n * @returns {void}\n */\n public add(item: SearchJSItem): void {",
"score": 21.95513017205406
},
{
"filename": "src/types/index.ts",
"retrieved_chunk": " icon?: string\n placeholder?: string\n }\n onSearchDelay?: number\n onSearch?: (keyword: string) => Array<SearchJSItem> | Promise<Array<SearchJSItem>>\n onSelected: (data: SearchJSItem) => void\n}",
"score": 19.68292967096194
},
{
"filename": "src/utils/SearchComponent.ts",
"retrieved_chunk": " /**\n * show item lists\n *\n * @param {Array<SearchJSItem>} items\n * @returns {void}\n */\n private showSearchResult(items: Array<SearchJSItem>): void {\n const itemInstance = new Item()\n itemInstance.renderList({\n id: ID_RESULTS,",
"score": 18.2556641165878
}
] | typescript | : (item: SearchJSItem) => void,
onRemove: (item: SearchJSItem) => void,
): void { |
import {
CLASS_CLEAR_ICON,
CLASS_CONTAINER,
ATTR_DATA_PAYLOAD,
ID,
CLASS_INPUT,
CLASS_ITEM,
CLASS_ITEM_CLOSE,
} from '../constant'
import { SearchJSItem } from '../types'
import { Encoder } from './Encoder'
export class DomListener {
/**
* @var {string} EVENT_CLICK
*/
private EVENT_CLICK = 'click'
/**
* @var {string} EVENT_KEYUP
*/
private EVENT_KEYUP = 'keyup'
/**
* listen for on back drop click to hide modal
*
* @param {Function} callback
* @returns {void}
*/
public onBackDropClick(callback: () => void): void {
const element = document.querySelector(`#${ID}.${CLASS_CONTAINER}`)
element.addEventListener(this.EVENT_CLICK, (event) => {
if (event.target === element) {
callback()
}
})
}
/**
* listen for on search
*
* @param {Function} callback
* @returns {void}
*/
public onSearch(callback: (keyword: string) => void): void {
const element: HTMLInputElement = document.querySelector(`#${ID} .${CLASS_INPUT}`)
// search input keyup
element.addEventListener(this.EVENT_KEYUP, (event: any) => {
const keyword = event.target.value.toLowerCase()
callback(keyword)
})
// clear icon
document.querySelector(`.${CLASS_CLEAR_ICON}`).addEventListener(this.EVENT_CLICK, () => {
element.value = ''
callback(null)
})
}
/**
* listen for on item click
*
* @param {Function} onSelected
* @param {Function} onRemove
* @returns {void}
*/
public onItemClick(
| onSelected: (item: SearchJSItem) => void,
onRemove: (item: SearchJSItem) => void,
): void { |
const items = document.querySelectorAll(`#${ID} .${CLASS_ITEM}`)
items.forEach((el) =>
// item click to select
el.addEventListener(this.EVENT_CLICK, (event: any) => {
const closeElements = event.target.closest(`.${CLASS_ITEM_CLOSE} *`)
if (event.target == closeElements) {
return
}
const parentElement = event.target.closest(`.${CLASS_ITEM}`)
const data = parentElement.getAttribute(ATTR_DATA_PAYLOAD)
onSelected(Encoder.decode(data))
}),
)
const closeItems = document.querySelectorAll(`#${ID} .${CLASS_ITEM_CLOSE}`)
closeItems.forEach((el) =>
// item click to remove from history
el.addEventListener(this.EVENT_CLICK, (event: any) => {
const parentElement = event.target.closest(`.${CLASS_ITEM_CLOSE}`)
const data = parentElement.getAttribute(ATTR_DATA_PAYLOAD)
onRemove(Encoder.decode(data))
}),
)
}
}
| src/utils/DomListener.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/utils/SearchComponent.ts",
"retrieved_chunk": " /**\n * listen on select and on remove event on item\n *\n * @return {void}\n */\n private handleItemClickListener(): void {\n this.domListener.onItemClick(\n (data: any) => {\n this.searchHistory.add(data)\n this.app.config.onSelected(data)",
"score": 32.008015924776345
},
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": " public clear(): void {\n this.db.setItem(this.storageKey, '[]')\n }\n /**\n * remove item stored\n *\n * @param {SearchJSItem} item\n * @returns {void}\n */\n public remove(item: SearchJSItem): void {",
"score": 26.231319086985383
},
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": " }\n this.db.setItem(this.storageKey, JSON.stringify(arrayItems))\n }\n /**\n * add item to history\n *\n * @param {SearchJSItem} item\n * @returns {void}\n */\n public add(item: SearchJSItem): void {",
"score": 24.184792854578006
},
{
"filename": "src/utils/SearchComponent.ts",
"retrieved_chunk": " /**\n * show item lists\n *\n * @param {Array<SearchJSItem>} items\n * @returns {void}\n */\n private showSearchResult(items: Array<SearchJSItem>): void {\n const itemInstance = new Item()\n itemInstance.renderList({\n id: ID_RESULTS,",
"score": 19.686058698006175
},
{
"filename": "src/types/index.ts",
"retrieved_chunk": " icon?: string\n placeholder?: string\n }\n onSearchDelay?: number\n onSearch?: (keyword: string) => Array<SearchJSItem> | Promise<Array<SearchJSItem>>\n onSelected: (data: SearchJSItem) => void\n}",
"score": 19.68292967096194
}
] | typescript | onSelected: (item: SearchJSItem) => void,
onRemove: (item: SearchJSItem) => void,
): void { |
import './assets/css/index.scss'
import './assets/css/github.scss'
import { DomListener } from './utils/DomListener'
import { SearchJSConfig } from './types'
import { SearchComponent } from './utils/SearchComponent'
import { SearchHistory } from './utils/SearchHistory'
import { Theme } from './themes'
export class SearchJSApp {
/**
* UI component
*
* @var {SearchComponent} component
*/
private component: SearchComponent
/**
* instance variable for singleton structure
*
* @var {SearchJSApp} _instance
*/
private static _instance: SearchJSApp
/**
* class constructor
*
* @param {SearchJSConfig} config
*/
constructor(public config: SearchJSConfig) {
this.component = new SearchComponent(this, new DomListener(), new SearchHistory(), new Theme())
this.listenKeyboardKeyPress()
}
/**
* get singleton instance
*
* @param {SearchJSConfig} config
* @returns {SearchJSApp}
*/
public static getInstance(config: SearchJSConfig): SearchJSApp {
return this._instance || (this._instance = new this(config))
}
/**
* function to open search modal
*
* @returns {void}
*/
public open(): void {
this.component.element.style.display = 'flex'
this.focusOnSearch()
}
/**
* function to close search modal
*
* @returns {void}
*/
public close(): void {
this.component.element.style.display = 'none'
}
/**
* private function to focus on search input when modal open
*
* @returns {void}
*/
private focusOnSearch(): void {
const element = document.querySelector<HTMLInputElement>('#search-js .search-input')
element.focus()
}
/**
* listen keyboard key press to open or close modal
* (ctrl + k) | (cmd + k) to open modal
* Esc to close modal
*
* @returns {void}
*/
private listenKeyboardKeyPress(): void {
const open = () => this.open()
const close = () => this.close()
window.onkeydown = function (event) {
const openKeys = (event.ctrlKey && event.key === 'k') || (event.metaKey && event.key === 'k')
if (openKeys) {
open()
}
if (event.key === 'Escape' || event.key === 'Esc') {
close()
}
}
}
}
/**
* init search js
*
* @param {SearchJSConfig} config
* @returns {SearchJSApp}
*/
const SearchJS = (config: SearchJSConfig): SearchJSApp => {
return SearchJSApp.getInstance(config)
}
declare global {
interface Window {
| SearchJS: (config: SearchJSConfig) => SearchJSApp
} |
}
window.SearchJS = SearchJS
export default SearchJS
export * from './types'
| src/index.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/themes/index.ts",
"retrieved_chunk": " return [SearchJSTheme.ThemeGithubLight, SearchJSTheme.ThemeGithubDark]\n }\n /**\n * get theme css string from config\n *\n * @param {SearchJSConfig} config\n * @returns {string}\n */\n private getTheme(config: SearchJSConfig): string {\n const defaultTheme = config.darkMode ? SearchJSTheme.ThemeDark : SearchJSTheme.ThemeLight",
"score": 24.580849211422734
},
{
"filename": "src/utils/SearchComponent.ts",
"retrieved_chunk": " */\n constructor(\n private app: SearchJSApp,\n private domListener: DomListener,\n private searchHistory: SearchHistory,\n private theme: Theme,\n ) {\n // add global css variable\n this.theme.createGlobalCssVariable(this.app.config)\n // append search element on parent element",
"score": 23.10085474809609
},
{
"filename": "src/themes/index.ts",
"retrieved_chunk": " CssHeight,\n CssPositionTop,\n CssTheme,\n CssWidth,\n} from './AvailableThemes'\nexport class Theme {\n /**\n * create global css variables base on provided theme\n *\n * @param {SearchJSConfig} config",
"score": 20.967677446783824
},
{
"filename": "src/components/Header.ts",
"retrieved_chunk": " render(config: SearchJSConfig): string {\n let icon = searchIcon(config.theme ?? DEFAULT_THEME_COLOR)\n let placeholder = 'Search'\n if (config.search?.icon) {\n icon = config.search.icon\n }\n if (config.search?.placeholder) {\n placeholder = config.search.placeholder\n }\n return `<div class=\"search-container\">",
"score": 19.036442027310297
},
{
"filename": "src/components/Header.ts",
"retrieved_chunk": "import { SearchJSConfig } from '../types'\nimport { clearIcon, searchIcon } from '../assets/Icon'\nimport { CLASS_CLEAR_ICON, CLASS_INPUT, DEFAULT_THEME_COLOR } from '../constant'\nexport class Header {\n /**\n * render header html string\n *\n * @param {SearchJSConfig} config\n * @returns {string}\n */",
"score": 18.546019815449377
}
] | typescript | SearchJS: (config: SearchJSConfig) => SearchJSApp
} |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
private domListener: DomListener,
| private searchHistory: SearchHistory,
private theme: Theme,
) { |
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
this.domListener.onSearch(async (keyword: string) => {
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string): Array<SearchJSItem> | null | undefined {
const items = this.app.config.data
return items.filter((item) => {
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
return this.app.config.element ?? document.body
}
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) {
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
icon: hashIcon(),
})
this.handleItemClickListener()
}
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
icon: historyIcon(),
})
this.handleItemClickListener()
}
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this.domListener.onItemClick(
(data: any) => {
this.searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => {
this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
}
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/index.ts",
"retrieved_chunk": " /**\n * class constructor\n *\n * @param {SearchJSConfig} config\n */\n constructor(public config: SearchJSConfig) {\n this.component = new SearchComponent(this, new DomListener(), new SearchHistory(), new Theme())\n this.listenKeyboardKeyPress()\n }\n /**",
"score": 30.188482591233647
},
{
"filename": "src/index.ts",
"retrieved_chunk": "import './assets/css/index.scss'\nimport './assets/css/github.scss'\nimport { DomListener } from './utils/DomListener'\nimport { SearchJSConfig } from './types'\nimport { SearchComponent } from './utils/SearchComponent'\nimport { SearchHistory } from './utils/SearchHistory'\nimport { Theme } from './themes'\nexport class SearchJSApp {\n /**\n * UI component",
"score": 24.49887709038035
},
{
"filename": "src/themes/index.ts",
"retrieved_chunk": " */\n private getThemeValues(theme: string): object {\n return AvailableThemes[theme]\n }\n /**\n * get theme css string\n *\n * @param {object} obj\n * @returns {string}\n */",
"score": 19.242747742861116
},
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": "import { Encoder } from './Encoder'\nexport class DomListener {\n /**\n * @var {string} EVENT_CLICK\n */\n private EVENT_CLICK = 'click'\n /**\n * @var {string} EVENT_KEYUP\n */\n private EVENT_KEYUP = 'keyup'",
"score": 18.16437237580669
},
{
"filename": "src/themes/index.ts",
"retrieved_chunk": " CssHeight,\n CssPositionTop,\n CssTheme,\n CssWidth,\n} from './AvailableThemes'\nexport class Theme {\n /**\n * create global css variables base on provided theme\n *\n * @param {SearchJSConfig} config",
"score": 15.563811345933587
}
] | typescript | private searchHistory: SearchHistory,
private theme: Theme,
) { |
import { Encoder } from './../utils/Encoder'
import { closeIcon } from '../assets/Icon'
import { ATTR_DATA_PAYLOAD, CLASS_ITEMS, CLASS_ITEM_CLOSE } from '../constant'
import { SearchJSItem } from '../types'
interface ItemComponentPayload {
item: SearchJSItem
icon: string
hideRemoveButton: boolean
}
export interface ListRenderPayload {
id: string
items?: Array<SearchJSItem>
icon: string
hideRemoveButton: boolean
notFoundLabel: string
}
export class Item {
/**
* render item list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
public renderList({ id, items, hideRemoveButton, notFoundLabel, icon }: ListRenderPayload): void {
const element = document.getElementById(id)
element.innerHTML = ``
let html = `<div class="${CLASS_ITEMS}">`
if (items.length == 0) {
html += `<div class="not-found-label">${notFoundLabel}</div>`
}
items.forEach((item) => {
html += this.render({
item,
icon,
hideRemoveButton,
})
})
html += '</div>'
element.innerHTML = html
element.style.display = 'block'
}
/**
* render items component
* @param {ItemComponentPayload} props
* @returns {string}
*/
render({ item, icon, hideRemoveButton = false }: ItemComponentPayload): string {
const dataPayload = Encoder.encode(item)
return `<div class="item" ${ATTR_DATA_PAYLOAD}='${dataPayload}'>
<div class="item-icon">${icon}</div>
<div style="flex: 1">
<div class="item-title">${item.title}</div>
${item.description ? `<div class="item-description">${item.description}</div>` : ``}
</div>${this.getCloseIcon(hideRemoveButton, dataPayload)}</div>`
}
/**
* get html string to show or hide remove button
*
* @param {boolean} hideRemoveButton
* @param {string} data
* @returns
*/
private getCloseIcon(hideRemoveButton: boolean, data: string) {
return hideRemoveButton
? ``
: `<div class='${ | CLASS_ITEM_CLOSE}' ${ATTR_DATA_PAYLOAD}='${data}'>${closeIcon()}</div>`
} |
}
| src/components/Item.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/types/index.ts",
"retrieved_chunk": "}\nexport interface SearchJSConfig {\n element?: HTMLElement\n theme?: string\n width?: string\n height?: string\n darkMode?: boolean\n positionTop?: string\n data?: Array<SearchJSItem>\n search?: {",
"score": 20.738360146389432
},
{
"filename": "src/utils/SearchComponent.ts",
"retrieved_chunk": " */\n private showHistory(items: Array<SearchJSItem>): void {\n const itemInstance = new Item()\n itemInstance.renderList({\n id: ID_HISTORIES,\n items: items,\n hideRemoveButton: false,\n notFoundLabel: 'No recent data',\n icon: historyIcon(),\n })",
"score": 18.145891682548665
},
{
"filename": "src/components/Footer.ts",
"retrieved_chunk": "export class Footer {\n /**\n * render footer html string\n *\n * @returns {string}\n */\n render(): string {\n return `<div class=\"keyboard-button\">Esc</div> <span>to close</span>`\n }\n}",
"score": 17.650812590449284
},
{
"filename": "src/utils/Encoder.ts",
"retrieved_chunk": " }\n /**\n * decode string to item\n * @param {string} data\n * @returns {SearchJSItem}\n */\n public static decode(data: string): SearchJSItem {\n return JSON.parse(unescape(window.atob(data)))\n }\n}",
"score": 17.629957423933043
},
{
"filename": "src/utils/SearchComponent.ts",
"retrieved_chunk": "<div class=\"${CLASS_MODAL_HEADER}\">${header.render(this.app.config)}</div>\n<div id=\"${ID_LOADING}\" class=\"${CLASS_MODAL_CONTENT}\">${loadingIcon()}</div>\n<div id=\"${ID_HISTORIES}\" class=\"${CLASS_MODAL_CONTENT}\"></div>\n<div id=\"${ID_RESULTS}\" class=\"${CLASS_MODAL_CONTENT}\"></div>\n<div class=\"${CLASS_MODAL_FOOTER}\">${footer.render()}</div>\n</div>\n`\n this.element = element\n return this.element\n }",
"score": 15.005309200051892
}
] | typescript | CLASS_ITEM_CLOSE}' ${ATTR_DATA_PAYLOAD}='${data}'>${closeIcon()}</div>`
} |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
private domListener: DomListener,
private searchHistory: SearchHistory,
private theme: Theme,
) {
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
this.domListener.onSearch(async (keyword: string) => {
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string): Array<SearchJSItem> | null | undefined {
const items = this.app.config.data
return items.filter((item) => {
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
return this.app.config.element ?? document.body
}
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) {
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
icon: hashIcon(),
})
this.handleItemClickListener()
}
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
icon: | historyIcon(),
})
this.handleItemClickListener()
} |
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this.domListener.onItemClick(
(data: any) => {
this.searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => {
this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
}
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " * @param {Array<SearchJSItem>} items\n * @returns {void}\n */\n public renderList({ id, items, hideRemoveButton, notFoundLabel, icon }: ListRenderPayload): void {\n const element = document.getElementById(id)\n element.innerHTML = ``\n let html = `<div class=\"${CLASS_ITEMS}\">`\n if (items.length == 0) {\n html += `<div class=\"not-found-label\">${notFoundLabel}</div>`\n }",
"score": 22.4020759245769
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " id: string\n items?: Array<SearchJSItem>\n icon: string\n hideRemoveButton: boolean\n notFoundLabel: string\n}\nexport class Item {\n /**\n * render item list\n *",
"score": 18.348039303791644
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " }\n /**\n * render items component\n * @param {ItemComponentPayload} props\n * @returns {string}\n */\n render({ item, icon, hideRemoveButton = false }: ItemComponentPayload): string {\n const dataPayload = Encoder.encode(item)\n return `<div class=\"item\" ${ATTR_DATA_PAYLOAD}='${dataPayload}'>\n<div class=\"item-icon\">${icon}</div>",
"score": 12.975019413948893
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " items.forEach((item) => {\n html += this.render({\n item,\n icon,\n hideRemoveButton,\n })\n })\n html += '</div>'\n element.innerHTML = html\n element.style.display = 'block'",
"score": 10.782836411463773
},
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": " if (!data) {\n data = '[]'\n }\n return JSON.parse(data).reverse()\n }\n /**\n * clear items stored\n *\n * @returns {void}\n */",
"score": 8.072497781040848
}
] | typescript | historyIcon(),
})
this.handleItemClickListener()
} |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
private domListener: DomListener,
private searchHistory: SearchHistory,
private theme: Theme,
) {
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
| this.domListener.onSearch(async (keyword: string) => { |
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string): Array<SearchJSItem> | null | undefined {
const items = this.app.config.data
return items.filter((item) => {
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
return this.app.config.element ?? document.body
}
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) {
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
icon: hashIcon(),
})
this.handleItemClickListener()
}
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
icon: historyIcon(),
})
this.handleItemClickListener()
}
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this.domListener.onItemClick(
(data: any) => {
this.searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => {
this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
}
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": " public onSearch(callback: (keyword: string) => void): void {\n const element: HTMLInputElement = document.querySelector(`#${ID} .${CLASS_INPUT}`)\n // search input keyup\n element.addEventListener(this.EVENT_KEYUP, (event: any) => {\n const keyword = event.target.value.toLowerCase()\n callback(keyword)\n })\n // clear icon\n document.querySelector(`.${CLASS_CLEAR_ICON}`).addEventListener(this.EVENT_CLICK, () => {\n element.value = ''",
"score": 16.390075492128396
},
{
"filename": "src/index.ts",
"retrieved_chunk": " * @returns {void}\n */\n public close(): void {\n this.component.element.style.display = 'none'\n }\n /**\n * private function to focus on search input when modal open\n *\n * @returns {void}\n */",
"score": 14.28688692414037
},
{
"filename": "src/types/index.ts",
"retrieved_chunk": " icon?: string\n placeholder?: string\n }\n onSearchDelay?: number\n onSearch?: (keyword: string) => Array<SearchJSItem> | Promise<Array<SearchJSItem>>\n onSelected: (data: SearchJSItem) => void\n}",
"score": 13.43057149343088
},
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": " callback()\n }\n })\n }\n /**\n * listen for on search\n *\n * @param {Function} callback\n * @returns {void}\n */",
"score": 10.239281493916158
},
{
"filename": "src/index.ts",
"retrieved_chunk": " *\n * @returns {void}\n */\n public open(): void {\n this.component.element.style.display = 'flex'\n this.focusOnSearch()\n }\n /**\n * function to close search modal\n *",
"score": 9.963560755769928
}
] | typescript | this.domListener.onSearch(async (keyword: string) => { |
import { SearchJSTheme } from '../types'
export const CssBackdropBackground = '--search-js-backdrop-bg'
export const CssModalBackground = '--search-js-modal-bg'
export const CssModalBoxShadow = '--search-js-modal-box-shadow'
export const CssModalFooterBoxShadow = '--search-js-modal-footer-box-shadow'
export const CssKeyboardButtonBoxShadow = '--search-js-keyboard-button-box-shadow'
export const CssKeyboardButtonBackground = '--search-js-keyboard-button-bg'
export const CssInputBackground = '--search-js-search-input-bg'
export const CssInputPlaceholderColor = '--search-js-input-placeholder-color'
export const CssItemBackground = '--search-js-item-bg'
export const CssItemBoxShadow = '--search-js-item-box-shadow'
export const CssTextColor = '--search-js-text-color'
export const CssTheme = '--search-js-theme'
export const CssWidth = '--search-js-width'
export const CssHeight = '--search-js-height'
export const CssFontFamily = '--search-js-font-family'
export const CssPositionTop = '--search-js-top'
export const AvailableThemes: any = {
[SearchJSTheme.ThemeDark]: {
[CssBackdropBackground]: 'rgba(47, 55, 69, 0.7)',
[CssModalBackground]: '#1b1b1d',
[CssModalBoxShadow]: 'inset 1px 1px 0 0 #2c2e40, 0 3px 8px 0 #000309',
[CssModalFooterBoxShadow]:
'inset 0 1px 0 0 rgba(73, 76, 106, 0.5), 0 -4px 8px 0 rgba(0, 0, 0, 0.2)',
[CssKeyboardButtonBoxShadow]:
'inset 0 -2px 0 0 #282d55, inset 0 0 1px 1px #51577d, 0 2px 2px 0 rgba(3, 4, 9, 0.3)',
[CssKeyboardButtonBackground]: 'linear-gradient(-26.5deg, transparent 0%, transparent 100%)',
[CssInputBackground]: 'black',
[CssInputPlaceholderColor]: '#aeaeae',
[CssItemBackground]: '#1c1e21',
[CssItemBoxShadow]: 'none',
[CssTextColor]: '#b3b3b3',
},
[SearchJSTheme.ThemeLight]: {
[CssBackdropBackground]: 'rgba(101, 108, 133, 0.8)',
[CssModalBackground]: '#f5f6f7',
[CssModalBoxShadow]: 'inset 1px 1px 0 0 hsla(0, 0%, 100%, 0.5), 0 3px 8px 0 #555a64',
[CssModalFooterBoxShadow]: '0 -1px 0 0 #e0e3e8, 0 -3px 6px 0 rgba(69, 98, 155, 0.12)',
[CssKeyboardButtonBoxShadow]:
'inset 0 -2px 0 0 #cdcde6, inset 0 0 1px 1px #fff, 0 1px 2px 1px rgba(30, 35, 90, 0.4)',
[CssKeyboardButtonBackground]: 'linear-gradient(-225deg, #d5dbe4, #f8f8f8)',
[CssInputBackground]: 'white',
[CssInputPlaceholderColor]: '#969faf',
[CssItemBackground]: 'white',
[CssItemBoxShadow]: '0 1px 3px 0 #d4d9e1',
[CssTextColor]: '#969faf',
},
| [SearchJSTheme.ThemeGithubDark]: { |
[CssBackdropBackground]: 'rgba(1,4,9,0.8)',
[CssModalBackground]: '#0D1116',
[CssModalBoxShadow]: 'none',
[CssModalFooterBoxShadow]: 'none',
[CssKeyboardButtonBoxShadow]: 'none',
[CssKeyboardButtonBackground]: 'none',
[CssInputBackground]: 'transparent',
[CssInputPlaceholderColor]: '#6D7681',
[CssItemBackground]: 'transparent',
[CssItemBoxShadow]: 'none',
[CssTextColor]: '#C5CED6',
[CssTheme]: 'transparent',
},
[SearchJSTheme.ThemeGithubLight]: {
[CssBackdropBackground]: 'rgba(27,31,36,0.5)',
[CssModalBackground]: '#FFFFFF',
[CssModalBoxShadow]: 'none',
[CssModalFooterBoxShadow]: 'none',
[CssKeyboardButtonBoxShadow]: 'none',
[CssKeyboardButtonBackground]: 'none',
[CssInputBackground]: 'transparent',
[CssInputPlaceholderColor]: '#6E7781',
[CssItemBackground]: 'transparent',
[CssItemBoxShadow]: 'none',
[CssTextColor]: '#1F2329',
[CssTheme]: 'transparent',
},
}
| src/themes/AvailableThemes.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/assets/Icon/index.ts",
"retrieved_chunk": "const hashIcon = (color = '#969faf') => {\n return `<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<path d=\"M10 3L8 21\" stroke=\"${color}\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n<path d=\"M16 3L14 21\" stroke=\"${color}\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n<path d=\"M3.5 9H21.5\" stroke=\"${color}\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n<path d=\"M2.5 15H20.5\" stroke=\"${color}\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n</svg>`\n}\nconst historyIcon = (color = '#969faf') => {\n return `<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">",
"score": 32.16058330638833
},
{
"filename": "src/assets/Icon/index.ts",
"retrieved_chunk": "<path d=\"M22 12C22 17.52 17.52 22 12 22C6.48 22 2 17.52 2 12C2 6.48 6.48 2 12 2C17.52 2 22 6.48 22 12Z\" stroke=\"${color}\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n<path d=\"M15.71 15.18L12.61 13.33C12.07 13.01 11.63 12.24 11.63 11.61V7.51001\" stroke=\"${color}\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n</svg>`\n}\nconst searchIcon = (color = '#000000') => {\n return `<svg fill=\"${color}\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 50 50\" width=\"25px\"><path d=\"M 21 3 C 11.601563 3 4 10.601563 4 20 C 4 29.398438 11.601563 37 21 37 C 24.355469 37 27.460938 36.015625 30.09375 34.34375 L 42.375 46.625 L 46.625 42.375 L 34.5 30.28125 C 36.679688 27.421875 38 23.878906 38 20 C 38 10.601563 30.398438 3 21 3 Z M 21 7 C 28.199219 7 34 12.800781 34 20 C 34 27.199219 28.199219 33 21 33 C 13.800781 33 8 27.199219 8 20 C 8 12.800781 13.800781 7 21 7 Z\"/></svg>`\n}\nconst closeIcon = (color = '#969faf') => {\n return `<svg width=\"35\" height=\"35\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<path d=\"M9.16998 14.83L14.83 9.17004\" stroke=\"${color}\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>",
"score": 25.26602444589893
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " * @param {Array<SearchJSItem>} items\n * @returns {void}\n */\n public renderList({ id, items, hideRemoveButton, notFoundLabel, icon }: ListRenderPayload): void {\n const element = document.getElementById(id)\n element.innerHTML = ``\n let html = `<div class=\"${CLASS_ITEMS}\">`\n if (items.length == 0) {\n html += `<div class=\"not-found-label\">${notFoundLabel}</div>`\n }",
"score": 21.660644697324116
},
{
"filename": "src/assets/Icon/index.ts",
"retrieved_chunk": "<path d=\"M14.83 14.83L9.16998 9.17004\" stroke=\"${color}\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n</svg>`\n}\nconst loadingIcon = (color = '#969faf') => {\n return `<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<path d=\"M14.55 21.67C18.84 20.54 22 16.64 22 12C22 6.48 17.56 2 12 2C5.33 2 2 7.56 2 7.56M2 7.56V3M2 7.56H4.01H6.44\" stroke=\"${color}\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n<path d=\"M2 12C2 17.52 6.48 22 12 22\" stroke=\"${color}\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-dasharray=\"3 3\"/>\n</svg>\n `\n}",
"score": 20.51231050155514
},
{
"filename": "src/assets/Icon/index.ts",
"retrieved_chunk": "const clearIcon = () => {\n return `<svg class=\"clear-svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<path d=\"M12 2C6.49 2 2 6.49 2 12C2 17.51 6.49 22 12 22C17.51 22 22 17.51 22 12C22 6.49 17.51 2 12 2ZM15.36 14.3C15.65 14.59 15.65 15.07 15.36 15.36C15.21 15.51 15.02 15.58 14.83 15.58C14.64 15.58 14.45 15.51 14.3 15.36L12 13.06L9.7 15.36C9.55 15.51 9.36 15.58 9.17 15.58C8.98 15.58 8.79 15.51 8.64 15.36C8.35 15.07 8.35 14.59 8.64 14.3L10.94 12L8.64 9.7C8.35 9.41 8.35 8.93 8.64 8.64C8.93 8.35 9.41 8.35 9.7 8.64L12 10.94L14.3 8.64C14.59 8.35 15.07 8.35 15.36 8.64C15.65 8.93 15.65 9.41 15.36 9.7L13.06 12L15.36 14.3Z\" fill=\"#969faf\"/>\n</svg>`\n}\nexport { hashIcon, searchIcon, historyIcon, closeIcon, loadingIcon, clearIcon }",
"score": 18.88717501481715
}
] | typescript | [SearchJSTheme.ThemeGithubDark]: { |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
private domListener: DomListener,
private searchHistory: SearchHistory,
private theme: | Theme,
) { |
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
this.domListener.onSearch(async (keyword: string) => {
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string): Array<SearchJSItem> | null | undefined {
const items = this.app.config.data
return items.filter((item) => {
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
return this.app.config.element ?? document.body
}
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) {
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
icon: hashIcon(),
})
this.handleItemClickListener()
}
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
icon: historyIcon(),
})
this.handleItemClickListener()
}
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this.domListener.onItemClick(
(data: any) => {
this.searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => {
this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
}
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/index.ts",
"retrieved_chunk": " /**\n * class constructor\n *\n * @param {SearchJSConfig} config\n */\n constructor(public config: SearchJSConfig) {\n this.component = new SearchComponent(this, new DomListener(), new SearchHistory(), new Theme())\n this.listenKeyboardKeyPress()\n }\n /**",
"score": 25.449229042149117
},
{
"filename": "src/index.ts",
"retrieved_chunk": "import './assets/css/index.scss'\nimport './assets/css/github.scss'\nimport { DomListener } from './utils/DomListener'\nimport { SearchJSConfig } from './types'\nimport { SearchComponent } from './utils/SearchComponent'\nimport { SearchHistory } from './utils/SearchHistory'\nimport { Theme } from './themes'\nexport class SearchJSApp {\n /**\n * UI component",
"score": 20.39683076914514
},
{
"filename": "src/themes/index.ts",
"retrieved_chunk": " */\n private getThemeValues(theme: string): object {\n return AvailableThemes[theme]\n }\n /**\n * get theme css string\n *\n * @param {object} obj\n * @returns {string}\n */",
"score": 17.948731529031782
},
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": "import { SearchJSItem } from '../types'\nexport class SearchHistory {\n /**\n * local storage\n *\n * @var {Storage} db\n */\n private db: Storage\n /**\n * max items to store in history",
"score": 15.053656361045972
},
{
"filename": "src/index.ts",
"retrieved_chunk": " *\n * @var {SearchComponent} component\n */\n private component: SearchComponent\n /**\n * instance variable for singleton structure\n *\n * @var {SearchJSApp} _instance\n */\n private static _instance: SearchJSApp",
"score": 15.001271214920994
}
] | typescript | Theme,
) { |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
private domListener: DomListener,
private searchHistory: SearchHistory,
| private theme: Theme,
) { |
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
this.domListener.onSearch(async (keyword: string) => {
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string): Array<SearchJSItem> | null | undefined {
const items = this.app.config.data
return items.filter((item) => {
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
return this.app.config.element ?? document.body
}
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) {
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
icon: hashIcon(),
})
this.handleItemClickListener()
}
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
icon: historyIcon(),
})
this.handleItemClickListener()
}
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this.domListener.onItemClick(
(data: any) => {
this.searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => {
this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
}
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/index.ts",
"retrieved_chunk": " /**\n * class constructor\n *\n * @param {SearchJSConfig} config\n */\n constructor(public config: SearchJSConfig) {\n this.component = new SearchComponent(this, new DomListener(), new SearchHistory(), new Theme())\n this.listenKeyboardKeyPress()\n }\n /**",
"score": 30.188482591233647
},
{
"filename": "src/index.ts",
"retrieved_chunk": "import './assets/css/index.scss'\nimport './assets/css/github.scss'\nimport { DomListener } from './utils/DomListener'\nimport { SearchJSConfig } from './types'\nimport { SearchComponent } from './utils/SearchComponent'\nimport { SearchHistory } from './utils/SearchHistory'\nimport { Theme } from './themes'\nexport class SearchJSApp {\n /**\n * UI component",
"score": 24.49887709038035
},
{
"filename": "src/themes/index.ts",
"retrieved_chunk": " */\n private getThemeValues(theme: string): object {\n return AvailableThemes[theme]\n }\n /**\n * get theme css string\n *\n * @param {object} obj\n * @returns {string}\n */",
"score": 19.242747742861116
},
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": "import { Encoder } from './Encoder'\nexport class DomListener {\n /**\n * @var {string} EVENT_CLICK\n */\n private EVENT_CLICK = 'click'\n /**\n * @var {string} EVENT_KEYUP\n */\n private EVENT_KEYUP = 'keyup'",
"score": 18.16437237580669
},
{
"filename": "src/themes/index.ts",
"retrieved_chunk": " CssHeight,\n CssPositionTop,\n CssTheme,\n CssWidth,\n} from './AvailableThemes'\nexport class Theme {\n /**\n * create global css variables base on provided theme\n *\n * @param {SearchJSConfig} config",
"score": 15.563811345933587
}
] | typescript | private theme: Theme,
) { |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
private domListener: DomListener,
private searchHistory: SearchHistory,
private | theme: Theme,
) { |
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
this.domListener.onSearch(async (keyword: string) => {
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string): Array<SearchJSItem> | null | undefined {
const items = this.app.config.data
return items.filter((item) => {
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
return this.app.config.element ?? document.body
}
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) {
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
icon: hashIcon(),
})
this.handleItemClickListener()
}
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
icon: historyIcon(),
})
this.handleItemClickListener()
}
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this.domListener.onItemClick(
(data: any) => {
this.searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => {
this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
}
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/index.ts",
"retrieved_chunk": " /**\n * class constructor\n *\n * @param {SearchJSConfig} config\n */\n constructor(public config: SearchJSConfig) {\n this.component = new SearchComponent(this, new DomListener(), new SearchHistory(), new Theme())\n this.listenKeyboardKeyPress()\n }\n /**",
"score": 25.449229042149117
},
{
"filename": "src/index.ts",
"retrieved_chunk": "import './assets/css/index.scss'\nimport './assets/css/github.scss'\nimport { DomListener } from './utils/DomListener'\nimport { SearchJSConfig } from './types'\nimport { SearchComponent } from './utils/SearchComponent'\nimport { SearchHistory } from './utils/SearchHistory'\nimport { Theme } from './themes'\nexport class SearchJSApp {\n /**\n * UI component",
"score": 20.39683076914514
},
{
"filename": "src/themes/index.ts",
"retrieved_chunk": " */\n private getThemeValues(theme: string): object {\n return AvailableThemes[theme]\n }\n /**\n * get theme css string\n *\n * @param {object} obj\n * @returns {string}\n */",
"score": 17.948731529031782
},
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": "import { SearchJSItem } from '../types'\nexport class SearchHistory {\n /**\n * local storage\n *\n * @var {Storage} db\n */\n private db: Storage\n /**\n * max items to store in history",
"score": 15.053656361045972
},
{
"filename": "src/index.ts",
"retrieved_chunk": " *\n * @var {SearchComponent} component\n */\n private component: SearchComponent\n /**\n * instance variable for singleton structure\n *\n * @var {SearchJSApp} _instance\n */\n private static _instance: SearchJSApp",
"score": 15.001271214920994
}
] | typescript | theme: Theme,
) { |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
private domListener: DomListener,
private searchHistory: SearchHistory,
private theme: Theme,
) {
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
this.domListener.onSearch(async (keyword: string) => {
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string): Array<SearchJSItem> | null | undefined {
const items = this.app.config.data
return items.filter((item) => {
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
return this.app.config.element ?? document.body
}
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) {
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
| icon: hashIcon(),
})
this.handleItemClickListener()
} |
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
icon: historyIcon(),
})
this.handleItemClickListener()
}
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this.domListener.onItemClick(
(data: any) => {
this.searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => {
this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
}
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " * @param {Array<SearchJSItem>} items\n * @returns {void}\n */\n public renderList({ id, items, hideRemoveButton, notFoundLabel, icon }: ListRenderPayload): void {\n const element = document.getElementById(id)\n element.innerHTML = ``\n let html = `<div class=\"${CLASS_ITEMS}\">`\n if (items.length == 0) {\n html += `<div class=\"not-found-label\">${notFoundLabel}</div>`\n }",
"score": 26.6903856137218
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " id: string\n items?: Array<SearchJSItem>\n icon: string\n hideRemoveButton: boolean\n notFoundLabel: string\n}\nexport class Item {\n /**\n * render item list\n *",
"score": 23.333366767653125
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " items.forEach((item) => {\n html += this.render({\n item,\n icon,\n hideRemoveButton,\n })\n })\n html += '</div>'\n element.innerHTML = html\n element.style.display = 'block'",
"score": 10.782836411463773
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " }\n /**\n * render items component\n * @param {ItemComponentPayload} props\n * @returns {string}\n */\n render({ item, icon, hideRemoveButton = false }: ItemComponentPayload): string {\n const dataPayload = Encoder.encode(item)\n return `<div class=\"item\" ${ATTR_DATA_PAYLOAD}='${dataPayload}'>\n<div class=\"item-icon\">${icon}</div>",
"score": 9.64313063335075
},
{
"filename": "src/index.ts",
"retrieved_chunk": " /**\n * class constructor\n *\n * @param {SearchJSConfig} config\n */\n constructor(public config: SearchJSConfig) {\n this.component = new SearchComponent(this, new DomListener(), new SearchHistory(), new Theme())\n this.listenKeyboardKeyPress()\n }\n /**",
"score": 8.143509543587559
}
] | typescript | icon: hashIcon(),
})
this.handleItemClickListener()
} |
import {
DEFAULT_HEIGHT,
DEFAULT_POSITION_TOP,
DEFAULT_THEME_COLOR,
DEFAULT_WIDTH,
} from '../constant'
import { SearchJSConfig, SearchJSTheme } from '../types'
import {
AvailableThemes,
CssFontFamily,
CssHeight,
CssPositionTop,
CssTheme,
CssWidth,
} from './AvailableThemes'
export class Theme {
/**
* create global css variables base on provided theme
*
* @param {SearchJSConfig} config
*/
public createGlobalCssVariable(config: SearchJSConfig) {
const bodyStyle = window.getComputedStyle(document.body)
const styleElement = document.createElement('style')
const cssObject = {
[CssWidth]: config.width ?? DEFAULT_WIDTH,
[CssHeight]: config.height ?? DEFAULT_HEIGHT,
[CssTheme]: config.theme ?? DEFAULT_THEME_COLOR,
[CssFontFamily]: bodyStyle.getPropertyValue('font-family'),
[CssPositionTop]: config.positionTop ?? DEFAULT_POSITION_TOP,
}
styleElement.innerHTML = `:root{${this.getCssVariables(cssObject)} ${this.getTheme(config)}}`
document.head.appendChild(styleElement)
}
/**
* get list of read made themes
*
* @returns {Array<SearchJSTheme>}
*/
| public getReadyMadeThemes(): Array<SearchJSTheme> { |
return [SearchJSTheme.ThemeGithubLight, SearchJSTheme.ThemeGithubDark]
}
/**
* get theme css string from config
*
* @param {SearchJSConfig} config
* @returns {string}
*/
private getTheme(config: SearchJSConfig): string {
const defaultTheme = config.darkMode ? SearchJSTheme.ThemeDark : SearchJSTheme.ThemeLight
const themeName = this.getReadyMadeThemes().includes(config.theme as SearchJSTheme)
? config.theme
: defaultTheme
return this.getCssVariables(this.getThemeValues(themeName))
}
/**
* get theme css variable values
*
* @param {string} theme
* @returns {object}
*/
private getThemeValues(theme: string): object {
return AvailableThemes[theme]
}
/**
* get theme css string
*
* @param {object} obj
* @returns {string}
*/
private getCssVariables(obj: object): string {
let css = ''
Object.entries(obj).forEach(([key, value]) => {
css += `${key} : ${value};`
})
return css
}
}
| src/themes/index.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": " constructor() {\n this.db = window.localStorage\n }\n /**\n * get list of items store in history\n *\n * @returns {Array<SearchJSItem> | undefined | null}\n */\n public getList(): Array<SearchJSItem> | undefined | null {\n let data = this.db.getItem(this.storageKey)",
"score": 19.527001637342405
},
{
"filename": "src/utils/SearchComponent.ts",
"retrieved_chunk": " private createElement() {\n const element = document.createElement('div')\n element.id = ID\n if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) {\n element.classList.add(this.app.config.theme)\n }\n element.classList.add(CLASS_CONTAINER)\n const footer = new Footer()\n const header = new Header()\n element.innerHTML = `<div class=\"${CLASS_MODAL}\"> ",
"score": 15.139248103328304
},
{
"filename": "src/utils/SearchComponent.ts",
"retrieved_chunk": " this.showSearchResult(items)\n }, this.app.config.onSearchDelay ?? 500)\n } else {\n this.showSearchResult(this.getItems(keyword))\n }\n })\n }\n /**\n * get list of items from config and filter with keyword from search input\n *",
"score": 14.008450864108841
},
{
"filename": "src/utils/SearchComponent.ts",
"retrieved_chunk": " * @returns {void}\n */\n private hideSearchResult(): void {\n document.getElementById(ID_RESULTS).style.display = 'none'\n }\n /**\n * show history list\n *\n * @param {Array<SearchJSItem>} items\n * @returns {void}",
"score": 11.582388183592004
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " * @param {Array<SearchJSItem>} items\n * @returns {void}\n */\n public renderList({ id, items, hideRemoveButton, notFoundLabel, icon }: ListRenderPayload): void {\n const element = document.getElementById(id)\n element.innerHTML = ``\n let html = `<div class=\"${CLASS_ITEMS}\">`\n if (items.length == 0) {\n html += `<div class=\"not-found-label\">${notFoundLabel}</div>`\n }",
"score": 10.529502879666806
}
] | typescript | public getReadyMadeThemes(): Array<SearchJSTheme> { |
/**
* A custom exception that represents a Unauthorized error.
*/
// Import required modules
import { ApiHideProperty, ApiProperty } from '@nestjs/swagger';
import { HttpException, HttpStatus } from '@nestjs/common';
// Import internal modules
import { ExceptionConstants } from './exceptions.constants';
import { IException, IHttpUnauthorizedExceptionResponse } from './exceptions.interface';
/**
* A custom exception for unauthorized access errors.
*/
export class UnauthorizedException extends HttpException {
/** The error code. */
@ApiProperty({
enum: ExceptionConstants.UnauthorizedCodes,
description: 'A unique code identifying the error.',
example: ExceptionConstants.UnauthorizedCodes.TOKEN_EXPIRED_ERROR,
})
code: number;
/** The error that caused this exception. */
@ApiHideProperty()
cause: Error;
/** The error message. */
@ApiProperty({
description: 'Message for the exception',
example: 'The authentication token provided has expired.',
})
message: string;
/** The detailed description of the error. */
@ApiProperty({
description: 'A description of the error message.',
example: 'This error message indicates that the authentication token provided with the request has expired, and therefore the server cannot verify the users identity.',
})
description: string;
/** Timestamp of the exception */
@ApiProperty({
description: 'Timestamp of the exception',
format: 'date-time',
example: '2022-12-31T23:59:59.999Z',
})
timestamp: string;
/** Trace ID of the request */
@ApiProperty({
description: 'Trace ID of the request',
example: '65b5f773-df95-4ce5-a917-62ee832fcdd0',
})
traceId: string; // Trace ID of the request
/**
* Constructs a new UnauthorizedException object.
* @param exception An object containing the exception details.
* - message: A string representing the error message.
* - cause: An object representing the cause of the error.
* - description: A string describing the error in detail.
* - code: A number representing internal status code which helpful in future for frontend
*/
constructor(exception: IException) {
| super(exception.message, HttpStatus.UNAUTHORIZED, { |
cause: exception.cause,
description: exception.description,
});
this.message = exception.message;
this.cause = exception.cause;
this.description = exception.description;
this.code = exception.code;
this.timestamp = new Date().toISOString();
}
/**
* Set the Trace ID of the BadRequestException instance.
* @param traceId A string representing the Trace ID.
*/
setTraceId = (traceId: string) => {
this.traceId = traceId;
};
/**
* Generate an HTTP response body representing the BadRequestException instance.
* @param message A string representing the message to include in the response body.
* @returns An object representing the HTTP response body.
*/
generateHttpResponseBody = (message?: string): IHttpUnauthorizedExceptionResponse => {
return {
code: this.code,
message: message || this.message,
description: this.description,
timestamp: this.timestamp,
traceId: this.traceId,
};
};
/**
* A static method to generate an exception for token expiration error.
* @param msg - An optional error message.
* @returns An instance of the UnauthorizedException class.
*/
static TOKEN_EXPIRED_ERROR = (msg?: string) => {
return new UnauthorizedException({
message: msg || 'The authentication token provided has expired.',
code: ExceptionConstants.UnauthorizedCodes.TOKEN_EXPIRED_ERROR,
});
};
/**
* A static method to generate an exception for invalid JSON web token.
* @param msg - An optional error message.
* @returns An instance of the UnauthorizedException class.
*/
static JSON_WEB_TOKEN_ERROR = (msg?: string) => {
return new UnauthorizedException({
message: msg || 'Invalid token specified.',
code: ExceptionConstants.UnauthorizedCodes.JSON_WEB_TOKEN_ERROR,
});
};
/**
* A static method to generate an exception for unauthorized access to a resource.
* @param description - An optional detailed description of the error.
* @returns An instance of the UnauthorizedException class.
*/
static UNAUTHORIZED_ACCESS = (description?: string) => {
return new UnauthorizedException({
message: 'Access to the requested resource is unauthorized.',
code: ExceptionConstants.UnauthorizedCodes.UNAUTHORIZED_ACCESS,
description,
});
};
/**
* Create a UnauthorizedException for when a resource is not found.
* @param {string} [msg] - Optional message for the exception.
* @returns {BadRequestException} - A UnauthorizedException with the appropriate error code and message.
*/
static RESOURCE_NOT_FOUND = (msg?: string) => {
return new UnauthorizedException({
message: msg || 'Resource Not Found',
code: ExceptionConstants.UnauthorizedCodes.RESOURCE_NOT_FOUND,
});
};
/**
* Create a UnauthorizedException for when a resource is not found.
* @param {string} [msg] - Optional message for the exception.
* @returns {BadRequestException} - A UnauthorizedException with the appropriate error code and message.
*/
static USER_NOT_VERIFIED = (msg?: string) => {
return new UnauthorizedException({
message: msg || 'User not verified. Please complete verification process before attempting this action.',
code: ExceptionConstants.UnauthorizedCodes.USER_NOT_VERIFIED,
});
};
/**
* A static method to generate an exception for unexpected errors.
* @param error - The error that caused this exception.
* @returns An instance of the UnauthorizedException class.
*/
static UNEXPECTED_ERROR = (error: any) => {
return new UnauthorizedException({
message: 'An unexpected error occurred while processing the request. Please try again later.',
code: ExceptionConstants.UnauthorizedCodes.UNEXPECTED_ERROR,
cause: error,
});
};
/**
* A static method to generate an exception for when a forgot or change password time previous login token needs to be re-issued.
* @param msg - An optional error message.
* @returns - An instance of the UnauthorizedException class.
*/
static REQUIRED_RE_AUTHENTICATION = (msg?: string) => {
return new UnauthorizedException({
message: msg || 'Your previous login session has been terminated due to a password change or reset. Please log in again with your new password.',
code: ExceptionConstants.UnauthorizedCodes.REQUIRED_RE_AUTHENTICATION,
});
};
/**
* A static method to generate an exception for reset password token is invalid.
* @param msg - An optional error message.
* @returns - An instance of the UnauthorizedException class.
*/
static INVALID_RESET_PASSWORD_TOKEN = (msg?: string) => {
return new UnauthorizedException({
message: msg || 'The reset password token provided is invalid. Please request a new reset password token.',
code: ExceptionConstants.UnauthorizedCodes.INVALID_RESET_PASSWORD_TOKEN,
});
};
}
| src/exceptions/unauthorized.exception.ts | piyush-kacha-nestjs-starter-kit-821cfdd | [
{
"filename": "src/exceptions/bad-request.exception.ts",
"retrieved_chunk": " * Constructs a new BadRequestException object.\n * @param exception An object containing the exception details.\n * - message: A string representing the error message.\n * - cause: An object representing the cause of the error.\n * - description: A string describing the error in detail.\n * - code: A number representing internal status code which helpful in future for frontend\n */\n constructor(exception: IException) {\n super(exception.message, HttpStatus.BAD_REQUEST, {\n cause: exception.cause,",
"score": 93.61526522714973
},
{
"filename": "src/exceptions/internal-server-error.exception.ts",
"retrieved_chunk": " * - message: A string representing the error message.\n * - cause: An object representing the cause of the error.\n * - description: A string describing the error in detail.\n * - code: A number representing internal status code which helpful in future for frontend\n */\n constructor(exception: IException) {\n super(exception.message, HttpStatus.INTERNAL_SERVER_ERROR, {\n cause: exception.cause,\n description: exception.description,\n });",
"score": 86.1193132291662
},
{
"filename": "src/exceptions/forbidden.exception.ts",
"retrieved_chunk": " * - message: A string representing the error message.\n * - cause: An object representing the cause of the error.\n * - description: A string describing the error in detail.\n * - code: A number representing internal status code which helpful in future for frontend\n */\n constructor(exception: IException) {\n super(exception.message, HttpStatus.FORBIDDEN, {\n cause: exception.cause,\n description: exception.description,\n });",
"score": 86.1193132291662
},
{
"filename": "src/exceptions/bad-request.exception.ts",
"retrieved_chunk": " * @param traceId A string representing the Trace ID.\n */\n setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the BadRequestException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */",
"score": 40.99767930592348
},
{
"filename": "src/exceptions/internal-server-error.exception.ts",
"retrieved_chunk": " setTraceId = (traceId: string) => {\n this.traceId = traceId;\n };\n /**\n * Generate an HTTP response body representing the ForbiddenException instance.\n * @param message A string representing the message to include in the response body.\n * @returns An object representing the HTTP response body.\n */\n generateHttpResponseBody = (message?: string): IHttpForbiddenExceptionResponse => {\n return {",
"score": 39.02944799530691
}
] | typescript | super(exception.message, HttpStatus.UNAUTHORIZED, { |
import {
DEFAULT_HEIGHT,
DEFAULT_POSITION_TOP,
DEFAULT_THEME_COLOR,
DEFAULT_WIDTH,
} from '../constant'
import { SearchJSConfig, SearchJSTheme } from '../types'
import {
AvailableThemes,
CssFontFamily,
CssHeight,
CssPositionTop,
CssTheme,
CssWidth,
} from './AvailableThemes'
export class Theme {
/**
* create global css variables base on provided theme
*
* @param {SearchJSConfig} config
*/
public createGlobalCssVariable(config: SearchJSConfig) {
const bodyStyle = window.getComputedStyle(document.body)
const styleElement = document.createElement('style')
const cssObject = {
[CssWidth]: config.width ?? DEFAULT_WIDTH,
[CssHeight]: config.height ?? DEFAULT_HEIGHT,
[CssTheme]: config.theme ?? DEFAULT_THEME_COLOR,
[CssFontFamily]: bodyStyle.getPropertyValue('font-family'),
[CssPositionTop]: config.positionTop ?? DEFAULT_POSITION_TOP,
}
styleElement.innerHTML = `:root{${this.getCssVariables(cssObject)} ${this.getTheme(config)}}`
document.head.appendChild(styleElement)
}
/**
* get list of read made themes
*
* @returns {Array<SearchJSTheme>}
*/
public getReadyMadeThemes() | : Array<SearchJSTheme> { |
return [SearchJSTheme.ThemeGithubLight, SearchJSTheme.ThemeGithubDark]
}
/**
* get theme css string from config
*
* @param {SearchJSConfig} config
* @returns {string}
*/
private getTheme(config: SearchJSConfig): string {
const defaultTheme = config.darkMode ? SearchJSTheme.ThemeDark : SearchJSTheme.ThemeLight
const themeName = this.getReadyMadeThemes().includes(config.theme as SearchJSTheme)
? config.theme
: defaultTheme
return this.getCssVariables(this.getThemeValues(themeName))
}
/**
* get theme css variable values
*
* @param {string} theme
* @returns {object}
*/
private getThemeValues(theme: string): object {
return AvailableThemes[theme]
}
/**
* get theme css string
*
* @param {object} obj
* @returns {string}
*/
private getCssVariables(obj: object): string {
let css = ''
Object.entries(obj).forEach(([key, value]) => {
css += `${key} : ${value};`
})
return css
}
}
| src/themes/index.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": " constructor() {\n this.db = window.localStorage\n }\n /**\n * get list of items store in history\n *\n * @returns {Array<SearchJSItem> | undefined | null}\n */\n public getList(): Array<SearchJSItem> | undefined | null {\n let data = this.db.getItem(this.storageKey)",
"score": 19.527001637342405
},
{
"filename": "src/utils/SearchComponent.ts",
"retrieved_chunk": " private createElement() {\n const element = document.createElement('div')\n element.id = ID\n if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) {\n element.classList.add(this.app.config.theme)\n }\n element.classList.add(CLASS_CONTAINER)\n const footer = new Footer()\n const header = new Header()\n element.innerHTML = `<div class=\"${CLASS_MODAL}\"> ",
"score": 15.139248103328304
},
{
"filename": "src/utils/SearchComponent.ts",
"retrieved_chunk": " this.showSearchResult(items)\n }, this.app.config.onSearchDelay ?? 500)\n } else {\n this.showSearchResult(this.getItems(keyword))\n }\n })\n }\n /**\n * get list of items from config and filter with keyword from search input\n *",
"score": 14.008450864108841
},
{
"filename": "src/utils/SearchComponent.ts",
"retrieved_chunk": " * @returns {void}\n */\n private hideSearchResult(): void {\n document.getElementById(ID_RESULTS).style.display = 'none'\n }\n /**\n * show history list\n *\n * @param {Array<SearchJSItem>} items\n * @returns {void}",
"score": 11.582388183592004
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " * @param {Array<SearchJSItem>} items\n * @returns {void}\n */\n public renderList({ id, items, hideRemoveButton, notFoundLabel, icon }: ListRenderPayload): void {\n const element = document.getElementById(id)\n element.innerHTML = ``\n let html = `<div class=\"${CLASS_ITEMS}\">`\n if (items.length == 0) {\n html += `<div class=\"not-found-label\">${notFoundLabel}</div>`\n }",
"score": 10.529502879666806
}
] | typescript | : Array<SearchJSTheme> { |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
| private domListener: DomListener,
private searchHistory: SearchHistory,
private theme: Theme,
) { |
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
this.domListener.onSearch(async (keyword: string) => {
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string): Array<SearchJSItem> | null | undefined {
const items = this.app.config.data
return items.filter((item) => {
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
return this.app.config.element ?? document.body
}
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) {
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
icon: hashIcon(),
})
this.handleItemClickListener()
}
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
icon: historyIcon(),
})
this.handleItemClickListener()
}
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this.domListener.onItemClick(
(data: any) => {
this.searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => {
this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
}
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/index.ts",
"retrieved_chunk": " /**\n * class constructor\n *\n * @param {SearchJSConfig} config\n */\n constructor(public config: SearchJSConfig) {\n this.component = new SearchComponent(this, new DomListener(), new SearchHistory(), new Theme())\n this.listenKeyboardKeyPress()\n }\n /**",
"score": 30.188482591233647
},
{
"filename": "src/index.ts",
"retrieved_chunk": "import './assets/css/index.scss'\nimport './assets/css/github.scss'\nimport { DomListener } from './utils/DomListener'\nimport { SearchJSConfig } from './types'\nimport { SearchComponent } from './utils/SearchComponent'\nimport { SearchHistory } from './utils/SearchHistory'\nimport { Theme } from './themes'\nexport class SearchJSApp {\n /**\n * UI component",
"score": 24.49887709038035
},
{
"filename": "src/themes/index.ts",
"retrieved_chunk": " */\n private getThemeValues(theme: string): object {\n return AvailableThemes[theme]\n }\n /**\n * get theme css string\n *\n * @param {object} obj\n * @returns {string}\n */",
"score": 19.242747742861116
},
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": "import { Encoder } from './Encoder'\nexport class DomListener {\n /**\n * @var {string} EVENT_CLICK\n */\n private EVENT_CLICK = 'click'\n /**\n * @var {string} EVENT_KEYUP\n */\n private EVENT_KEYUP = 'keyup'",
"score": 18.16437237580669
},
{
"filename": "src/themes/index.ts",
"retrieved_chunk": " CssHeight,\n CssPositionTop,\n CssTheme,\n CssWidth,\n} from './AvailableThemes'\nexport class Theme {\n /**\n * create global css variables base on provided theme\n *\n * @param {SearchJSConfig} config",
"score": 15.563811345933587
}
] | typescript | private domListener: DomListener,
private searchHistory: SearchHistory,
private theme: Theme,
) { |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
private domListener: DomListener,
private searchHistory: SearchHistory,
private theme: Theme,
) {
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
this.domListener.onSearch(async (keyword: string) => {
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string): Array<SearchJSItem> | null | undefined {
const items = this.app.config.data
return items.filter((item) => {
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
| return this.app.config.element ?? document.body
} |
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) {
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
icon: hashIcon(),
})
this.handleItemClickListener()
}
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
icon: historyIcon(),
})
this.handleItemClickListener()
}
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this.domListener.onItemClick(
(data: any) => {
this.searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => {
this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
}
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/index.ts",
"retrieved_chunk": " private focusOnSearch(): void {\n const element = document.querySelector<HTMLInputElement>('#search-js .search-input')\n element.focus()\n }\n /**\n * listen keyboard key press to open or close modal\n * (ctrl + k) | (cmd + k) to open modal\n * Esc to close modal\n *\n * @returns {void}",
"score": 18.89269160985544
},
{
"filename": "src/types/index.ts",
"retrieved_chunk": "}\nexport interface SearchJSConfig {\n element?: HTMLElement\n theme?: string\n width?: string\n height?: string\n darkMode?: boolean\n positionTop?: string\n data?: Array<SearchJSItem>\n search?: {",
"score": 18.642790133617016
},
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": " /**\n * listen for on back drop click to hide modal\n *\n * @param {Function} callback\n * @returns {void}\n */\n public onBackDropClick(callback: () => void): void {\n const element = document.querySelector(`#${ID}.${CLASS_CONTAINER}`)\n element.addEventListener(this.EVENT_CLICK, (event) => {\n if (event.target === element) {",
"score": 14.92429968816532
},
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": " public onSearch(callback: (keyword: string) => void): void {\n const element: HTMLInputElement = document.querySelector(`#${ID} .${CLASS_INPUT}`)\n // search input keyup\n element.addEventListener(this.EVENT_KEYUP, (event: any) => {\n const keyword = event.target.value.toLowerCase()\n callback(keyword)\n })\n // clear icon\n document.querySelector(`.${CLASS_CLEAR_ICON}`).addEventListener(this.EVENT_CLICK, () => {\n element.value = ''",
"score": 14.499243110651761
},
{
"filename": "src/index.ts",
"retrieved_chunk": " * @returns {void}\n */\n public close(): void {\n this.component.element.style.display = 'none'\n }\n /**\n * private function to focus on search input when modal open\n *\n * @returns {void}\n */",
"score": 14.156888630198251
}
] | typescript | return this.app.config.element ?? document.body
} |
import { Encoder } from './../utils/Encoder'
import { closeIcon } from '../assets/Icon'
import { ATTR_DATA_PAYLOAD, CLASS_ITEMS, CLASS_ITEM_CLOSE } from '../constant'
import { SearchJSItem } from '../types'
interface ItemComponentPayload {
item: SearchJSItem
icon: string
hideRemoveButton: boolean
}
export interface ListRenderPayload {
id: string
items?: Array<SearchJSItem>
icon: string
hideRemoveButton: boolean
notFoundLabel: string
}
export class Item {
/**
* render item list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
public renderList({ id, items, hideRemoveButton, notFoundLabel, icon }: ListRenderPayload): void {
const element = document.getElementById(id)
element.innerHTML = ``
let html = `<div class="${CLASS_ITEMS}">`
if (items.length == 0) {
html += `<div class="not-found-label">${notFoundLabel}</div>`
}
items.forEach((item) => {
html += this.render({
item,
icon,
hideRemoveButton,
})
})
html += '</div>'
element.innerHTML = html
element.style.display = 'block'
}
/**
* render items component
* @param {ItemComponentPayload} props
* @returns {string}
*/
render({ item, icon, hideRemoveButton = false }: ItemComponentPayload): string {
const dataPayload = Encoder.encode(item)
return `<div class="item" ${ATTR_DATA_PAYLOAD}='${dataPayload}'>
<div class="item-icon">${icon}</div>
<div style="flex: 1">
<div class="item-title">${item.title}</div>
${item.description ? `<div class="item-description">${item.description}</div>` : ``}
</div>${this.getCloseIcon(hideRemoveButton, dataPayload)}</div>`
}
/**
* get html string to show or hide remove button
*
* @param {boolean} hideRemoveButton
* @param {string} data
* @returns
*/
private getCloseIcon(hideRemoveButton: boolean, data: string) {
return hideRemoveButton
? ``
| : `<div class='${CLASS_ITEM_CLOSE}' ${ATTR_DATA_PAYLOAD}='${data}'>${closeIcon()}</div>`
} |
}
| src/components/Item.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/types/index.ts",
"retrieved_chunk": "}\nexport interface SearchJSConfig {\n element?: HTMLElement\n theme?: string\n width?: string\n height?: string\n darkMode?: boolean\n positionTop?: string\n data?: Array<SearchJSItem>\n search?: {",
"score": 20.738360146389432
},
{
"filename": "src/utils/SearchComponent.ts",
"retrieved_chunk": " */\n private showHistory(items: Array<SearchJSItem>): void {\n const itemInstance = new Item()\n itemInstance.renderList({\n id: ID_HISTORIES,\n items: items,\n hideRemoveButton: false,\n notFoundLabel: 'No recent data',\n icon: historyIcon(),\n })",
"score": 18.145891682548665
},
{
"filename": "src/components/Footer.ts",
"retrieved_chunk": "export class Footer {\n /**\n * render footer html string\n *\n * @returns {string}\n */\n render(): string {\n return `<div class=\"keyboard-button\">Esc</div> <span>to close</span>`\n }\n}",
"score": 17.650812590449284
},
{
"filename": "src/utils/Encoder.ts",
"retrieved_chunk": " }\n /**\n * decode string to item\n * @param {string} data\n * @returns {SearchJSItem}\n */\n public static decode(data: string): SearchJSItem {\n return JSON.parse(unescape(window.atob(data)))\n }\n}",
"score": 17.629957423933043
},
{
"filename": "src/utils/SearchComponent.ts",
"retrieved_chunk": "<div class=\"${CLASS_MODAL_HEADER}\">${header.render(this.app.config)}</div>\n<div id=\"${ID_LOADING}\" class=\"${CLASS_MODAL_CONTENT}\">${loadingIcon()}</div>\n<div id=\"${ID_HISTORIES}\" class=\"${CLASS_MODAL_CONTENT}\"></div>\n<div id=\"${ID_RESULTS}\" class=\"${CLASS_MODAL_CONTENT}\"></div>\n<div class=\"${CLASS_MODAL_FOOTER}\">${footer.render()}</div>\n</div>\n`\n this.element = element\n return this.element\n }",
"score": 15.005309200051892
}
] | typescript | : `<div class='${CLASS_ITEM_CLOSE}' ${ATTR_DATA_PAYLOAD}='${data}'>${closeIcon()}</div>`
} |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
private domListener: DomListener,
private searchHistory: SearchHistory,
private theme: Theme,
) {
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
this.domListener.onSearch(async (keyword: string) => {
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string) | : Array<SearchJSItem> | null | undefined { |
const items = this.app.config.data
return items.filter((item) => {
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
return this.app.config.element ?? document.body
}
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) {
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
icon: hashIcon(),
})
this.handleItemClickListener()
}
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
icon: historyIcon(),
})
this.handleItemClickListener()
}
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this.domListener.onItemClick(
(data: any) => {
this.searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => {
this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
}
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": " constructor() {\n this.db = window.localStorage\n }\n /**\n * get list of items store in history\n *\n * @returns {Array<SearchJSItem> | undefined | null}\n */\n public getList(): Array<SearchJSItem> | undefined | null {\n let data = this.db.getItem(this.storageKey)",
"score": 43.24249391231313
},
{
"filename": "src/types/index.ts",
"retrieved_chunk": " icon?: string\n placeholder?: string\n }\n onSearchDelay?: number\n onSearch?: (keyword: string) => Array<SearchJSItem> | Promise<Array<SearchJSItem>>\n onSelected: (data: SearchJSItem) => void\n}",
"score": 27.88532307614834
},
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": " public onSearch(callback: (keyword: string) => void): void {\n const element: HTMLInputElement = document.querySelector(`#${ID} .${CLASS_INPUT}`)\n // search input keyup\n element.addEventListener(this.EVENT_KEYUP, (event: any) => {\n const keyword = event.target.value.toLowerCase()\n callback(keyword)\n })\n // clear icon\n document.querySelector(`.${CLASS_CLEAR_ICON}`).addEventListener(this.EVENT_CLICK, () => {\n element.value = ''",
"score": 20.686418596435697
},
{
"filename": "src/themes/index.ts",
"retrieved_chunk": " }\n styleElement.innerHTML = `:root{${this.getCssVariables(cssObject)} ${this.getTheme(config)}}`\n document.head.appendChild(styleElement)\n }\n /**\n * get list of read made themes\n *\n * @returns {Array<SearchJSTheme>}\n */\n public getReadyMadeThemes(): Array<SearchJSTheme> {",
"score": 19.104311256419123
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " id: string\n items?: Array<SearchJSItem>\n icon: string\n hideRemoveButton: boolean\n notFoundLabel: string\n}\nexport class Item {\n /**\n * render item list\n *",
"score": 18.354148728861105
}
] | typescript | : Array<SearchJSItem> | null | undefined { |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
private domListener: DomListener,
private | searchHistory: SearchHistory,
private theme: Theme,
) { |
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
this.domListener.onSearch(async (keyword: string) => {
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string): Array<SearchJSItem> | null | undefined {
const items = this.app.config.data
return items.filter((item) => {
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
return this.app.config.element ?? document.body
}
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) {
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
icon: hashIcon(),
})
this.handleItemClickListener()
}
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
icon: historyIcon(),
})
this.handleItemClickListener()
}
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this.domListener.onItemClick(
(data: any) => {
this.searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => {
this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
}
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/index.ts",
"retrieved_chunk": " /**\n * class constructor\n *\n * @param {SearchJSConfig} config\n */\n constructor(public config: SearchJSConfig) {\n this.component = new SearchComponent(this, new DomListener(), new SearchHistory(), new Theme())\n this.listenKeyboardKeyPress()\n }\n /**",
"score": 25.449229042149117
},
{
"filename": "src/index.ts",
"retrieved_chunk": "import './assets/css/index.scss'\nimport './assets/css/github.scss'\nimport { DomListener } from './utils/DomListener'\nimport { SearchJSConfig } from './types'\nimport { SearchComponent } from './utils/SearchComponent'\nimport { SearchHistory } from './utils/SearchHistory'\nimport { Theme } from './themes'\nexport class SearchJSApp {\n /**\n * UI component",
"score": 20.39683076914514
},
{
"filename": "src/themes/index.ts",
"retrieved_chunk": " */\n private getThemeValues(theme: string): object {\n return AvailableThemes[theme]\n }\n /**\n * get theme css string\n *\n * @param {object} obj\n * @returns {string}\n */",
"score": 17.948731529031782
},
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": "import { SearchJSItem } from '../types'\nexport class SearchHistory {\n /**\n * local storage\n *\n * @var {Storage} db\n */\n private db: Storage\n /**\n * max items to store in history",
"score": 15.053656361045972
},
{
"filename": "src/index.ts",
"retrieved_chunk": " *\n * @var {SearchComponent} component\n */\n private component: SearchComponent\n /**\n * instance variable for singleton structure\n *\n * @var {SearchJSApp} _instance\n */\n private static _instance: SearchJSApp",
"score": 15.001271214920994
}
] | typescript | searchHistory: SearchHistory,
private theme: Theme,
) { |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
private domListener: DomListener,
private searchHistory: SearchHistory,
private theme: Theme,
) {
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
this.domListener.onSearch(async (keyword: string) => {
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string): Array<SearchJSItem> | null | undefined {
| const items = this.app.config.data
return items.filter((item) => { |
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
return this.app.config.element ?? document.body
}
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) {
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
icon: hashIcon(),
})
this.handleItemClickListener()
}
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
icon: historyIcon(),
})
this.handleItemClickListener()
}
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this.domListener.onItemClick(
(data: any) => {
this.searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => {
this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
}
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": " constructor() {\n this.db = window.localStorage\n }\n /**\n * get list of items store in history\n *\n * @returns {Array<SearchJSItem> | undefined | null}\n */\n public getList(): Array<SearchJSItem> | undefined | null {\n let data = this.db.getItem(this.storageKey)",
"score": 50.39235855537013
},
{
"filename": "src/types/index.ts",
"retrieved_chunk": " icon?: string\n placeholder?: string\n }\n onSearchDelay?: number\n onSearch?: (keyword: string) => Array<SearchJSItem> | Promise<Array<SearchJSItem>>\n onSelected: (data: SearchJSItem) => void\n}",
"score": 29.813808646609175
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " id: string\n items?: Array<SearchJSItem>\n icon: string\n hideRemoveButton: boolean\n notFoundLabel: string\n}\nexport class Item {\n /**\n * render item list\n *",
"score": 24.428034632906908
},
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": " public onSearch(callback: (keyword: string) => void): void {\n const element: HTMLInputElement = document.querySelector(`#${ID} .${CLASS_INPUT}`)\n // search input keyup\n element.addEventListener(this.EVENT_KEYUP, (event: any) => {\n const keyword = event.target.value.toLowerCase()\n callback(keyword)\n })\n // clear icon\n document.querySelector(`.${CLASS_CLEAR_ICON}`).addEventListener(this.EVENT_CLICK, () => {\n element.value = ''",
"score": 22.812315332398395
},
{
"filename": "src/themes/index.ts",
"retrieved_chunk": " }\n styleElement.innerHTML = `:root{${this.getCssVariables(cssObject)} ${this.getTheme(config)}}`\n document.head.appendChild(styleElement)\n }\n /**\n * get list of read made themes\n *\n * @returns {Array<SearchJSTheme>}\n */\n public getReadyMadeThemes(): Array<SearchJSTheme> {",
"score": 22.362300990741886
}
] | typescript | const items = this.app.config.data
return items.filter((item) => { |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
private domListener: DomListener,
private searchHistory: SearchHistory,
private theme: Theme,
) {
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
this.domListener.onSearch(async (keyword: string) => {
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string): Array<SearchJSItem> | null | undefined {
const items = this.app.config.data
return items.filter((item) => {
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
return this.app.config.element ?? document.body
}
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this.theme.getReadyMadeThemes().includes(this.app.config.theme | as SearchJSTheme)) { |
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
icon: hashIcon(),
})
this.handleItemClickListener()
}
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
icon: historyIcon(),
})
this.handleItemClickListener()
}
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this.domListener.onItemClick(
(data: any) => {
this.searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => {
this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
}
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/themes/index.ts",
"retrieved_chunk": " const themeName = this.getReadyMadeThemes().includes(config.theme as SearchJSTheme)\n ? config.theme\n : defaultTheme\n return this.getCssVariables(this.getThemeValues(themeName))\n }\n /**\n * get theme css variable values\n *\n * @param {string} theme\n * @returns {object}",
"score": 33.032027969960836
},
{
"filename": "src/themes/index.ts",
"retrieved_chunk": " */\n public createGlobalCssVariable(config: SearchJSConfig) {\n const bodyStyle = window.getComputedStyle(document.body)\n const styleElement = document.createElement('style')\n const cssObject = {\n [CssWidth]: config.width ?? DEFAULT_WIDTH,\n [CssHeight]: config.height ?? DEFAULT_HEIGHT,\n [CssTheme]: config.theme ?? DEFAULT_THEME_COLOR,\n [CssFontFamily]: bodyStyle.getPropertyValue('font-family'),\n [CssPositionTop]: config.positionTop ?? DEFAULT_POSITION_TOP,",
"score": 27.311212504685383
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " * @param {Array<SearchJSItem>} items\n * @returns {void}\n */\n public renderList({ id, items, hideRemoveButton, notFoundLabel, icon }: ListRenderPayload): void {\n const element = document.getElementById(id)\n element.innerHTML = ``\n let html = `<div class=\"${CLASS_ITEMS}\">`\n if (items.length == 0) {\n html += `<div class=\"not-found-label\">${notFoundLabel}</div>`\n }",
"score": 22.652030425629924
},
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": " /**\n * listen for on back drop click to hide modal\n *\n * @param {Function} callback\n * @returns {void}\n */\n public onBackDropClick(callback: () => void): void {\n const element = document.querySelector(`#${ID}.${CLASS_CONTAINER}`)\n element.addEventListener(this.EVENT_CLICK, (event) => {\n if (event.target === element) {",
"score": 22.210603507266875
},
{
"filename": "src/types/index.ts",
"retrieved_chunk": "}\nexport interface SearchJSConfig {\n element?: HTMLElement\n theme?: string\n width?: string\n height?: string\n darkMode?: boolean\n positionTop?: string\n data?: Array<SearchJSItem>\n search?: {",
"score": 21.718471715289837
}
] | typescript | as SearchJSTheme)) { |
import { SearchJSTheme } from '../types'
export const CssBackdropBackground = '--search-js-backdrop-bg'
export const CssModalBackground = '--search-js-modal-bg'
export const CssModalBoxShadow = '--search-js-modal-box-shadow'
export const CssModalFooterBoxShadow = '--search-js-modal-footer-box-shadow'
export const CssKeyboardButtonBoxShadow = '--search-js-keyboard-button-box-shadow'
export const CssKeyboardButtonBackground = '--search-js-keyboard-button-bg'
export const CssInputBackground = '--search-js-search-input-bg'
export const CssInputPlaceholderColor = '--search-js-input-placeholder-color'
export const CssItemBackground = '--search-js-item-bg'
export const CssItemBoxShadow = '--search-js-item-box-shadow'
export const CssTextColor = '--search-js-text-color'
export const CssTheme = '--search-js-theme'
export const CssWidth = '--search-js-width'
export const CssHeight = '--search-js-height'
export const CssFontFamily = '--search-js-font-family'
export const CssPositionTop = '--search-js-top'
export const AvailableThemes: any = {
[SearchJSTheme.ThemeDark]: {
[CssBackdropBackground]: 'rgba(47, 55, 69, 0.7)',
[CssModalBackground]: '#1b1b1d',
[CssModalBoxShadow]: 'inset 1px 1px 0 0 #2c2e40, 0 3px 8px 0 #000309',
[CssModalFooterBoxShadow]:
'inset 0 1px 0 0 rgba(73, 76, 106, 0.5), 0 -4px 8px 0 rgba(0, 0, 0, 0.2)',
[CssKeyboardButtonBoxShadow]:
'inset 0 -2px 0 0 #282d55, inset 0 0 1px 1px #51577d, 0 2px 2px 0 rgba(3, 4, 9, 0.3)',
[CssKeyboardButtonBackground]: 'linear-gradient(-26.5deg, transparent 0%, transparent 100%)',
[CssInputBackground]: 'black',
[CssInputPlaceholderColor]: '#aeaeae',
[CssItemBackground]: '#1c1e21',
[CssItemBoxShadow]: 'none',
[CssTextColor]: '#b3b3b3',
},
| [SearchJSTheme.ThemeLight]: { |
[CssBackdropBackground]: 'rgba(101, 108, 133, 0.8)',
[CssModalBackground]: '#f5f6f7',
[CssModalBoxShadow]: 'inset 1px 1px 0 0 hsla(0, 0%, 100%, 0.5), 0 3px 8px 0 #555a64',
[CssModalFooterBoxShadow]: '0 -1px 0 0 #e0e3e8, 0 -3px 6px 0 rgba(69, 98, 155, 0.12)',
[CssKeyboardButtonBoxShadow]:
'inset 0 -2px 0 0 #cdcde6, inset 0 0 1px 1px #fff, 0 1px 2px 1px rgba(30, 35, 90, 0.4)',
[CssKeyboardButtonBackground]: 'linear-gradient(-225deg, #d5dbe4, #f8f8f8)',
[CssInputBackground]: 'white',
[CssInputPlaceholderColor]: '#969faf',
[CssItemBackground]: 'white',
[CssItemBoxShadow]: '0 1px 3px 0 #d4d9e1',
[CssTextColor]: '#969faf',
},
[SearchJSTheme.ThemeGithubDark]: {
[CssBackdropBackground]: 'rgba(1,4,9,0.8)',
[CssModalBackground]: '#0D1116',
[CssModalBoxShadow]: 'none',
[CssModalFooterBoxShadow]: 'none',
[CssKeyboardButtonBoxShadow]: 'none',
[CssKeyboardButtonBackground]: 'none',
[CssInputBackground]: 'transparent',
[CssInputPlaceholderColor]: '#6D7681',
[CssItemBackground]: 'transparent',
[CssItemBoxShadow]: 'none',
[CssTextColor]: '#C5CED6',
[CssTheme]: 'transparent',
},
[SearchJSTheme.ThemeGithubLight]: {
[CssBackdropBackground]: 'rgba(27,31,36,0.5)',
[CssModalBackground]: '#FFFFFF',
[CssModalBoxShadow]: 'none',
[CssModalFooterBoxShadow]: 'none',
[CssKeyboardButtonBoxShadow]: 'none',
[CssKeyboardButtonBackground]: 'none',
[CssInputBackground]: 'transparent',
[CssInputPlaceholderColor]: '#6E7781',
[CssItemBackground]: 'transparent',
[CssItemBoxShadow]: 'none',
[CssTextColor]: '#1F2329',
[CssTheme]: 'transparent',
},
}
| src/themes/AvailableThemes.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/assets/Icon/index.ts",
"retrieved_chunk": "const hashIcon = (color = '#969faf') => {\n return `<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<path d=\"M10 3L8 21\" stroke=\"${color}\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n<path d=\"M16 3L14 21\" stroke=\"${color}\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n<path d=\"M3.5 9H21.5\" stroke=\"${color}\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n<path d=\"M2.5 15H20.5\" stroke=\"${color}\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n</svg>`\n}\nconst historyIcon = (color = '#969faf') => {\n return `<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">",
"score": 29.45096051143949
},
{
"filename": "src/assets/Icon/index.ts",
"retrieved_chunk": "<path d=\"M22 12C22 17.52 17.52 22 12 22C6.48 22 2 17.52 2 12C2 6.48 6.48 2 12 2C17.52 2 22 6.48 22 12Z\" stroke=\"${color}\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n<path d=\"M15.71 15.18L12.61 13.33C12.07 13.01 11.63 12.24 11.63 11.61V7.51001\" stroke=\"${color}\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n</svg>`\n}\nconst searchIcon = (color = '#000000') => {\n return `<svg fill=\"${color}\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 50 50\" width=\"25px\"><path d=\"M 21 3 C 11.601563 3 4 10.601563 4 20 C 4 29.398438 11.601563 37 21 37 C 24.355469 37 27.460938 36.015625 30.09375 34.34375 L 42.375 46.625 L 46.625 42.375 L 34.5 30.28125 C 36.679688 27.421875 38 23.878906 38 20 C 38 10.601563 30.398438 3 21 3 Z M 21 7 C 28.199219 7 34 12.800781 34 20 C 34 27.199219 28.199219 33 21 33 C 13.800781 33 8 27.199219 8 20 C 8 12.800781 13.800781 7 21 7 Z\"/></svg>`\n}\nconst closeIcon = (color = '#969faf') => {\n return `<svg width=\"35\" height=\"35\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<path d=\"M9.16998 14.83L14.83 9.17004\" stroke=\"${color}\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>",
"score": 25.88084039410769
},
{
"filename": "src/assets/Icon/index.ts",
"retrieved_chunk": "<path d=\"M14.83 14.83L9.16998 9.17004\" stroke=\"${color}\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n</svg>`\n}\nconst loadingIcon = (color = '#969faf') => {\n return `<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<path d=\"M14.55 21.67C18.84 20.54 22 16.64 22 12C22 6.48 17.56 2 12 2C5.33 2 2 7.56 2 7.56M2 7.56V3M2 7.56H4.01H6.44\" stroke=\"${color}\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>\n<path d=\"M2 12C2 17.52 6.48 22 12 22\" stroke=\"${color}\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-dasharray=\"3 3\"/>\n</svg>\n `\n}",
"score": 25.03997180155076
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " * @param {Array<SearchJSItem>} items\n * @returns {void}\n */\n public renderList({ id, items, hideRemoveButton, notFoundLabel, icon }: ListRenderPayload): void {\n const element = document.getElementById(id)\n element.innerHTML = ``\n let html = `<div class=\"${CLASS_ITEMS}\">`\n if (items.length == 0) {\n html += `<div class=\"not-found-label\">${notFoundLabel}</div>`\n }",
"score": 21.660644697324116
},
{
"filename": "src/assets/Icon/index.ts",
"retrieved_chunk": "const clearIcon = () => {\n return `<svg class=\"clear-svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n<path d=\"M12 2C6.49 2 2 6.49 2 12C2 17.51 6.49 22 12 22C17.51 22 22 17.51 22 12C22 6.49 17.51 2 12 2ZM15.36 14.3C15.65 14.59 15.65 15.07 15.36 15.36C15.21 15.51 15.02 15.58 14.83 15.58C14.64 15.58 14.45 15.51 14.3 15.36L12 13.06L9.7 15.36C9.55 15.51 9.36 15.58 9.17 15.58C8.98 15.58 8.79 15.51 8.64 15.36C8.35 15.07 8.35 14.59 8.64 14.3L10.94 12L8.64 9.7C8.35 9.41 8.35 8.93 8.64 8.64C8.93 8.35 9.41 8.35 9.7 8.64L12 10.94L14.3 8.64C14.59 8.35 15.07 8.35 15.36 8.64C15.65 8.93 15.65 9.41 15.36 9.7L13.06 12L15.36 14.3Z\" fill=\"#969faf\"/>\n</svg>`\n}\nexport { hashIcon, searchIcon, historyIcon, closeIcon, loadingIcon, clearIcon }",
"score": 20.70098990405322
}
] | typescript | [SearchJSTheme.ThemeLight]: { |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
private domListener: DomListener,
private searchHistory: SearchHistory,
private theme: Theme,
) {
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
this.domListener.onSearch(async (keyword: string) => {
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string): Array<SearchJSItem> | null | undefined {
const items = this.app.config.data
return items.filter((item) => {
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
return this.app.config.element ?? document.body
}
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this.theme.getReadyMadeThemes(). | includes(this.app.config.theme as SearchJSTheme)) { |
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
icon: hashIcon(),
})
this.handleItemClickListener()
}
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
icon: historyIcon(),
})
this.handleItemClickListener()
}
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this.domListener.onItemClick(
(data: any) => {
this.searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => {
this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
}
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/themes/index.ts",
"retrieved_chunk": " const themeName = this.getReadyMadeThemes().includes(config.theme as SearchJSTheme)\n ? config.theme\n : defaultTheme\n return this.getCssVariables(this.getThemeValues(themeName))\n }\n /**\n * get theme css variable values\n *\n * @param {string} theme\n * @returns {object}",
"score": 33.032027969960836
},
{
"filename": "src/themes/index.ts",
"retrieved_chunk": " */\n public createGlobalCssVariable(config: SearchJSConfig) {\n const bodyStyle = window.getComputedStyle(document.body)\n const styleElement = document.createElement('style')\n const cssObject = {\n [CssWidth]: config.width ?? DEFAULT_WIDTH,\n [CssHeight]: config.height ?? DEFAULT_HEIGHT,\n [CssTheme]: config.theme ?? DEFAULT_THEME_COLOR,\n [CssFontFamily]: bodyStyle.getPropertyValue('font-family'),\n [CssPositionTop]: config.positionTop ?? DEFAULT_POSITION_TOP,",
"score": 27.311212504685383
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " * @param {Array<SearchJSItem>} items\n * @returns {void}\n */\n public renderList({ id, items, hideRemoveButton, notFoundLabel, icon }: ListRenderPayload): void {\n const element = document.getElementById(id)\n element.innerHTML = ``\n let html = `<div class=\"${CLASS_ITEMS}\">`\n if (items.length == 0) {\n html += `<div class=\"not-found-label\">${notFoundLabel}</div>`\n }",
"score": 22.652030425629924
},
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": " /**\n * listen for on back drop click to hide modal\n *\n * @param {Function} callback\n * @returns {void}\n */\n public onBackDropClick(callback: () => void): void {\n const element = document.querySelector(`#${ID}.${CLASS_CONTAINER}`)\n element.addEventListener(this.EVENT_CLICK, (event) => {\n if (event.target === element) {",
"score": 22.210603507266875
},
{
"filename": "src/types/index.ts",
"retrieved_chunk": "}\nexport interface SearchJSConfig {\n element?: HTMLElement\n theme?: string\n width?: string\n height?: string\n darkMode?: boolean\n positionTop?: string\n data?: Array<SearchJSItem>\n search?: {",
"score": 21.718471715289837
}
] | typescript | includes(this.app.config.theme as SearchJSTheme)) { |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
private domListener: DomListener,
private searchHistory: SearchHistory,
private theme: Theme,
) {
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
this.domListener.onSearch(async (keyword: string) => {
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string): Array<SearchJSItem> | null | undefined {
const items = this.app.config.data
return items.filter((item) => {
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
return this.app.config.element ?? document.body
}
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) {
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
icon: hashIcon(),
})
this.handleItemClickListener()
}
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
| icon: historyIcon(),
})
this.handleItemClickListener()
} |
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this.domListener.onItemClick(
(data: any) => {
this.searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => {
this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
}
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " id: string\n items?: Array<SearchJSItem>\n icon: string\n hideRemoveButton: boolean\n notFoundLabel: string\n}\nexport class Item {\n /**\n * render item list\n *",
"score": 23.333366767653125
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " * @param {Array<SearchJSItem>} items\n * @returns {void}\n */\n public renderList({ id, items, hideRemoveButton, notFoundLabel, icon }: ListRenderPayload): void {\n const element = document.getElementById(id)\n element.innerHTML = ``\n let html = `<div class=\"${CLASS_ITEMS}\">`\n if (items.length == 0) {\n html += `<div class=\"not-found-label\">${notFoundLabel}</div>`\n }",
"score": 23.020111621367874
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " }\n /**\n * render items component\n * @param {ItemComponentPayload} props\n * @returns {string}\n */\n render({ item, icon, hideRemoveButton = false }: ItemComponentPayload): string {\n const dataPayload = Encoder.encode(item)\n return `<div class=\"item\" ${ATTR_DATA_PAYLOAD}='${dataPayload}'>\n<div class=\"item-icon\">${icon}</div>",
"score": 13.649680434728467
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " items.forEach((item) => {\n html += this.render({\n item,\n icon,\n hideRemoveButton,\n })\n })\n html += '</div>'\n element.innerHTML = html\n element.style.display = 'block'",
"score": 10.782836411463773
},
{
"filename": "src/index.ts",
"retrieved_chunk": " /**\n * class constructor\n *\n * @param {SearchJSConfig} config\n */\n constructor(public config: SearchJSConfig) {\n this.component = new SearchComponent(this, new DomListener(), new SearchHistory(), new Theme())\n this.listenKeyboardKeyPress()\n }\n /**",
"score": 8.143509543587559
}
] | typescript | icon: historyIcon(),
})
this.handleItemClickListener()
} |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
private domListener: DomListener,
private searchHistory: SearchHistory,
private theme: Theme,
) {
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
this.domListener.onSearch(async (keyword: string) => {
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string): Array<SearchJSItem> | null | undefined {
const items = this.app.config.data
return items.filter((item) => {
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
return this.app.config.element ?? document.body
}
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) {
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
icon | : hashIcon(),
})
this.handleItemClickListener()
} |
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
icon: historyIcon(),
})
this.handleItemClickListener()
}
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this.domListener.onItemClick(
(data: any) => {
this.searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => {
this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
}
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " * @param {Array<SearchJSItem>} items\n * @returns {void}\n */\n public renderList({ id, items, hideRemoveButton, notFoundLabel, icon }: ListRenderPayload): void {\n const element = document.getElementById(id)\n element.innerHTML = ``\n let html = `<div class=\"${CLASS_ITEMS}\">`\n if (items.length == 0) {\n html += `<div class=\"not-found-label\">${notFoundLabel}</div>`\n }",
"score": 26.072349916930825
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " id: string\n items?: Array<SearchJSItem>\n icon: string\n hideRemoveButton: boolean\n notFoundLabel: string\n}\nexport class Item {\n /**\n * render item list\n *",
"score": 18.348039303791644
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " items.forEach((item) => {\n html += this.render({\n item,\n icon,\n hideRemoveButton,\n })\n })\n html += '</div>'\n element.innerHTML = html\n element.style.display = 'block'",
"score": 10.782836411463773
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " }\n /**\n * render items component\n * @param {ItemComponentPayload} props\n * @returns {string}\n */\n render({ item, icon, hideRemoveButton = false }: ItemComponentPayload): string {\n const dataPayload = Encoder.encode(item)\n return `<div class=\"item\" ${ATTR_DATA_PAYLOAD}='${dataPayload}'>\n<div class=\"item-icon\">${icon}</div>",
"score": 8.968469612571177
},
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": " public onItemClick(\n onSelected: (item: SearchJSItem) => void,\n onRemove: (item: SearchJSItem) => void,\n ): void {\n const items = document.querySelectorAll(`#${ID} .${CLASS_ITEM}`)\n items.forEach((el) =>\n // item click to select\n el.addEventListener(this.EVENT_CLICK, (event: any) => {\n const closeElements = event.target.closest(`.${CLASS_ITEM_CLOSE} *`)\n if (event.target == closeElements) {",
"score": 5.901631306654025
}
] | typescript | : hashIcon(),
})
this.handleItemClickListener()
} |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
private domListener: DomListener,
private searchHistory: SearchHistory,
private theme: Theme,
) {
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
this.domListener.onSearch(async (keyword: string) => {
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string): Array<SearchJSItem> | null | undefined {
const items = this.app.config.data
return items.filter((item) => {
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
return this.app.config.element ?? document.body
}
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) {
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
icon: hashIcon(),
})
this.handleItemClickListener()
}
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
icon: historyIcon(),
})
this.handleItemClickListener()
}
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this.domListener.onItemClick(
(data: any) => {
this.searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => {
| this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
} |
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": " el.addEventListener(this.EVENT_CLICK, (event: any) => {\n const parentElement = event.target.closest(`.${CLASS_ITEM_CLOSE}`)\n const data = parentElement.getAttribute(ATTR_DATA_PAYLOAD)\n onRemove(Encoder.decode(data))\n }),\n )\n }\n}",
"score": 23.941745247060414
},
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": " let data = this.db.getItem(this.storageKey)\n if (!data) {\n data = '[]'\n }\n const arrayItems = JSON.parse(data)\n if (arrayItems.length == this.maxItems) {\n arrayItems.pop()\n }\n const findItem = arrayItems.find((d: SearchJSItem) => {\n return JSON.stringify(d) == JSON.stringify(item)",
"score": 21.316482576050852
},
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": " let data = this.db.getItem(this.storageKey)\n if (!data) {\n data = '[]'\n }\n const arrayItems = JSON.parse(data)\n const index = arrayItems.findIndex((d: SearchJSItem) => {\n return JSON.stringify(d) == JSON.stringify(item)\n })\n if (index != -1) {\n arrayItems.splice(index, 1)",
"score": 20.23913293783088
},
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": " constructor() {\n this.db = window.localStorage\n }\n /**\n * get list of items store in history\n *\n * @returns {Array<SearchJSItem> | undefined | null}\n */\n public getList(): Array<SearchJSItem> | undefined | null {\n let data = this.db.getItem(this.storageKey)",
"score": 20.140112555249033
},
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": " return\n }\n const parentElement = event.target.closest(`.${CLASS_ITEM}`)\n const data = parentElement.getAttribute(ATTR_DATA_PAYLOAD)\n onSelected(Encoder.decode(data))\n }),\n )\n const closeItems = document.querySelectorAll(`#${ID} .${CLASS_ITEM_CLOSE}`)\n closeItems.forEach((el) =>\n // item click to remove from history",
"score": 17.128173689933767
}
] | typescript | this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
} |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
private domListener: DomListener,
private searchHistory: SearchHistory,
private theme: Theme,
) {
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
this.domListener.onSearch(async (keyword: string) => {
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string): Array<SearchJSItem> | null | undefined {
const items = this.app.config.data
return items.filter((item) => {
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
return this.app.config.element ?? document.body
}
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this | .theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) { |
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
icon: hashIcon(),
})
this.handleItemClickListener()
}
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
icon: historyIcon(),
})
this.handleItemClickListener()
}
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this.domListener.onItemClick(
(data: any) => {
this.searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => {
this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
}
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/themes/index.ts",
"retrieved_chunk": " const themeName = this.getReadyMadeThemes().includes(config.theme as SearchJSTheme)\n ? config.theme\n : defaultTheme\n return this.getCssVariables(this.getThemeValues(themeName))\n }\n /**\n * get theme css variable values\n *\n * @param {string} theme\n * @returns {object}",
"score": 33.032027969960836
},
{
"filename": "src/themes/index.ts",
"retrieved_chunk": " */\n public createGlobalCssVariable(config: SearchJSConfig) {\n const bodyStyle = window.getComputedStyle(document.body)\n const styleElement = document.createElement('style')\n const cssObject = {\n [CssWidth]: config.width ?? DEFAULT_WIDTH,\n [CssHeight]: config.height ?? DEFAULT_HEIGHT,\n [CssTheme]: config.theme ?? DEFAULT_THEME_COLOR,\n [CssFontFamily]: bodyStyle.getPropertyValue('font-family'),\n [CssPositionTop]: config.positionTop ?? DEFAULT_POSITION_TOP,",
"score": 27.311212504685383
},
{
"filename": "src/components/Item.ts",
"retrieved_chunk": " * @param {Array<SearchJSItem>} items\n * @returns {void}\n */\n public renderList({ id, items, hideRemoveButton, notFoundLabel, icon }: ListRenderPayload): void {\n const element = document.getElementById(id)\n element.innerHTML = ``\n let html = `<div class=\"${CLASS_ITEMS}\">`\n if (items.length == 0) {\n html += `<div class=\"not-found-label\">${notFoundLabel}</div>`\n }",
"score": 22.652030425629924
},
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": " /**\n * listen for on back drop click to hide modal\n *\n * @param {Function} callback\n * @returns {void}\n */\n public onBackDropClick(callback: () => void): void {\n const element = document.querySelector(`#${ID}.${CLASS_CONTAINER}`)\n element.addEventListener(this.EVENT_CLICK, (event) => {\n if (event.target === element) {",
"score": 22.210603507266875
},
{
"filename": "src/types/index.ts",
"retrieved_chunk": "}\nexport interface SearchJSConfig {\n element?: HTMLElement\n theme?: string\n width?: string\n height?: string\n darkMode?: boolean\n positionTop?: string\n data?: Array<SearchJSItem>\n search?: {",
"score": 21.718471715289837
}
] | typescript | .theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) { |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
private domListener: DomListener,
private searchHistory: SearchHistory,
private theme: Theme,
) {
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
this.domListener.onSearch(async (keyword: string) => {
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string): Array<SearchJSItem> | null | undefined {
const items = this.app.config.data
return items.filter((item) => {
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
return this.app.config.element ?? document.body
}
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) {
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
icon: hashIcon(),
})
this.handleItemClickListener()
}
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
icon: historyIcon(),
})
this.handleItemClickListener()
}
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this.domListener.onItemClick(
(data: any) => {
this | .searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => { |
this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
}
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": " el.addEventListener(this.EVENT_CLICK, (event: any) => {\n const parentElement = event.target.closest(`.${CLASS_ITEM_CLOSE}`)\n const data = parentElement.getAttribute(ATTR_DATA_PAYLOAD)\n onRemove(Encoder.decode(data))\n }),\n )\n }\n}",
"score": 19.22871528482197
},
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": " public onItemClick(\n onSelected: (item: SearchJSItem) => void,\n onRemove: (item: SearchJSItem) => void,\n ): void {\n const items = document.querySelectorAll(`#${ID} .${CLASS_ITEM}`)\n items.forEach((el) =>\n // item click to select\n el.addEventListener(this.EVENT_CLICK, (event: any) => {\n const closeElements = event.target.closest(`.${CLASS_ITEM_CLOSE} *`)\n if (event.target == closeElements) {",
"score": 17.66704878392793
},
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": " if (!data) {\n data = '[]'\n }\n return JSON.parse(data).reverse()\n }\n /**\n * clear items stored\n *\n * @returns {void}\n */",
"score": 16.692210841339516
},
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": " let data = this.db.getItem(this.storageKey)\n if (!data) {\n data = '[]'\n }\n const arrayItems = JSON.parse(data)\n if (arrayItems.length == this.maxItems) {\n arrayItems.pop()\n }\n const findItem = arrayItems.find((d: SearchJSItem) => {\n return JSON.stringify(d) == JSON.stringify(item)",
"score": 16.374956757440312
},
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": " let data = this.db.getItem(this.storageKey)\n if (!data) {\n data = '[]'\n }\n const arrayItems = JSON.parse(data)\n const index = arrayItems.findIndex((d: SearchJSItem) => {\n return JSON.stringify(d) == JSON.stringify(item)\n })\n if (index != -1) {\n arrayItems.splice(index, 1)",
"score": 15.728546974508332
}
] | typescript | .searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => { |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
private domListener: DomListener,
private searchHistory: SearchHistory,
private theme: Theme,
) {
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
this.domListener.onSearch(async (keyword: string) => {
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string): Array<SearchJSItem> | null | undefined {
const items = this.app.config.data
return items.filter((item) => {
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
return this.app.config.element ?? document.body
}
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) {
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
icon: hashIcon(),
})
this.handleItemClickListener()
}
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
icon: historyIcon(),
})
this.handleItemClickListener()
}
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this.domListener.onItemClick(
(data: any) => {
this.searchHistory.add(data)
this.app | .config.onSelected(data)
},
(data: any) => { |
this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
}
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": " el.addEventListener(this.EVENT_CLICK, (event: any) => {\n const parentElement = event.target.closest(`.${CLASS_ITEM_CLOSE}`)\n const data = parentElement.getAttribute(ATTR_DATA_PAYLOAD)\n onRemove(Encoder.decode(data))\n }),\n )\n }\n}",
"score": 19.22871528482197
},
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": " public onItemClick(\n onSelected: (item: SearchJSItem) => void,\n onRemove: (item: SearchJSItem) => void,\n ): void {\n const items = document.querySelectorAll(`#${ID} .${CLASS_ITEM}`)\n items.forEach((el) =>\n // item click to select\n el.addEventListener(this.EVENT_CLICK, (event: any) => {\n const closeElements = event.target.closest(`.${CLASS_ITEM_CLOSE} *`)\n if (event.target == closeElements) {",
"score": 17.66704878392793
},
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": " if (!data) {\n data = '[]'\n }\n return JSON.parse(data).reverse()\n }\n /**\n * clear items stored\n *\n * @returns {void}\n */",
"score": 16.692210841339516
},
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": " let data = this.db.getItem(this.storageKey)\n if (!data) {\n data = '[]'\n }\n const arrayItems = JSON.parse(data)\n if (arrayItems.length == this.maxItems) {\n arrayItems.pop()\n }\n const findItem = arrayItems.find((d: SearchJSItem) => {\n return JSON.stringify(d) == JSON.stringify(item)",
"score": 16.374956757440312
},
{
"filename": "src/utils/SearchHistory.ts",
"retrieved_chunk": " let data = this.db.getItem(this.storageKey)\n if (!data) {\n data = '[]'\n }\n const arrayItems = JSON.parse(data)\n const index = arrayItems.findIndex((d: SearchJSItem) => {\n return JSON.stringify(d) == JSON.stringify(item)\n })\n if (index != -1) {\n arrayItems.splice(index, 1)",
"score": 15.728546974508332
}
] | typescript | .config.onSelected(data)
},
(data: any) => { |
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'
import { Footer } from '../components/Footer'
import { Header } from '../components/Header'
import { Item } from '../components/Item'
import { DomListener } from './DomListener'
import { SearchHistory } from './SearchHistory'
import { SearchJSApp } from '..'
import { SearchJSItem, SearchJSTheme } from '../types'
import { Theme } from '../themes'
import {
CLASS_CONTAINER,
ID,
CLASS_MODAL,
ID_HISTORIES,
ID_LOADING,
ID_RESULTS,
CLASS_MODAL_HEADER,
CLASS_MODAL_FOOTER,
CLASS_MODAL_CONTENT,
} from '../constant'
export class SearchComponent {
/**
* the entire search js element
*
* @var {HTMLElement} element
*/
public element: HTMLElement
/**
* timer placeholder to handle search
*
* @var {number} searchTimer
*/
private searchTimer?: number
/**
* class constructor
*
* @param {SearchJSApp} app
* @param {DomListener} domListener
* @param {SearchHistory} searchHistory
* @param {Theme} theme
*/
constructor(
private app: SearchJSApp,
private domListener: DomListener,
private searchHistory: SearchHistory,
private theme: Theme,
) {
// add global css variable
this.theme.createGlobalCssVariable(this.app.config)
// append search element on parent element
this.getParentElement().appendChild(this.createElement())
// render initial data list
this.showHistory(this.searchHistory.getList())
this.domListener.onBackDropClick(() => {
this.app.close()
})
this.handleOnSearch()
}
/**
* handle search and show list on result
*
* @returns {void}
*/
private handleOnSearch(): void {
this.domListener.onSearch(async (keyword: string) => {
if (!keyword) {
clearTimeout(this.searchTimer)
this.hideLoading()
this.showHistory(this.searchHistory.getList())
this.hideSearchResult()
return
}
this.hideHistories()
this.hideSearchResult()
if (this.app.config.onSearch) {
this.showLoading()
clearTimeout(this.searchTimer)
this.searchTimer = setTimeout(async () => {
const items = await this.app.config.onSearch(keyword)
this.hideLoading()
this.showSearchResult(items)
}, this.app.config.onSearchDelay ?? 500)
} else {
this.showSearchResult(this.getItems(keyword))
}
})
}
/**
* get list of items from config and filter with keyword from search input
*
* @param {string} keyword
* @returns {Array<SearchJSItem> | null | undefined}
*/
private getItems(keyword: string): Array<SearchJSItem> | null | undefined {
const items = this.app.config.data
return items.filter((item) => {
return (
(item.title && item.title.toLowerCase().includes(keyword)) ||
(item.description && item.description.toLowerCase().includes(keyword))
)
})
}
/**
* get parent element to append search-js element
*
* @returns {HTMLElement}
*/
private getParentElement(): HTMLElement {
return this.app.config.element ?? document.body
}
private createElement() {
const element = document.createElement('div')
element.id = ID
if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) {
element.classList.add(this.app.config.theme)
}
element.classList.add(CLASS_CONTAINER)
const footer = new Footer()
const header = new Header()
element.innerHTML = `<div class="${CLASS_MODAL}">
<div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div>
<div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div>
<div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div>
<div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div>
<div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div>
</div>
`
this.element = element
return this.element
}
/**
* show item lists
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showSearchResult(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_RESULTS,
items: items,
hideRemoveButton: true,
notFoundLabel: 'No match found',
icon: hashIcon(),
})
this.handleItemClickListener()
}
/**
* hide search result
*
* @returns {void}
*/
private hideSearchResult(): void {
document.getElementById(ID_RESULTS).style.display = 'none'
}
/**
* show history list
*
* @param {Array<SearchJSItem>} items
* @returns {void}
*/
private showHistory(items: Array<SearchJSItem>): void {
const itemInstance = new Item()
itemInstance.renderList({
id: ID_HISTORIES,
items: items,
hideRemoveButton: false,
notFoundLabel: 'No recent data',
icon: historyIcon(),
})
this.handleItemClickListener()
}
/**
* hide history
*
* @returns {void}
*/
private hideHistories(): void {
document.getElementById(ID_HISTORIES).style.display = 'none'
}
/**
* listen on select and on remove event on item
*
* @return {void}
*/
private handleItemClickListener(): void {
this. | domListener.onItemClick(
(data: any) => { |
this.searchHistory.add(data)
this.app.config.onSelected(data)
},
(data: any) => {
this.searchHistory.remove(data)
this.showHistory(this.searchHistory.getList())
},
)
}
/**
* show loading
*
* @returns {void}
*/
private showLoading(): void {
document.getElementById(ID_LOADING).style.display = 'flex'
}
/**
* hide loading
*
* @returns {void}
*/
private hideLoading(): void {
document.getElementById(ID_LOADING).style.display = 'none'
}
}
| src/utils/SearchComponent.ts | necessarylion-search-js-74bfb45 | [
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": " public onItemClick(\n onSelected: (item: SearchJSItem) => void,\n onRemove: (item: SearchJSItem) => void,\n ): void {\n const items = document.querySelectorAll(`#${ID} .${CLASS_ITEM}`)\n items.forEach((el) =>\n // item click to select\n el.addEventListener(this.EVENT_CLICK, (event: any) => {\n const closeElements = event.target.closest(`.${CLASS_ITEM_CLOSE} *`)\n if (event.target == closeElements) {",
"score": 19.947308676524386
},
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": " /**\n * listen for on back drop click to hide modal\n *\n * @param {Function} callback\n * @returns {void}\n */\n public onBackDropClick(callback: () => void): void {\n const element = document.querySelector(`#${ID}.${CLASS_CONTAINER}`)\n element.addEventListener(this.EVENT_CLICK, (event) => {\n if (event.target === element) {",
"score": 18.872074819558204
},
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": " callback()\n }\n })\n }\n /**\n * listen for on search\n *\n * @param {Function} callback\n * @returns {void}\n */",
"score": 18.622702744054358
},
{
"filename": "src/utils/DomListener.ts",
"retrieved_chunk": " callback(null)\n })\n }\n /**\n * listen for on item click\n *\n * @param {Function} onSelected\n * @param {Function} onRemove\n * @returns {void}\n */",
"score": 18.392754994081077
},
{
"filename": "src/index.ts",
"retrieved_chunk": " * @returns {void}\n */\n public close(): void {\n this.component.element.style.display = 'none'\n }\n /**\n * private function to focus on search input when modal open\n *\n * @returns {void}\n */",
"score": 16.522319646338605
}
] | typescript | domListener.onItemClick(
(data: any) => { |
import { mastodon } from "masto";
import { FeedFetcher, Scorer, StatusType, weightsType } from "./types";
import {
favsFeatureScorer,
interactsFeatureScorer,
reblogsFeatureScorer,
diversityFeedScorer,
reblogsFeedScorer,
FeatureScorer,
FeedScorer,
topPostFeatureScorer
} from "./scorer";
import weightsStore from "./weights/weightsStore";
import getHomeFeed from "./feeds/homeFeed";
import topPostsFeed from "./feeds/topPostsFeed";
import Storage from "./Storage";
import { StaticArrayPaginator } from "./Paginator"
export default class TheAlgorithm {
user: mastodon.v1.Account;
fetchers = [getHomeFeed, topPostsFeed]
featureScorer = [new favsFeatureScorer(), new reblogsFeatureScorer(), new interactsFeatureScorer(), new topPostFeatureScorer()]
feedScorer = [new reblogsFeedScorer(), new diversityFeedScorer()]
feed: StatusType[] = [];
api: mastodon.Client;
constructor(api: mastodon.Client, user: mastodon.v1.Account, valueCalculator: (((scores: weightsType) => Promise<number>) | null) = null) {
this.api = api;
this.user = user;
Storage.setIdentity(user);
Storage.logOpening();
if (valueCalculator) {
this._getValueFromScores = valueCalculator;
}
this.setDefaultWeights();
}
async getFeedAdvanced(
fetchers: Array<FeedFetcher>,
featureScorer: Array<FeatureScorer>,
feedScorer: Array<FeedScorer>
) {
this.fetchers = fetchers;
this.featureScorer = featureScorer;
this.feedScorer = feedScorer;
return this.getFeed();
}
async getFeed(): Promise<StatusType[]> {
const { fetchers, featureScorer, feedScorer } = this;
const response = await Promise.all(fetchers.map(fetcher => fetcher(this.api, this.user)))
this.feed = response.flat();
// Load and Prepare Features
await Promise.all(featureScorer.map(scorer => scorer.getFeature(this.api)));
await Promise.all(feedScorer.map(scorer => scorer.setFeed(this.feed)));
// Get Score Names
const scoreNames = featureScorer.map(scorer => scorer.getVerboseName());
const feedScoreNames = feedScorer.map(scorer => scorer.getVerboseName());
// Score Feed
let scoredFeed: StatusType[] = []
for (const status of this.feed) {
// Load Scores for each status
const featureScore = await Promise.all(featureScorer.map(scorer => scorer.score(this.api, status)));
const feedScore = await Promise.all(feedScorer.map(scorer => scorer.score(status)));
// Turn Scores into Weight Objects
const featureScoreObj = this._getScoreObj(scoreNames, featureScore);
const feedScoreObj = this._getScoreObj(feedScoreNames, feedScore);
const scoreObj = { ...featureScoreObj, ...feedScoreObj };
// Add Weight Object to Status
status["scores"] = scoreObj;
status["value"] = await this._getValueFromScores(scoreObj);
scoredFeed.push(status);
}
// Remove Replies, Stuff Already Retweeted, and Nulls
scoredFeed = scoredFeed
.filter((item: StatusType) => item != undefined)
.filter((item: StatusType) => item.inReplyToId === null)
.filter((item: StatusType) => item.content.includes("RT @") === false)
.filter((item: StatusType) => !(item?.reblog?.reblogged ?? false))
// Add Time Penalty
scoredFeed = scoredFeed.map((item: StatusType) => {
const seconds = Math.floor((new Date().getTime() - new Date(item.createdAt).getTime()) / 1000);
const timediscount = Math.pow((1 + 0.7 * 0.2), -Math.pow((seconds / 3600), 2));
item.value = (item.value ?? 0) * timediscount
return item;
})
// Sort Feed
scoredFeed = scoredFeed.sort((a, b) => (b.value ?? 0) - (a.value ?? 0));
//Remove duplicates
scoredFeed = [...new Map(scoredFeed.map((item: StatusType) => [item["uri"], item])).values()];
this.feed = scoredFeed
console.log(this.feed);
return this.feed;
}
private _getScoreObj(scoreNames: string[], scores: number[]): weightsType {
return scoreNames.reduce((obj: weightsType, cur, i) => {
obj[cur] = scores[i];
return obj;
}, {});
}
private async _getValueFromScores(scores: weightsType): Promise<number> {
const weights = await weightsStore.getWeightsMulti(Object.keys(scores));
const weightedScores = Object.keys(scores).reduce((obj: number, cur) => {
obj = obj + (scores[cur] * weights[cur] ?? 0)
return obj;
}, 0);
return weightedScores;
}
getWeightNames(): string[] {
const scorers = [...this.featureScorer, ...this.feedScorer];
return [...scorers.map(scorer => scorer.getVerboseName())]
}
async setDefaultWeights(): Promise<void> {
//Set Default Weights if they don't exist
const scorers = [...this.featureScorer, ...this.feedScorer];
Promise.all(scorers.map(scorer => weightsStore.defaultFallback(scorer.getVerboseName(), scorer.getDefaultWeight())))
}
getWeightDescriptions(): string[] {
const scorers = [...this.featureScorer, ...this.feedScorer];
return [...scorers.map(scorer => scorer.getDescription())]
}
async getWeights(): Promise<weightsType> {
const verboseNames = this.getWeightNames();
const weights = await weightsStore.getWeightsMulti(verboseNames);
return weights;
}
async setWeights(weights: weightsType): Promise<StatusType[]> {
await weightsStore.setWeightsMulti(weights);
const scoredFeed: StatusType[] = []
for (const status of this.feed) {
if (!status["scores"]) {
return this.getFeed();
}
status["value"] = await this._getValueFromScores(status["scores"]);
scoredFeed.push(status);
}
this.feed = scoredFeed.sort((a, b) => (b.value ?? 0) - (a.value ?? 0));
return this.feed;
}
getDescription(verboseName: string): string {
const scorers = [...this.featureScorer, ...this.feedScorer];
const scorer = scorers.find(scorer => scorer.getVerboseName() === verboseName);
if (scorer) {
return scorer.getDescription();
}
return "";
}
| async weightAdjust(statusWeights: weightsType): Promise<weightsType | undefined> { |
//Adjust Weights based on user interaction
if (statusWeights == undefined) return;
const mean = Object.values(statusWeights).reduce((accumulator, currentValue) => accumulator + Math.abs(currentValue), 0) / Object.values(statusWeights).length;
const currentWeight: weightsType = await this.getWeights()
const currentMean = Object.values(currentWeight).reduce((accumulator, currentValue) => accumulator + currentValue, 0) / Object.values(currentWeight).length;
for (let key in currentWeight) {
let reweight = 1 - (Math.abs(statusWeights[key]) / mean) / (currentWeight[key] / currentMean);
currentWeight[key] = currentWeight[key] + 0.02 * currentWeight[key] * reweight;
console.log(reweight);
}
await this.setWeights(currentWeight);
return currentWeight;
}
} | src/index.ts | pkreissel-fedialgo-a1b7a40 | [
{
"filename": "src/weights/weightsStore.ts",
"retrieved_chunk": " static async setWeights(weights: weightsType, verboseName: string) {\n await this.set(Key.WEIGHTS, weights, true, verboseName);\n }\n static async getWeightsMulti(verboseNames: string[]) {\n const weights: weightsType = {}\n for (const verboseName of verboseNames) {\n const weight = await this.getWeight(verboseName);\n weights[verboseName] = weight[verboseName]\n }\n return weights;",
"score": 17.768484475812482
},
{
"filename": "src/scorer/FeatureScorer.ts",
"retrieved_chunk": " return 0\n }\n getVerboseName() {\n return this._verboseName;\n }\n getDescription() {\n return this._description;\n }\n getDefaultWeight() {\n return this._defaultWeight;",
"score": 16.787281110748644
},
{
"filename": "src/weights/weightsStore.ts",
"retrieved_chunk": "import { weightsType } from \"../types\";\nimport Storage, { Key } from \"../Storage\";\nexport default class weightsStore extends Storage {\n static async getWeight(verboseName: string) {\n const weight = await this.get(Key.WEIGHTS, true, verboseName) as weightsType;\n if (weight != null) {\n return weight;\n }\n return { [verboseName]: 1 };\n }",
"score": 16.173008515452608
},
{
"filename": "src/weights/weightsStore.ts",
"retrieved_chunk": " }\n static async setWeightsMulti(weights: weightsType) {\n for (const verboseName in weights) {\n await this.setWeights({ [verboseName]: weights[verboseName] }, verboseName);\n }\n }\n static async defaultFallback(verboseName: string, defaultWeight: number): Promise<boolean> {\n // If the weight is not set, set it to the default weight\n const weight = await this.get(Key.WEIGHTS, true, verboseName) as weightsType;\n if (weight == null) {",
"score": 15.019350280498829
},
{
"filename": "src/scorer/FeedScorer.ts",
"retrieved_chunk": " async score(status: mastodon.v1.Status) {\n if (!this._isReady) {\n throw new Error(\"FeedScorer not ready\");\n }\n return 0;\n }\n getVerboseName() {\n return this._verboseName;\n }\n getDescription() {",
"score": 14.963774800254086
}
] | typescript | async weightAdjust(statusWeights: weightsType): Promise<weightsType | undefined> { |
import { mastodon } from "masto";
import { FeedFetcher, Scorer, StatusType, weightsType } from "./types";
import {
favsFeatureScorer,
interactsFeatureScorer,
reblogsFeatureScorer,
diversityFeedScorer,
reblogsFeedScorer,
FeatureScorer,
FeedScorer,
topPostFeatureScorer
} from "./scorer";
import weightsStore from "./weights/weightsStore";
import getHomeFeed from "./feeds/homeFeed";
import topPostsFeed from "./feeds/topPostsFeed";
import Storage from "./Storage";
import { StaticArrayPaginator } from "./Paginator"
export default class TheAlgorithm {
user: mastodon.v1.Account;
fetchers = [getHomeFeed, topPostsFeed]
featureScorer = [new favsFeatureScorer(), new reblogsFeatureScorer(), new interactsFeatureScorer(), new topPostFeatureScorer()]
feedScorer = [new reblogsFeedScorer(), new diversityFeedScorer()]
feed: StatusType[] = [];
api: mastodon.Client;
constructor(api: mastodon.Client, user: mastodon.v1.Account, valueCalculator: (((scores: weightsType) => Promise<number>) | null) = null) {
this.api = api;
this.user = user;
Storage.setIdentity(user);
Storage.logOpening();
if (valueCalculator) {
this._getValueFromScores = valueCalculator;
}
this.setDefaultWeights();
}
async getFeedAdvanced(
fetchers: Array<FeedFetcher>,
featureScorer: Array<FeatureScorer>,
feedScorer: Array<FeedScorer>
) {
this.fetchers = fetchers;
this.featureScorer = featureScorer;
this.feedScorer = feedScorer;
return this.getFeed();
}
async getFeed(): Promise<StatusType[]> {
const { fetchers, featureScorer, feedScorer } = this;
const response = await Promise.all(fetchers.map(fetcher => fetcher(this.api, this.user)))
this.feed = response.flat();
// Load and Prepare Features
await Promise.all(featureScorer.map(scorer => scorer.getFeature(this.api)));
await Promise.all(feedScorer.map(scorer => scorer.setFeed(this.feed)));
// Get Score Names
const scoreNames = featureScorer.map(scorer => scorer.getVerboseName());
const feedScoreNames = feedScorer.map(scorer => scorer.getVerboseName());
// Score Feed
let scoredFeed: StatusType[] = []
for (const status of this.feed) {
// Load Scores for each status
const featureScore = await Promise.all(featureScorer.map(scorer => scorer.score(this.api, status)));
const feedScore = await Promise.all(feedScorer.map(scorer => scorer.score(status)));
// Turn Scores into Weight Objects
const featureScoreObj = this._getScoreObj(scoreNames, featureScore);
const feedScoreObj = this._getScoreObj(feedScoreNames, feedScore);
const scoreObj = { ...featureScoreObj, ...feedScoreObj };
// Add Weight Object to Status
status["scores"] = scoreObj;
status["value"] = await this._getValueFromScores(scoreObj);
scoredFeed.push(status);
}
// Remove Replies, Stuff Already Retweeted, and Nulls
scoredFeed = scoredFeed
.filter((item: StatusType) => item != undefined)
.filter((item: StatusType) => item.inReplyToId === null)
.filter((item: StatusType) => item.content.includes("RT @") === false)
.filter((item: StatusType) => !(item?.reblog?.reblogged ?? false))
// Add Time Penalty
scoredFeed = scoredFeed.map((item: StatusType) => {
const seconds = Math.floor((new Date().getTime() - new Date(item.createdAt).getTime()) / 1000);
const timediscount = Math.pow((1 + 0.7 * 0.2), -Math.pow((seconds / 3600), 2));
item.value = (item.value ?? 0) * timediscount
return item;
})
// Sort Feed
scoredFeed = scoredFeed.sort((a, b) => (b.value ?? 0) - (a.value ?? 0));
//Remove duplicates
scoredFeed = [...new Map(scoredFeed.map((item: StatusType) => [item["uri"], item])).values()];
this.feed = scoredFeed
console.log(this.feed);
return this.feed;
}
private _getScoreObj(scoreNames: string[], scores: number[]): weightsType {
return scoreNames.reduce((obj: weightsType, cur, i) => {
obj[cur] = scores[i];
return obj;
}, {});
}
private async _getValueFromScores(scores: weightsType): Promise<number> {
const weights = await weightsStore.getWeightsMulti(Object.keys(scores));
const weightedScores = Object.keys(scores).reduce((obj: number, cur) => {
obj = obj + (scores[cur] * weights[cur] ?? 0)
return obj;
}, 0);
return weightedScores;
}
getWeightNames(): string[] {
const scorers = [...this.featureScorer, ...this.feedScorer];
return [...scorers.map(scorer => scorer.getVerboseName())]
}
async setDefaultWeights(): Promise<void> {
//Set Default Weights if they don't exist
const scorers = [...this.featureScorer, ...this.feedScorer];
Promise.all(scorers.map(scorer => weightsStore.defaultFallback(scorer.getVerboseName(), scorer.getDefaultWeight())))
}
getWeightDescriptions(): string[] {
const scorers = [...this.featureScorer, ...this.feedScorer];
return [...scorers.map(scorer => scorer.getDescription())]
}
| async getWeights(): Promise<weightsType> { |
const verboseNames = this.getWeightNames();
const weights = await weightsStore.getWeightsMulti(verboseNames);
return weights;
}
async setWeights(weights: weightsType): Promise<StatusType[]> {
await weightsStore.setWeightsMulti(weights);
const scoredFeed: StatusType[] = []
for (const status of this.feed) {
if (!status["scores"]) {
return this.getFeed();
}
status["value"] = await this._getValueFromScores(status["scores"]);
scoredFeed.push(status);
}
this.feed = scoredFeed.sort((a, b) => (b.value ?? 0) - (a.value ?? 0));
return this.feed;
}
getDescription(verboseName: string): string {
const scorers = [...this.featureScorer, ...this.feedScorer];
const scorer = scorers.find(scorer => scorer.getVerboseName() === verboseName);
if (scorer) {
return scorer.getDescription();
}
return "";
}
async weightAdjust(statusWeights: weightsType): Promise<weightsType | undefined> {
//Adjust Weights based on user interaction
if (statusWeights == undefined) return;
const mean = Object.values(statusWeights).reduce((accumulator, currentValue) => accumulator + Math.abs(currentValue), 0) / Object.values(statusWeights).length;
const currentWeight: weightsType = await this.getWeights()
const currentMean = Object.values(currentWeight).reduce((accumulator, currentValue) => accumulator + currentValue, 0) / Object.values(currentWeight).length;
for (let key in currentWeight) {
let reweight = 1 - (Math.abs(statusWeights[key]) / mean) / (currentWeight[key] / currentMean);
currentWeight[key] = currentWeight[key] + 0.02 * currentWeight[key] * reweight;
console.log(reweight);
}
await this.setWeights(currentWeight);
return currentWeight;
}
} | src/index.ts | pkreissel-fedialgo-a1b7a40 | [
{
"filename": "src/feeds/topPostsFeed.ts",
"retrieved_chunk": " results = await Promise.all(servers.map(async (server: string): Promise<mastodon.v1.Status[]> => {\n if (server === \"undefined\" || typeof server == \"undefined\" || server === \"\") return [];\n let res;\n try {\n res = await fetch(\"https://\" + server + \"/api/v1/trends/statuses\")\n }\n catch (e) {\n return [];\n }\n if (!res.ok) {",
"score": 16.493882682026175
},
{
"filename": "src/scorer/FeatureScorer.ts",
"retrieved_chunk": " return 0\n }\n getVerboseName() {\n return this._verboseName;\n }\n getDescription() {\n return this._description;\n }\n getDefaultWeight() {\n return this._defaultWeight;",
"score": 15.988307040076602
},
{
"filename": "src/weights/weightsStore.ts",
"retrieved_chunk": " }\n static async setWeightsMulti(weights: weightsType) {\n for (const verboseName in weights) {\n await this.setWeights({ [verboseName]: weights[verboseName] }, verboseName);\n }\n }\n static async defaultFallback(verboseName: string, defaultWeight: number): Promise<boolean> {\n // If the weight is not set, set it to the default weight\n const weight = await this.get(Key.WEIGHTS, true, verboseName) as weightsType;\n if (weight == null) {",
"score": 10.996042710827139
},
{
"filename": "src/scorer/FeedScorer.ts",
"retrieved_chunk": " async score(status: mastodon.v1.Status) {\n if (!this._isReady) {\n throw new Error(\"FeedScorer not ready\");\n }\n return 0;\n }\n getVerboseName() {\n return this._verboseName;\n }\n getDescription() {",
"score": 10.736932053421636
},
{
"filename": "src/weights/weightsStore.ts",
"retrieved_chunk": "import { weightsType } from \"../types\";\nimport Storage, { Key } from \"../Storage\";\nexport default class weightsStore extends Storage {\n static async getWeight(verboseName: string) {\n const weight = await this.get(Key.WEIGHTS, true, verboseName) as weightsType;\n if (weight != null) {\n return weight;\n }\n return { [verboseName]: 1 };\n }",
"score": 10.210272488629592
}
] | typescript | async getWeights(): Promise<weightsType> { |
import { mastodon } from "masto";
import { serverFeatureType, accFeatureType } from "../types";
import FavsFeature from "./favsFeature";
import reblogsFeature from "./reblogsFeature";
import interactsFeature from "./interactsFeature";
import coreServerFeature from "./coreServerFeature";
import Storage, { Key } from "../Storage";
export default class FeatureStorage extends Storage {
static async getTopFavs(api: mastodon.Client): Promise<accFeatureType> {
const topFavs: accFeatureType = await this.get(Key.TOP_FAVS) as accFeatureType;
console.log(topFavs);
if (topFavs != null && await this.getOpenings() < 10) {
return topFavs;
} else {
const favs = await FavsFeature(api);
await this.set(Key.TOP_FAVS, favs);
return favs;
}
}
static async getTopReblogs(api: mastodon.Client): Promise<accFeatureType> {
const topReblogs: accFeatureType = await this.get(Key.TOP_REBLOGS) as accFeatureType;
console.log(topReblogs);
if (topReblogs != null && await this.getOpenings() < 10) {
return topReblogs;
} else {
const reblogs = await reblogsFeature(api);
await this.set(Key.TOP_REBLOGS, reblogs);
return reblogs;
}
}
static async getTopInteracts(api: mastodon.Client): Promise<accFeatureType> {
const topInteracts: accFeatureType = await this.get(Key.TOP_INTERACTS) as accFeatureType;
console.log(topInteracts);
if (topInteracts != null && await this.getOpenings() < 10) {
return topInteracts;
} else {
const interacts = await interactsFeature(api);
await this.set(Key.TOP_INTERACTS, interacts);
return interacts;
}
}
| static async getCoreServer(api: mastodon.Client): Promise<serverFeatureType> { |
const coreServer: serverFeatureType = await this.get(Key.CORE_SERVER) as serverFeatureType;
console.log(coreServer);
if (coreServer != null && await this.getOpenings() < 10) {
return coreServer;
} else {
const user = await this.getIdentity();
const server = await coreServerFeature(api, user);
await this.set(Key.CORE_SERVER, server);
return server;
}
}
}
| src/features/FeatureStore.ts | pkreissel-fedialgo-a1b7a40 | [
{
"filename": "src/Storage.ts",
"retrieved_chunk": " static async logOpening() {\n console.log(\"Logging Opening\")\n const openings = parseInt(await this.get(Key.OPENINGS, true) as string);\n if (openings == null || isNaN(openings)) {\n await this.set(Key.OPENINGS, \"1\", true);\n } else {\n await this.set(Key.OPENINGS, (openings + 1).toString(), true);\n }\n }\n static async getOpenings() {",
"score": 25.082471291224703
},
{
"filename": "src/Storage.ts",
"retrieved_chunk": "import AsyncStorage from '@react-native-async-storage/async-storage';\nimport { serverFeatureType, accFeatureType, weightsType } from \"./types\";\nimport { mastodon } from \"masto\";\nexport enum Key {\n TOP_FAVS = 'favs',\n TOP_REBLOGS = 'reblogs',\n TOP_INTERACTS = 'interacts',\n CORE_SERVER = 'coreServer',\n USER = 'algouser',\n WEIGHTS = 'weights',",
"score": 20.58979836572536
},
{
"filename": "src/Storage.ts",
"retrieved_chunk": " const openings = parseInt(await this.get(Key.OPENINGS, true) as string);\n return openings;\n }\n static async getIdentity(): Promise<mastodon.v1.Account> {\n const userJson = await AsyncStorage.getItem(Key.USER);\n const user: mastodon.v1.Account = userJson != null ? JSON.parse(userJson) : null;\n return user;\n }\n static async setIdentity(user: mastodon.v1.Account) {\n const userJson = JSON.stringify(user);",
"score": 12.715837119598286
},
{
"filename": "src/weights/weightsStore.ts",
"retrieved_chunk": " }\n static async setWeightsMulti(weights: weightsType) {\n for (const verboseName in weights) {\n await this.setWeights({ [verboseName]: weights[verboseName] }, verboseName);\n }\n }\n static async defaultFallback(verboseName: string, defaultWeight: number): Promise<boolean> {\n // If the weight is not set, set it to the default weight\n const weight = await this.get(Key.WEIGHTS, true, verboseName) as weightsType;\n if (weight == null) {",
"score": 12.707436637393588
},
{
"filename": "src/Storage.ts",
"retrieved_chunk": " OPENINGS = \"openings\",\n}\ntype StorageValue = serverFeatureType | accFeatureType | mastodon.v1.Account | weightsType | string\nexport default class Storage {\n protected static async get(key: Key, groupedByUser = true, suffix = \"\"): Promise<StorageValue> {\n const suffixKey = this.suffix(key, suffix);\n const storageKey = groupedByUser ? await this.prefix(suffixKey) : suffixKey;\n const jsonValue = await AsyncStorage.getItem(storageKey);\n const value = jsonValue != null ? JSON.parse(jsonValue) : null;\n return value != null ? value[storageKey] : null;",
"score": 12.438847859817407
}
] | typescript | static async getCoreServer(api: mastodon.Client): Promise<serverFeatureType> { |
import { mastodon } from "masto";
import { FeedFetcher, Scorer, StatusType, weightsType } from "./types";
import {
favsFeatureScorer,
interactsFeatureScorer,
reblogsFeatureScorer,
diversityFeedScorer,
reblogsFeedScorer,
FeatureScorer,
FeedScorer,
topPostFeatureScorer
} from "./scorer";
import weightsStore from "./weights/weightsStore";
import getHomeFeed from "./feeds/homeFeed";
import topPostsFeed from "./feeds/topPostsFeed";
import Storage from "./Storage";
import { StaticArrayPaginator } from "./Paginator"
export default class TheAlgorithm {
user: mastodon.v1.Account;
fetchers = [getHomeFeed, topPostsFeed]
featureScorer = [new favsFeatureScorer(), new reblogsFeatureScorer(), new interactsFeatureScorer(), new topPostFeatureScorer()]
feedScorer = [new reblogsFeedScorer(), new diversityFeedScorer()]
feed: StatusType[] = [];
api: mastodon.Client;
constructor(api: mastodon.Client, user: mastodon.v1.Account, valueCalculator: (((scores: weightsType) => Promise<number>) | null) = null) {
this.api = api;
this.user = user;
Storage.setIdentity(user);
Storage.logOpening();
if (valueCalculator) {
this._getValueFromScores = valueCalculator;
}
this.setDefaultWeights();
}
async getFeedAdvanced(
fetchers: Array<FeedFetcher>,
featureScorer: Array<FeatureScorer>,
feedScorer: Array<FeedScorer>
) {
this.fetchers = fetchers;
this.featureScorer = featureScorer;
this.feedScorer = feedScorer;
return this.getFeed();
}
async getFeed(): Promise<StatusType[]> {
const { fetchers, featureScorer, feedScorer } = this;
const response = await Promise.all(fetchers.map(fetcher => fetcher(this.api, this.user)))
this.feed = response.flat();
// Load and Prepare Features
await Promise.all(featureScorer.map(scorer => scorer.getFeature(this.api)));
await Promise.all(feedScorer.map(scorer => scorer.setFeed(this.feed)));
// Get Score Names
const scoreNames = featureScorer.map(scorer => scorer.getVerboseName());
const feedScoreNames = feedScorer.map(scorer => scorer.getVerboseName());
// Score Feed
let scoredFeed: StatusType[] = []
for (const status of this.feed) {
// Load Scores for each status
const featureScore = await Promise.all(featureScorer.map(scorer => scorer.score(this.api, status)));
const feedScore = await Promise.all(feedScorer.map(scorer => scorer.score(status)));
// Turn Scores into Weight Objects
const featureScoreObj = this._getScoreObj(scoreNames, featureScore);
const feedScoreObj = this._getScoreObj(feedScoreNames, feedScore);
const scoreObj = { ...featureScoreObj, ...feedScoreObj };
// Add Weight Object to Status
status["scores"] = scoreObj;
status["value"] = await this._getValueFromScores(scoreObj);
scoredFeed.push(status);
}
// Remove Replies, Stuff Already Retweeted, and Nulls
scoredFeed = scoredFeed
.filter((item: StatusType) => item != undefined)
.filter((item: StatusType) => item.inReplyToId === null)
.filter((item: StatusType) => item.content.includes("RT @") === false)
.filter((item: StatusType) => !(item?.reblog?.reblogged ?? false))
// Add Time Penalty
scoredFeed = scoredFeed.map((item: StatusType) => {
const seconds = Math.floor((new Date().getTime() - new Date(item.createdAt).getTime()) / 1000);
const timediscount = Math.pow((1 + 0.7 * 0.2), -Math.pow((seconds / 3600), 2));
item.value = (item.value ?? 0) * timediscount
return item;
})
// Sort Feed
scoredFeed = scoredFeed.sort((a, b) => (b.value ?? 0) - (a.value ?? 0));
//Remove duplicates
scoredFeed = [...new Map(scoredFeed.map((item: StatusType) => [item["uri"], item])).values()];
this.feed = scoredFeed
console.log(this.feed);
return this.feed;
}
private _getScoreObj(scoreNames: string[], scores: number[]): weightsType {
return scoreNames.reduce((obj: weightsType, cur, i) => {
obj[cur] = scores[i];
return obj;
}, {});
}
private async _getValueFromScores(scores: weightsType): Promise<number> {
| const weights = await weightsStore.getWeightsMulti(Object.keys(scores)); |
const weightedScores = Object.keys(scores).reduce((obj: number, cur) => {
obj = obj + (scores[cur] * weights[cur] ?? 0)
return obj;
}, 0);
return weightedScores;
}
getWeightNames(): string[] {
const scorers = [...this.featureScorer, ...this.feedScorer];
return [...scorers.map(scorer => scorer.getVerboseName())]
}
async setDefaultWeights(): Promise<void> {
//Set Default Weights if they don't exist
const scorers = [...this.featureScorer, ...this.feedScorer];
Promise.all(scorers.map(scorer => weightsStore.defaultFallback(scorer.getVerboseName(), scorer.getDefaultWeight())))
}
getWeightDescriptions(): string[] {
const scorers = [...this.featureScorer, ...this.feedScorer];
return [...scorers.map(scorer => scorer.getDescription())]
}
async getWeights(): Promise<weightsType> {
const verboseNames = this.getWeightNames();
const weights = await weightsStore.getWeightsMulti(verboseNames);
return weights;
}
async setWeights(weights: weightsType): Promise<StatusType[]> {
await weightsStore.setWeightsMulti(weights);
const scoredFeed: StatusType[] = []
for (const status of this.feed) {
if (!status["scores"]) {
return this.getFeed();
}
status["value"] = await this._getValueFromScores(status["scores"]);
scoredFeed.push(status);
}
this.feed = scoredFeed.sort((a, b) => (b.value ?? 0) - (a.value ?? 0));
return this.feed;
}
getDescription(verboseName: string): string {
const scorers = [...this.featureScorer, ...this.feedScorer];
const scorer = scorers.find(scorer => scorer.getVerboseName() === verboseName);
if (scorer) {
return scorer.getDescription();
}
return "";
}
async weightAdjust(statusWeights: weightsType): Promise<weightsType | undefined> {
//Adjust Weights based on user interaction
if (statusWeights == undefined) return;
const mean = Object.values(statusWeights).reduce((accumulator, currentValue) => accumulator + Math.abs(currentValue), 0) / Object.values(statusWeights).length;
const currentWeight: weightsType = await this.getWeights()
const currentMean = Object.values(currentWeight).reduce((accumulator, currentValue) => accumulator + currentValue, 0) / Object.values(currentWeight).length;
for (let key in currentWeight) {
let reweight = 1 - (Math.abs(statusWeights[key]) / mean) / (currentWeight[key] / currentMean);
currentWeight[key] = currentWeight[key] + 0.02 * currentWeight[key] * reweight;
console.log(reweight);
}
await this.setWeights(currentWeight);
return currentWeight;
}
} | src/index.ts | pkreissel-fedialgo-a1b7a40 | [
{
"filename": "src/types.ts",
"retrieved_chunk": "export interface StatusType extends mastodon.v1.Status {\n topPost?: boolean;\n scores?: weightsType;\n value?: number;\n reblog?: StatusType;\n reblogBy?: string;\n}\nexport type FeedFetcher = (api: mastodon.Client) => Promise<StatusType[]>;\nexport type Scorer = (api: mastodon.Client, status: StatusType) => number;",
"score": 28.086478269904763
},
{
"filename": "src/weights/weightsStore.ts",
"retrieved_chunk": " static async setWeights(weights: weightsType, verboseName: string) {\n await this.set(Key.WEIGHTS, weights, true, verboseName);\n }\n static async getWeightsMulti(verboseNames: string[]) {\n const weights: weightsType = {}\n for (const verboseName of verboseNames) {\n const weight = await this.getWeight(verboseName);\n weights[verboseName] = weight[verboseName]\n }\n return weights;",
"score": 22.007420272311396
},
{
"filename": "src/scorer/feed/diversityFeedScorer.ts",
"retrieved_chunk": "import FeedScorer from \"../FeedScorer\";\nimport { StatusType } from \"../../types\";\nexport default class diversityFeedScorer extends FeedScorer {\n constructor() {\n super(\"Diversity\", \"Downranks posts from users that you have seen a lot of posts from\");\n }\n feedExtractor(feed: StatusType[]) {\n return feed.reduce((obj: any, status) => {\n obj[status.account.acct] = (obj[status.account.acct] || 0) - 1;\n return obj;",
"score": 21.66290891575401
},
{
"filename": "src/scorer/feed/reblogsFeedScorer.ts",
"retrieved_chunk": " obj[status.reblog.uri] = (obj[status.reblog.uri] || 0) + 1;\n } else {\n obj[status.uri] = (obj[status.uri] || 0) + 1;\n }\n return obj;\n }, {});\n }\n async score(status: StatusType) {\n super.score(status);\n const features = this.features;",
"score": 19.42239664092848
},
{
"filename": "src/weights/weightsStore.ts",
"retrieved_chunk": " }\n static async setWeightsMulti(weights: weightsType) {\n for (const verboseName in weights) {\n await this.setWeights({ [verboseName]: weights[verboseName] }, verboseName);\n }\n }\n static async defaultFallback(verboseName: string, defaultWeight: number): Promise<boolean> {\n // If the weight is not set, set it to the default weight\n const weight = await this.get(Key.WEIGHTS, true, verboseName) as weightsType;\n if (weight == null) {",
"score": 17.30814630988698
}
] | typescript | const weights = await weightsStore.getWeightsMulti(Object.keys(scores)); |
import { mastodon } from "masto";
import { FeedFetcher, Scorer, StatusType, weightsType } from "./types";
import {
favsFeatureScorer,
interactsFeatureScorer,
reblogsFeatureScorer,
diversityFeedScorer,
reblogsFeedScorer,
FeatureScorer,
FeedScorer,
topPostFeatureScorer
} from "./scorer";
import weightsStore from "./weights/weightsStore";
import getHomeFeed from "./feeds/homeFeed";
import topPostsFeed from "./feeds/topPostsFeed";
import Storage from "./Storage";
import { StaticArrayPaginator } from "./Paginator"
export default class TheAlgorithm {
user: mastodon.v1.Account;
fetchers = [getHomeFeed, topPostsFeed]
featureScorer = [new favsFeatureScorer(), new reblogsFeatureScorer(), new interactsFeatureScorer(), new topPostFeatureScorer()]
feedScorer = [new reblogsFeedScorer(), new diversityFeedScorer()]
feed: StatusType[] = [];
api: mastodon.Client;
constructor(api: mastodon.Client, user: mastodon.v1.Account, valueCalculator: (((scores: weightsType) => Promise<number>) | null) = null) {
this.api = api;
this.user = user;
Storage.setIdentity(user);
Storage.logOpening();
if (valueCalculator) {
this._getValueFromScores = valueCalculator;
}
this.setDefaultWeights();
}
async getFeedAdvanced(
fetchers: Array<FeedFetcher>,
featureScorer: Array<FeatureScorer>,
feedScorer: Array<FeedScorer>
) {
this.fetchers = fetchers;
this.featureScorer = featureScorer;
this.feedScorer = feedScorer;
return this.getFeed();
}
async getFeed(): Promise<StatusType[]> {
const { fetchers, featureScorer, feedScorer } = this;
const response = await Promise.all(fetchers.map(fetcher => fetcher(this.api, this.user)))
this.feed = response.flat();
// Load and Prepare Features
await Promise.all(featureScorer.map(scorer => scorer.getFeature(this.api)));
await Promise.all(feedScorer.map(scorer => scorer.setFeed(this.feed)));
// Get Score Names
const scoreNames = featureScorer.map(scorer => scorer.getVerboseName());
const feedScoreNames = feedScorer.map(scorer => scorer.getVerboseName());
// Score Feed
let scoredFeed: StatusType[] = []
for (const status of this.feed) {
// Load Scores for each status
const featureScore = await Promise.all(featureScorer.map(scorer => scorer.score(this.api, status)));
const feedScore = await Promise.all(feedScorer.map(scorer => scorer.score(status)));
// Turn Scores into Weight Objects
const featureScoreObj = this._getScoreObj(scoreNames, featureScore);
const feedScoreObj = this._getScoreObj(feedScoreNames, feedScore);
const scoreObj = { ...featureScoreObj, ...feedScoreObj };
// Add Weight Object to Status
status["scores"] = scoreObj;
status["value"] = await this._getValueFromScores(scoreObj);
scoredFeed.push(status);
}
// Remove Replies, Stuff Already Retweeted, and Nulls
scoredFeed = scoredFeed
.filter((item: StatusType) => item != undefined)
.filter((item: StatusType) => item.inReplyToId === null)
.filter((item: StatusType) => item.content.includes("RT @") === false)
.filter((item: StatusType) => !(item?.reblog?.reblogged ?? false))
// Add Time Penalty
scoredFeed = scoredFeed.map((item: StatusType) => {
const seconds = Math.floor((new Date().getTime() - new Date(item.createdAt).getTime()) / 1000);
const timediscount = Math.pow((1 + 0.7 * 0.2), -Math.pow((seconds / 3600), 2));
| item.value = (item.value ?? 0) * timediscount
return item; |
})
// Sort Feed
scoredFeed = scoredFeed.sort((a, b) => (b.value ?? 0) - (a.value ?? 0));
//Remove duplicates
scoredFeed = [...new Map(scoredFeed.map((item: StatusType) => [item["uri"], item])).values()];
this.feed = scoredFeed
console.log(this.feed);
return this.feed;
}
private _getScoreObj(scoreNames: string[], scores: number[]): weightsType {
return scoreNames.reduce((obj: weightsType, cur, i) => {
obj[cur] = scores[i];
return obj;
}, {});
}
private async _getValueFromScores(scores: weightsType): Promise<number> {
const weights = await weightsStore.getWeightsMulti(Object.keys(scores));
const weightedScores = Object.keys(scores).reduce((obj: number, cur) => {
obj = obj + (scores[cur] * weights[cur] ?? 0)
return obj;
}, 0);
return weightedScores;
}
getWeightNames(): string[] {
const scorers = [...this.featureScorer, ...this.feedScorer];
return [...scorers.map(scorer => scorer.getVerboseName())]
}
async setDefaultWeights(): Promise<void> {
//Set Default Weights if they don't exist
const scorers = [...this.featureScorer, ...this.feedScorer];
Promise.all(scorers.map(scorer => weightsStore.defaultFallback(scorer.getVerboseName(), scorer.getDefaultWeight())))
}
getWeightDescriptions(): string[] {
const scorers = [...this.featureScorer, ...this.feedScorer];
return [...scorers.map(scorer => scorer.getDescription())]
}
async getWeights(): Promise<weightsType> {
const verboseNames = this.getWeightNames();
const weights = await weightsStore.getWeightsMulti(verboseNames);
return weights;
}
async setWeights(weights: weightsType): Promise<StatusType[]> {
await weightsStore.setWeightsMulti(weights);
const scoredFeed: StatusType[] = []
for (const status of this.feed) {
if (!status["scores"]) {
return this.getFeed();
}
status["value"] = await this._getValueFromScores(status["scores"]);
scoredFeed.push(status);
}
this.feed = scoredFeed.sort((a, b) => (b.value ?? 0) - (a.value ?? 0));
return this.feed;
}
getDescription(verboseName: string): string {
const scorers = [...this.featureScorer, ...this.feedScorer];
const scorer = scorers.find(scorer => scorer.getVerboseName() === verboseName);
if (scorer) {
return scorer.getDescription();
}
return "";
}
async weightAdjust(statusWeights: weightsType): Promise<weightsType | undefined> {
//Adjust Weights based on user interaction
if (statusWeights == undefined) return;
const mean = Object.values(statusWeights).reduce((accumulator, currentValue) => accumulator + Math.abs(currentValue), 0) / Object.values(statusWeights).length;
const currentWeight: weightsType = await this.getWeights()
const currentMean = Object.values(currentWeight).reduce((accumulator, currentValue) => accumulator + currentValue, 0) / Object.values(currentWeight).length;
for (let key in currentWeight) {
let reweight = 1 - (Math.abs(statusWeights[key]) / mean) / (currentWeight[key] / currentMean);
currentWeight[key] = currentWeight[key] + 0.02 * currentWeight[key] * reweight;
console.log(reweight);
}
await this.setWeights(currentWeight);
return currentWeight;
}
} | src/index.ts | pkreissel-fedialgo-a1b7a40 | [
{
"filename": "src/Paginator.ts",
"retrieved_chunk": " const data: StatusType[] = [];\n let hasNextPage = false;\n const startIndex = this.currentIndex;\n const endIndex = this.currentIndex + this.pageSize;\n const currentData = this.dataArray.slice(startIndex, endIndex);\n currentData.forEach((item) => data.push(item));\n if (endIndex < this.dataArray.length) {\n hasNextPage = true;\n }\n this.currentIndex += this.pageSize;",
"score": 73.89072282146516
},
{
"filename": "src/feeds/homeFeed.ts",
"retrieved_chunk": "import { mastodon } from \"masto\";\nexport default async function getHomeFeed(api: mastodon.Client, user: mastodon.v1.Account) {\n let results: any[] = [];\n let pages = 10;\n for await (const page of api.v1.timelines.listHome()) {\n results = results.concat(page)\n pages--;\n //check if status is less than 12 hours old\n if (pages === 0 || new Date(page[0].createdAt) < new Date(Date.now() - 43200000)) {\n break;",
"score": 21.869258440135596
},
{
"filename": "src/scorer/feature/interactsFeatureScorer.ts",
"retrieved_chunk": " defaultWeight: 2,\n })\n }\n async score(api: mastodon.Client, status: StatusType) {\n return (status.account.acct in this.feature) ? this.feature[status.account.acct] : 0\n }\n}",
"score": 16.805365296662277
},
{
"filename": "src/scorer/feed/reblogsFeedScorer.ts",
"retrieved_chunk": " obj[status.reblog.uri] = (obj[status.reblog.uri] || 0) + 1;\n } else {\n obj[status.uri] = (obj[status.uri] || 0) + 1;\n }\n return obj;\n }, {});\n }\n async score(status: StatusType) {\n super.score(status);\n const features = this.features;",
"score": 13.449351660648286
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export interface StatusType extends mastodon.v1.Status {\n topPost?: boolean;\n scores?: weightsType;\n value?: number;\n reblog?: StatusType;\n reblogBy?: string;\n}\nexport type FeedFetcher = (api: mastodon.Client) => Promise<StatusType[]>;\nexport type Scorer = (api: mastodon.Client, status: StatusType) => number;",
"score": 13.224541206629297
}
] | typescript | item.value = (item.value ?? 0) * timediscount
return item; |
import { mastodon } from "masto";
import { FeedFetcher, Scorer, StatusType, weightsType } from "./types";
import {
favsFeatureScorer,
interactsFeatureScorer,
reblogsFeatureScorer,
diversityFeedScorer,
reblogsFeedScorer,
FeatureScorer,
FeedScorer,
topPostFeatureScorer
} from "./scorer";
import weightsStore from "./weights/weightsStore";
import getHomeFeed from "./feeds/homeFeed";
import topPostsFeed from "./feeds/topPostsFeed";
import Storage from "./Storage";
import { StaticArrayPaginator } from "./Paginator"
export default class TheAlgorithm {
user: mastodon.v1.Account;
fetchers = [getHomeFeed, topPostsFeed]
featureScorer = [new favsFeatureScorer(), new reblogsFeatureScorer(), new interactsFeatureScorer(), new topPostFeatureScorer()]
feedScorer = [new reblogsFeedScorer(), new diversityFeedScorer()]
feed: StatusType[] = [];
api: mastodon.Client;
constructor(api: mastodon.Client, user: mastodon.v1.Account, valueCalculator: (((scores: weightsType) => Promise<number>) | null) = null) {
this.api = api;
this.user = user;
Storage.setIdentity(user);
Storage.logOpening();
if (valueCalculator) {
this._getValueFromScores = valueCalculator;
}
this.setDefaultWeights();
}
async getFeedAdvanced(
fetchers: Array<FeedFetcher>,
featureScorer: Array<FeatureScorer>,
feedScorer: Array<FeedScorer>
) {
this.fetchers = fetchers;
this.featureScorer = featureScorer;
this.feedScorer = feedScorer;
return this.getFeed();
}
async getFeed | (): Promise<StatusType[]> { |
const { fetchers, featureScorer, feedScorer } = this;
const response = await Promise.all(fetchers.map(fetcher => fetcher(this.api, this.user)))
this.feed = response.flat();
// Load and Prepare Features
await Promise.all(featureScorer.map(scorer => scorer.getFeature(this.api)));
await Promise.all(feedScorer.map(scorer => scorer.setFeed(this.feed)));
// Get Score Names
const scoreNames = featureScorer.map(scorer => scorer.getVerboseName());
const feedScoreNames = feedScorer.map(scorer => scorer.getVerboseName());
// Score Feed
let scoredFeed: StatusType[] = []
for (const status of this.feed) {
// Load Scores for each status
const featureScore = await Promise.all(featureScorer.map(scorer => scorer.score(this.api, status)));
const feedScore = await Promise.all(feedScorer.map(scorer => scorer.score(status)));
// Turn Scores into Weight Objects
const featureScoreObj = this._getScoreObj(scoreNames, featureScore);
const feedScoreObj = this._getScoreObj(feedScoreNames, feedScore);
const scoreObj = { ...featureScoreObj, ...feedScoreObj };
// Add Weight Object to Status
status["scores"] = scoreObj;
status["value"] = await this._getValueFromScores(scoreObj);
scoredFeed.push(status);
}
// Remove Replies, Stuff Already Retweeted, and Nulls
scoredFeed = scoredFeed
.filter((item: StatusType) => item != undefined)
.filter((item: StatusType) => item.inReplyToId === null)
.filter((item: StatusType) => item.content.includes("RT @") === false)
.filter((item: StatusType) => !(item?.reblog?.reblogged ?? false))
// Add Time Penalty
scoredFeed = scoredFeed.map((item: StatusType) => {
const seconds = Math.floor((new Date().getTime() - new Date(item.createdAt).getTime()) / 1000);
const timediscount = Math.pow((1 + 0.7 * 0.2), -Math.pow((seconds / 3600), 2));
item.value = (item.value ?? 0) * timediscount
return item;
})
// Sort Feed
scoredFeed = scoredFeed.sort((a, b) => (b.value ?? 0) - (a.value ?? 0));
//Remove duplicates
scoredFeed = [...new Map(scoredFeed.map((item: StatusType) => [item["uri"], item])).values()];
this.feed = scoredFeed
console.log(this.feed);
return this.feed;
}
private _getScoreObj(scoreNames: string[], scores: number[]): weightsType {
return scoreNames.reduce((obj: weightsType, cur, i) => {
obj[cur] = scores[i];
return obj;
}, {});
}
private async _getValueFromScores(scores: weightsType): Promise<number> {
const weights = await weightsStore.getWeightsMulti(Object.keys(scores));
const weightedScores = Object.keys(scores).reduce((obj: number, cur) => {
obj = obj + (scores[cur] * weights[cur] ?? 0)
return obj;
}, 0);
return weightedScores;
}
getWeightNames(): string[] {
const scorers = [...this.featureScorer, ...this.feedScorer];
return [...scorers.map(scorer => scorer.getVerboseName())]
}
async setDefaultWeights(): Promise<void> {
//Set Default Weights if they don't exist
const scorers = [...this.featureScorer, ...this.feedScorer];
Promise.all(scorers.map(scorer => weightsStore.defaultFallback(scorer.getVerboseName(), scorer.getDefaultWeight())))
}
getWeightDescriptions(): string[] {
const scorers = [...this.featureScorer, ...this.feedScorer];
return [...scorers.map(scorer => scorer.getDescription())]
}
async getWeights(): Promise<weightsType> {
const verboseNames = this.getWeightNames();
const weights = await weightsStore.getWeightsMulti(verboseNames);
return weights;
}
async setWeights(weights: weightsType): Promise<StatusType[]> {
await weightsStore.setWeightsMulti(weights);
const scoredFeed: StatusType[] = []
for (const status of this.feed) {
if (!status["scores"]) {
return this.getFeed();
}
status["value"] = await this._getValueFromScores(status["scores"]);
scoredFeed.push(status);
}
this.feed = scoredFeed.sort((a, b) => (b.value ?? 0) - (a.value ?? 0));
return this.feed;
}
getDescription(verboseName: string): string {
const scorers = [...this.featureScorer, ...this.feedScorer];
const scorer = scorers.find(scorer => scorer.getVerboseName() === verboseName);
if (scorer) {
return scorer.getDescription();
}
return "";
}
async weightAdjust(statusWeights: weightsType): Promise<weightsType | undefined> {
//Adjust Weights based on user interaction
if (statusWeights == undefined) return;
const mean = Object.values(statusWeights).reduce((accumulator, currentValue) => accumulator + Math.abs(currentValue), 0) / Object.values(statusWeights).length;
const currentWeight: weightsType = await this.getWeights()
const currentMean = Object.values(currentWeight).reduce((accumulator, currentValue) => accumulator + currentValue, 0) / Object.values(currentWeight).length;
for (let key in currentWeight) {
let reweight = 1 - (Math.abs(statusWeights[key]) / mean) / (currentWeight[key] / currentMean);
currentWeight[key] = currentWeight[key] + 0.02 * currentWeight[key] * reweight;
console.log(reweight);
}
await this.setWeights(currentWeight);
return currentWeight;
}
} | src/index.ts | pkreissel-fedialgo-a1b7a40 | [
{
"filename": "src/Paginator.ts",
"retrieved_chunk": " private dataArray: StatusType[] = [];\n private algo: TheAlgorithm;\n constructor(api: mastodon.Client, user: mastodon.v1.Account, pageSize: number = 10) {\n this.algo = new TheAlgorithm(api, user);\n this.pageSize = pageSize;\n }\n async next(): Promise<IteratorResult<StatusType[]>> {\n if (this.dataArray.length == 0) {\n this.dataArray = await this.algo.getFeed();\n }",
"score": 9.948361925418439
},
{
"filename": "src/scorer/index.ts",
"retrieved_chunk": " interactsFeatureScorer,\n reblogsFeatureScorer,\n topPostFeatureScorer,\n diversityFeedScorer,\n reblogsFeedScorer,\n FeedScorer,\n FeatureScorer\n}",
"score": 6.5580429916906855
},
{
"filename": "src/scorer/index.ts",
"retrieved_chunk": "import favsFeatureScorer from \"./feature/favsFeatureScorer\";\nimport interactsFeatureScorer from \"./feature/interactsFeatureScorer\";\nimport reblogsFeatureScorer from \"./feature/reblogsFeatureScorer\";\nimport topPostFeatureScorer from \"./feature/topPostFeatureScorer\";\nimport diversityFeedScorer from \"./feed/diversityFeedScorer\";\nimport reblogsFeedScorer from \"./feed/reblogsFeedScorer\";\nimport FeedScorer from \"./FeedScorer\";\nimport FeatureScorer from \"./FeatureScorer\";\nexport {\n favsFeatureScorer,",
"score": 5.658718386921336
},
{
"filename": "src/scorer/feature/topPostFeatureScorer.ts",
"retrieved_chunk": "import FeatureScorer from '../FeatureScorer';\nimport { StatusType, accFeatureType } from \"../../types\";\nimport { mastodon } from \"masto\";\nimport FeatureStorage from \"../../features/FeatureStore\";\nexport default class topPostFeatureScorer extends FeatureScorer {\n constructor() {\n super({\n featureGetter: (api: mastodon.Client) => { return Promise.resolve({}) },\n verboseName: \"TopPosts\",\n description: \"Posts that are trending on multiple of your most popular instances\",",
"score": 5.114820174804789
},
{
"filename": "src/scorer/FeedScorer.ts",
"retrieved_chunk": " async score(status: mastodon.v1.Status) {\n if (!this._isReady) {\n throw new Error(\"FeedScorer not ready\");\n }\n return 0;\n }\n getVerboseName() {\n return this._verboseName;\n }\n getDescription() {",
"score": 5.092027918535485
}
] | typescript | (): Promise<StatusType[]> { |
import { mastodon } from "masto";
import { serverFeatureType, accFeatureType } from "../types";
import FavsFeature from "./favsFeature";
import reblogsFeature from "./reblogsFeature";
import interactsFeature from "./interactsFeature";
import coreServerFeature from "./coreServerFeature";
import Storage, { Key } from "../Storage";
export default class FeatureStorage extends Storage {
static async getTopFavs(api: mastodon.Client): Promise<accFeatureType> {
const topFavs: accFeatureType = await this.get(Key.TOP_FAVS) as accFeatureType;
console.log(topFavs);
if (topFavs != null && await this.getOpenings() < 10) {
return topFavs;
} else {
const favs = await FavsFeature(api);
await this.set(Key.TOP_FAVS, favs);
return favs;
}
}
static async getTopReblogs(api: mastodon.Client): Promise<accFeatureType> {
const topReblogs: accFeatureType = await this.get(Key.TOP_REBLOGS) as accFeatureType;
console.log(topReblogs);
if (topReblogs != null && await this.getOpenings() < 10) {
return topReblogs;
} else {
const reblogs = await reblogsFeature(api);
await this.set(Key.TOP_REBLOGS, reblogs);
return reblogs;
}
}
static async getTopInteracts(api: mastodon.Client): Promise<accFeatureType> {
const topInteracts: accFeatureType = await this.get(Key.TOP_INTERACTS) as accFeatureType;
console.log(topInteracts);
if (topInteracts != null && await this.getOpenings() < 10) {
return topInteracts;
} else {
const interacts = await interactsFeature(api);
await this.set(Key.TOP_INTERACTS, interacts);
return interacts;
}
}
static async getCoreServer(api: mastodon.Client): Promise<serverFeatureType> {
const coreServer: serverFeatureType = await this.get(Key.CORE_SERVER) as serverFeatureType;
console.log(coreServer);
if (coreServer != null && await this.getOpenings() < 10) {
return coreServer;
} else {
| const user = await this.getIdentity(); |
const server = await coreServerFeature(api, user);
await this.set(Key.CORE_SERVER, server);
return server;
}
}
}
| src/features/FeatureStore.ts | pkreissel-fedialgo-a1b7a40 | [
{
"filename": "src/Storage.ts",
"retrieved_chunk": "import AsyncStorage from '@react-native-async-storage/async-storage';\nimport { serverFeatureType, accFeatureType, weightsType } from \"./types\";\nimport { mastodon } from \"masto\";\nexport enum Key {\n TOP_FAVS = 'favs',\n TOP_REBLOGS = 'reblogs',\n TOP_INTERACTS = 'interacts',\n CORE_SERVER = 'coreServer',\n USER = 'algouser',\n WEIGHTS = 'weights',",
"score": 33.576055079623096
},
{
"filename": "src/Storage.ts",
"retrieved_chunk": " static async logOpening() {\n console.log(\"Logging Opening\")\n const openings = parseInt(await this.get(Key.OPENINGS, true) as string);\n if (openings == null || isNaN(openings)) {\n await this.set(Key.OPENINGS, \"1\", true);\n } else {\n await this.set(Key.OPENINGS, (openings + 1).toString(), true);\n }\n }\n static async getOpenings() {",
"score": 26.29191598371053
},
{
"filename": "src/Storage.ts",
"retrieved_chunk": " const openings = parseInt(await this.get(Key.OPENINGS, true) as string);\n return openings;\n }\n static async getIdentity(): Promise<mastodon.v1.Account> {\n const userJson = await AsyncStorage.getItem(Key.USER);\n const user: mastodon.v1.Account = userJson != null ? JSON.parse(userJson) : null;\n return user;\n }\n static async setIdentity(user: mastodon.v1.Account) {\n const userJson = JSON.stringify(user);",
"score": 23.201880198005952
},
{
"filename": "src/Storage.ts",
"retrieved_chunk": " OPENINGS = \"openings\",\n}\ntype StorageValue = serverFeatureType | accFeatureType | mastodon.v1.Account | weightsType | string\nexport default class Storage {\n protected static async get(key: Key, groupedByUser = true, suffix = \"\"): Promise<StorageValue> {\n const suffixKey = this.suffix(key, suffix);\n const storageKey = groupedByUser ? await this.prefix(suffixKey) : suffixKey;\n const jsonValue = await AsyncStorage.getItem(storageKey);\n const value = jsonValue != null ? JSON.parse(jsonValue) : null;\n return value != null ? value[storageKey] : null;",
"score": 18.576275631549976
},
{
"filename": "src/features/coreServerFeature.ts",
"retrieved_chunk": "import { mastodon } from \"masto\";\nimport { serverFeatureType } from \"../types\";\nexport default async function coreServerFeature(api: mastodon.Client, user: mastodon.v1.Account): Promise<serverFeatureType> {\n let results: mastodon.v1.Account[] = [];\n let pages = 10;\n for await (const page of api.v1.accounts.listFollowing(user.id, { limit: 80 })) {\n results = results.concat(page)\n pages--;\n if (pages === 0 || results.length < 80) {\n break;",
"score": 18.34233209291092
}
] | typescript | const user = await this.getIdentity(); |
import { mastodon } from "masto";
import { FeedFetcher, Scorer, StatusType, weightsType } from "./types";
import {
favsFeatureScorer,
interactsFeatureScorer,
reblogsFeatureScorer,
diversityFeedScorer,
reblogsFeedScorer,
FeatureScorer,
FeedScorer,
topPostFeatureScorer
} from "./scorer";
import weightsStore from "./weights/weightsStore";
import getHomeFeed from "./feeds/homeFeed";
import topPostsFeed from "./feeds/topPostsFeed";
import Storage from "./Storage";
import { StaticArrayPaginator } from "./Paginator"
export default class TheAlgorithm {
user: mastodon.v1.Account;
fetchers = [getHomeFeed, topPostsFeed]
featureScorer = [new favsFeatureScorer(), new reblogsFeatureScorer(), new interactsFeatureScorer(), new topPostFeatureScorer()]
feedScorer = [new reblogsFeedScorer(), new diversityFeedScorer()]
feed: StatusType[] = [];
api: mastodon.Client;
constructor(api: mastodon.Client, user: mastodon.v1.Account, valueCalculator: (((scores: weightsType) => Promise<number>) | null) = null) {
this.api = api;
this.user = user;
Storage.setIdentity(user);
Storage.logOpening();
if (valueCalculator) {
this._getValueFromScores = valueCalculator;
}
this.setDefaultWeights();
}
async getFeedAdvanced(
fetchers: Array<FeedFetcher>,
featureScorer: Array<FeatureScorer>,
feedScorer: Array<FeedScorer>
) {
this.fetchers = fetchers;
this.featureScorer = featureScorer;
this.feedScorer = feedScorer;
return this.getFeed();
}
async getFeed(): Promise<StatusType[]> {
const { fetchers, featureScorer, feedScorer } = this;
const response = await Promise.all(fetchers.map(fetcher => fetcher(this.api, this.user)))
this.feed = response.flat();
// Load and Prepare Features
await Promise.all(featureScorer.map(scorer => scorer.getFeature(this.api)));
await Promise.all(feedScorer.map(scorer => scorer.setFeed(this.feed)));
// Get Score Names
const scoreNames = featureScorer.map(scorer => scorer.getVerboseName());
const feedScoreNames = feedScorer.map(scorer => scorer.getVerboseName());
// Score Feed
let scoredFeed: StatusType[] = []
for (const status of this.feed) {
// Load Scores for each status
const featureScore = await Promise.all(featureScorer.map(scorer => scorer.score(this.api, status)));
const feedScore = await Promise.all(feedScorer.map(scorer => scorer.score(status)));
// Turn Scores into Weight Objects
const featureScoreObj = this._getScoreObj(scoreNames, featureScore);
const feedScoreObj = this._getScoreObj(feedScoreNames, feedScore);
const scoreObj = { ...featureScoreObj, ...feedScoreObj };
// Add Weight Object to Status
status["scores"] = scoreObj;
status["value"] = await this._getValueFromScores(scoreObj);
scoredFeed.push(status);
}
// Remove Replies, Stuff Already Retweeted, and Nulls
scoredFeed = scoredFeed
.filter((item: StatusType) => item != undefined)
.filter((item: StatusType) => item.inReplyToId === null)
.filter((item: StatusType) => item.content.includes("RT @") === false)
.filter((item: StatusType) => !(item?.reblog?.reblogged ?? false))
// Add Time Penalty
scoredFeed = scoredFeed.map((item: StatusType) => {
const seconds = Math.floor((new Date().getTime() - new Date(item.createdAt).getTime()) / 1000);
const timediscount = Math.pow((1 + 0.7 * 0.2), -Math.pow((seconds / 3600), 2));
item.value = (item.value ?? 0) * timediscount
return item;
})
// Sort Feed
scoredFeed = scoredFeed.sort((a, b) => (b.value ?? 0) - (a.value ?? 0));
//Remove duplicates
scoredFeed = [...new Map(scoredFeed.map((item: StatusType) => [item["uri"], item])).values()];
this.feed = scoredFeed
console.log(this.feed);
return this.feed;
}
private _getScoreObj(scoreNames: string[], scores: number[]): weightsType {
return scoreNames.reduce((obj: weightsType, cur, i) => {
obj[cur] = scores[i];
return obj;
}, {});
}
private async _getValueFromScores(scores: weightsType): Promise<number> {
const weights = await weightsStore.getWeightsMulti(Object.keys(scores));
const weightedScores = Object.keys(scores).reduce((obj: number, cur) => {
obj = obj + (scores[cur] * weights[cur] ?? 0)
return obj;
}, 0);
return weightedScores;
}
getWeightNames(): string[] {
const scorers = [...this.featureScorer, ...this.feedScorer];
return [...scorers.map(scorer => scorer.getVerboseName())]
}
async setDefaultWeights(): Promise<void> {
//Set Default Weights if they don't exist
const scorers = [...this.featureScorer, ...this.feedScorer];
Promise.all(scorers.map( | scorer => weightsStore.defaultFallback(scorer.getVerboseName(), scorer.getDefaultWeight())))
} |
getWeightDescriptions(): string[] {
const scorers = [...this.featureScorer, ...this.feedScorer];
return [...scorers.map(scorer => scorer.getDescription())]
}
async getWeights(): Promise<weightsType> {
const verboseNames = this.getWeightNames();
const weights = await weightsStore.getWeightsMulti(verboseNames);
return weights;
}
async setWeights(weights: weightsType): Promise<StatusType[]> {
await weightsStore.setWeightsMulti(weights);
const scoredFeed: StatusType[] = []
for (const status of this.feed) {
if (!status["scores"]) {
return this.getFeed();
}
status["value"] = await this._getValueFromScores(status["scores"]);
scoredFeed.push(status);
}
this.feed = scoredFeed.sort((a, b) => (b.value ?? 0) - (a.value ?? 0));
return this.feed;
}
getDescription(verboseName: string): string {
const scorers = [...this.featureScorer, ...this.feedScorer];
const scorer = scorers.find(scorer => scorer.getVerboseName() === verboseName);
if (scorer) {
return scorer.getDescription();
}
return "";
}
async weightAdjust(statusWeights: weightsType): Promise<weightsType | undefined> {
//Adjust Weights based on user interaction
if (statusWeights == undefined) return;
const mean = Object.values(statusWeights).reduce((accumulator, currentValue) => accumulator + Math.abs(currentValue), 0) / Object.values(statusWeights).length;
const currentWeight: weightsType = await this.getWeights()
const currentMean = Object.values(currentWeight).reduce((accumulator, currentValue) => accumulator + currentValue, 0) / Object.values(currentWeight).length;
for (let key in currentWeight) {
let reweight = 1 - (Math.abs(statusWeights[key]) / mean) / (currentWeight[key] / currentMean);
currentWeight[key] = currentWeight[key] + 0.02 * currentWeight[key] * reweight;
console.log(reweight);
}
await this.setWeights(currentWeight);
return currentWeight;
}
} | src/index.ts | pkreissel-fedialgo-a1b7a40 | [
{
"filename": "src/scorer/FeatureScorer.ts",
"retrieved_chunk": " return 0\n }\n getVerboseName() {\n return this._verboseName;\n }\n getDescription() {\n return this._description;\n }\n getDefaultWeight() {\n return this._defaultWeight;",
"score": 15.9883070400766
},
{
"filename": "src/feeds/topPostsFeed.ts",
"retrieved_chunk": " results = await Promise.all(servers.map(async (server: string): Promise<mastodon.v1.Status[]> => {\n if (server === \"undefined\" || typeof server == \"undefined\" || server === \"\") return [];\n let res;\n try {\n res = await fetch(\"https://\" + server + \"/api/v1/trends/statuses\")\n }\n catch (e) {\n return [];\n }\n if (!res.ok) {",
"score": 15.033285881296836
},
{
"filename": "src/scorer/FeedScorer.ts",
"retrieved_chunk": " async score(status: mastodon.v1.Status) {\n if (!this._isReady) {\n throw new Error(\"FeedScorer not ready\");\n }\n return 0;\n }\n getVerboseName() {\n return this._verboseName;\n }\n getDescription() {",
"score": 10.59204950684401
},
{
"filename": "src/feeds/topPostsFeed.ts",
"retrieved_chunk": " return [];\n }\n const data: any[] = serializer.deserialize('application/json', await res.text());\n if (data === undefined) {\n return [];\n }\n return data.map((status: any) => {\n status.topPost = true;\n return status;\n }).slice(0, 10)",
"score": 9.286734966389877
},
{
"filename": "src/scorer/FeedScorer.ts",
"retrieved_chunk": " return this._description;\n }\n getDefaultWeight() {\n return this._defaultWeight;\n }\n}",
"score": 7.8127975368533065
}
] | typescript | scorer => weightsStore.defaultFallback(scorer.getVerboseName(), scorer.getDefaultWeight())))
} |
import { mastodon } from "masto";
import { FeedFetcher, Scorer, StatusType, weightsType } from "./types";
import {
favsFeatureScorer,
interactsFeatureScorer,
reblogsFeatureScorer,
diversityFeedScorer,
reblogsFeedScorer,
FeatureScorer,
FeedScorer,
topPostFeatureScorer
} from "./scorer";
import weightsStore from "./weights/weightsStore";
import getHomeFeed from "./feeds/homeFeed";
import topPostsFeed from "./feeds/topPostsFeed";
import Storage from "./Storage";
import { StaticArrayPaginator } from "./Paginator"
export default class TheAlgorithm {
user: mastodon.v1.Account;
fetchers = [getHomeFeed, topPostsFeed]
featureScorer = [new favsFeatureScorer(), new reblogsFeatureScorer(), new interactsFeatureScorer(), new topPostFeatureScorer()]
feedScorer = [new reblogsFeedScorer(), new diversityFeedScorer()]
feed: StatusType[] = [];
api: mastodon.Client;
constructor(api: mastodon.Client, user: mastodon.v1.Account, valueCalculator: (((scores: weightsType) => Promise<number>) | null) = null) {
this.api = api;
this.user = user;
Storage.setIdentity(user);
Storage.logOpening();
if (valueCalculator) {
this._getValueFromScores = valueCalculator;
}
this.setDefaultWeights();
}
async getFeedAdvanced(
fetchers: Array<FeedFetcher>,
featureScorer: Array<FeatureScorer>,
feedScorer: Array<FeedScorer>
) {
this.fetchers = fetchers;
this.featureScorer = featureScorer;
this.feedScorer = feedScorer;
return this.getFeed();
}
async getFeed(): Promise<StatusType[]> {
const { fetchers, featureScorer, feedScorer } = this;
const response = await Promise.all(fetchers.map(fetcher => fetcher(this.api, this.user)))
this.feed = response.flat();
// Load and Prepare Features
await Promise.all(featureScorer.map(scorer => scorer.getFeature(this.api)));
await Promise.all(feedScorer.map(scorer => scorer.setFeed(this.feed)));
// Get Score Names
const scoreNames = featureScorer.map(scorer => scorer.getVerboseName());
const feedScoreNames = feedScorer.map(scorer => scorer.getVerboseName());
// Score Feed
let scoredFeed: StatusType[] = []
for (const status of this.feed) {
// Load Scores for each status
const featureScore = await Promise.all(featureScorer.map(scorer => scorer.score(this.api, status)));
const feedScore = await Promise.all(feedScorer.map(scorer => scorer.score(status)));
// Turn Scores into Weight Objects
const featureScoreObj = this._getScoreObj(scoreNames, featureScore);
const feedScoreObj = this._getScoreObj(feedScoreNames, feedScore);
const scoreObj = { ...featureScoreObj, ...feedScoreObj };
// Add Weight Object to Status
status["scores"] = scoreObj;
status["value"] = await this._getValueFromScores(scoreObj);
scoredFeed.push(status);
}
// Remove Replies, Stuff Already Retweeted, and Nulls
scoredFeed = scoredFeed
.filter((item: StatusType) => item != undefined)
.filter((item: StatusType) => item.inReplyToId === null)
.filter((item: StatusType) => item.content.includes("RT @") === false)
.filter((item: StatusType) => !(item?.reblog?.reblogged ?? false))
// Add Time Penalty
scoredFeed = scoredFeed.map((item: StatusType) => {
const seconds = Math.floor((new Date().getTime() - new Date(item.createdAt).getTime()) / 1000);
const timediscount = Math.pow((1 + 0.7 * 0.2), -Math.pow((seconds / 3600), 2));
item.value = (item.value ?? 0) * timediscount
return item;
})
// Sort Feed
scoredFeed = scoredFeed.sort((a, b) => (b.value ?? 0) - (a.value ?? 0));
//Remove duplicates
scoredFeed = [...new Map(scoredFeed | .map((item: StatusType) => [item["uri"], item])).values()]; |
this.feed = scoredFeed
console.log(this.feed);
return this.feed;
}
private _getScoreObj(scoreNames: string[], scores: number[]): weightsType {
return scoreNames.reduce((obj: weightsType, cur, i) => {
obj[cur] = scores[i];
return obj;
}, {});
}
private async _getValueFromScores(scores: weightsType): Promise<number> {
const weights = await weightsStore.getWeightsMulti(Object.keys(scores));
const weightedScores = Object.keys(scores).reduce((obj: number, cur) => {
obj = obj + (scores[cur] * weights[cur] ?? 0)
return obj;
}, 0);
return weightedScores;
}
getWeightNames(): string[] {
const scorers = [...this.featureScorer, ...this.feedScorer];
return [...scorers.map(scorer => scorer.getVerboseName())]
}
async setDefaultWeights(): Promise<void> {
//Set Default Weights if they don't exist
const scorers = [...this.featureScorer, ...this.feedScorer];
Promise.all(scorers.map(scorer => weightsStore.defaultFallback(scorer.getVerboseName(), scorer.getDefaultWeight())))
}
getWeightDescriptions(): string[] {
const scorers = [...this.featureScorer, ...this.feedScorer];
return [...scorers.map(scorer => scorer.getDescription())]
}
async getWeights(): Promise<weightsType> {
const verboseNames = this.getWeightNames();
const weights = await weightsStore.getWeightsMulti(verboseNames);
return weights;
}
async setWeights(weights: weightsType): Promise<StatusType[]> {
await weightsStore.setWeightsMulti(weights);
const scoredFeed: StatusType[] = []
for (const status of this.feed) {
if (!status["scores"]) {
return this.getFeed();
}
status["value"] = await this._getValueFromScores(status["scores"]);
scoredFeed.push(status);
}
this.feed = scoredFeed.sort((a, b) => (b.value ?? 0) - (a.value ?? 0));
return this.feed;
}
getDescription(verboseName: string): string {
const scorers = [...this.featureScorer, ...this.feedScorer];
const scorer = scorers.find(scorer => scorer.getVerboseName() === verboseName);
if (scorer) {
return scorer.getDescription();
}
return "";
}
async weightAdjust(statusWeights: weightsType): Promise<weightsType | undefined> {
//Adjust Weights based on user interaction
if (statusWeights == undefined) return;
const mean = Object.values(statusWeights).reduce((accumulator, currentValue) => accumulator + Math.abs(currentValue), 0) / Object.values(statusWeights).length;
const currentWeight: weightsType = await this.getWeights()
const currentMean = Object.values(currentWeight).reduce((accumulator, currentValue) => accumulator + currentValue, 0) / Object.values(currentWeight).length;
for (let key in currentWeight) {
let reweight = 1 - (Math.abs(statusWeights[key]) / mean) / (currentWeight[key] / currentMean);
currentWeight[key] = currentWeight[key] + 0.02 * currentWeight[key] * reweight;
console.log(reweight);
}
await this.setWeights(currentWeight);
return currentWeight;
}
} | src/index.ts | pkreissel-fedialgo-a1b7a40 | [
{
"filename": "src/Paginator.ts",
"retrieved_chunk": " const data: StatusType[] = [];\n let hasNextPage = false;\n const startIndex = this.currentIndex;\n const endIndex = this.currentIndex + this.pageSize;\n const currentData = this.dataArray.slice(startIndex, endIndex);\n currentData.forEach((item) => data.push(item));\n if (endIndex < this.dataArray.length) {\n hasNextPage = true;\n }\n this.currentIndex += this.pageSize;",
"score": 36.54526384208836
},
{
"filename": "src/feeds/topPostsFeed.ts",
"retrieved_chunk": "import { SerializerNativeImpl, mastodon } from \"masto\";\nimport FeatureStore from \"../features/FeatureStore\";\nexport default async function getTopPostFeed(api: mastodon.Client): Promise<mastodon.v1.Status[]> {\n const core_servers = await FeatureStore.getCoreServer(api)\n let results: any[] = [];\n const serializer = new SerializerNativeImpl();\n //Get Top Servers\n const servers = Object.keys(core_servers).sort((a, b) => {\n return core_servers[b] - core_servers[a]\n }).slice(0, 10)",
"score": 28.699640298881235
},
{
"filename": "src/feeds/homeFeed.ts",
"retrieved_chunk": "import { mastodon } from \"masto\";\nexport default async function getHomeFeed(api: mastodon.Client, user: mastodon.v1.Account) {\n let results: any[] = [];\n let pages = 10;\n for await (const page of api.v1.timelines.listHome()) {\n results = results.concat(page)\n pages--;\n //check if status is less than 12 hours old\n if (pages === 0 || new Date(page[0].createdAt) < new Date(Date.now() - 43200000)) {\n break;",
"score": 26.511236325387415
},
{
"filename": "src/Paginator.ts",
"retrieved_chunk": " return {\n done: !hasNextPage,\n value: data as StatusType[]\n };\n }\n [Symbol.asyncIterator]() {\n return this\n }\n}",
"score": 15.948446449235554
},
{
"filename": "src/scorer/feature/interactsFeatureScorer.ts",
"retrieved_chunk": " defaultWeight: 2,\n })\n }\n async score(api: mastodon.Client, status: StatusType) {\n return (status.account.acct in this.feature) ? this.feature[status.account.acct] : 0\n }\n}",
"score": 15.483619562376234
}
] | typescript | .map((item: StatusType) => [item["uri"], item])).values()]; |
import { mastodon } from "masto";
import { serverFeatureType, accFeatureType } from "../types";
import FavsFeature from "./favsFeature";
import reblogsFeature from "./reblogsFeature";
import interactsFeature from "./interactsFeature";
import coreServerFeature from "./coreServerFeature";
import Storage, { Key } from "../Storage";
export default class FeatureStorage extends Storage {
static async getTopFavs(api: mastodon.Client): Promise<accFeatureType> {
const topFavs: accFeatureType = await this.get(Key.TOP_FAVS) as accFeatureType;
console.log(topFavs);
if (topFavs != null && await this.getOpenings() < 10) {
return topFavs;
} else {
const favs = await FavsFeature(api);
await this.set(Key.TOP_FAVS, favs);
return favs;
}
}
static async getTopReblogs(api: mastodon.Client): Promise<accFeatureType> {
const topReblogs: accFeatureType = await this.get(Key.TOP_REBLOGS) as accFeatureType;
console.log(topReblogs);
if (topReblogs != null && await this.getOpenings() < 10) {
return topReblogs;
} else {
const reblogs = await reblogsFeature(api);
await this.set(Key.TOP_REBLOGS, reblogs);
return reblogs;
}
}
static async getTopInteracts(api: mastodon.Client): Promise<accFeatureType> {
const topInteracts: accFeatureType = await this.get(Key.TOP_INTERACTS) as accFeatureType;
console.log(topInteracts);
if (topInteracts != null && await this.getOpenings() < 10) {
return topInteracts;
} else {
const interacts = await interactsFeature(api);
await this.set(Key.TOP_INTERACTS, interacts);
return interacts;
}
}
static async getCoreServer(api: mastodon.Client): Promise<serverFeatureType> {
const coreServer: serverFeatureType = await this.get(Key.CORE_SERVER) as serverFeatureType;
console.log(coreServer);
if (coreServer != null && await this.getOpenings() < 10) {
return coreServer;
} else {
const user = await this.getIdentity();
| const server = await coreServerFeature(api, user); |
await this.set(Key.CORE_SERVER, server);
return server;
}
}
}
| src/features/FeatureStore.ts | pkreissel-fedialgo-a1b7a40 | [
{
"filename": "src/Storage.ts",
"retrieved_chunk": "import AsyncStorage from '@react-native-async-storage/async-storage';\nimport { serverFeatureType, accFeatureType, weightsType } from \"./types\";\nimport { mastodon } from \"masto\";\nexport enum Key {\n TOP_FAVS = 'favs',\n TOP_REBLOGS = 'reblogs',\n TOP_INTERACTS = 'interacts',\n CORE_SERVER = 'coreServer',\n USER = 'algouser',\n WEIGHTS = 'weights',",
"score": 29.645046923288618
},
{
"filename": "src/Storage.ts",
"retrieved_chunk": " static async logOpening() {\n console.log(\"Logging Opening\")\n const openings = parseInt(await this.get(Key.OPENINGS, true) as string);\n if (openings == null || isNaN(openings)) {\n await this.set(Key.OPENINGS, \"1\", true);\n } else {\n await this.set(Key.OPENINGS, (openings + 1).toString(), true);\n }\n }\n static async getOpenings() {",
"score": 27.16730712255963
},
{
"filename": "src/Storage.ts",
"retrieved_chunk": " const openings = parseInt(await this.get(Key.OPENINGS, true) as string);\n return openings;\n }\n static async getIdentity(): Promise<mastodon.v1.Account> {\n const userJson = await AsyncStorage.getItem(Key.USER);\n const user: mastodon.v1.Account = userJson != null ? JSON.parse(userJson) : null;\n return user;\n }\n static async setIdentity(user: mastodon.v1.Account) {\n const userJson = JSON.stringify(user);",
"score": 26.303562652360874
},
{
"filename": "src/features/coreServerFeature.ts",
"retrieved_chunk": "import { mastodon } from \"masto\";\nimport { serverFeatureType } from \"../types\";\nexport default async function coreServerFeature(api: mastodon.Client, user: mastodon.v1.Account): Promise<serverFeatureType> {\n let results: mastodon.v1.Account[] = [];\n let pages = 10;\n for await (const page of api.v1.accounts.listFollowing(user.id, { limit: 80 })) {\n results = results.concat(page)\n pages--;\n if (pages === 0 || results.length < 80) {\n break;",
"score": 25.283161543240922
},
{
"filename": "src/features/coreServerFeature.ts",
"retrieved_chunk": " }\n }\n const serverFrequ = results.reduce((accumulator: serverFeatureType, follower: mastodon.v1.Account) => {\n const server = follower.url.split(\"@\")[0].split(\"https://\")[1];\n if (server in accumulator) {\n accumulator[server] += 1;\n } else {\n accumulator[server] = 1;\n }\n return accumulator",
"score": 19.113338573390052
}
] | typescript | const server = await coreServerFeature(api, user); |
import { mastodon } from "masto";
import { FeedFetcher, Scorer, StatusType, weightsType } from "./types";
import {
favsFeatureScorer,
interactsFeatureScorer,
reblogsFeatureScorer,
diversityFeedScorer,
reblogsFeedScorer,
FeatureScorer,
FeedScorer,
topPostFeatureScorer
} from "./scorer";
import weightsStore from "./weights/weightsStore";
import getHomeFeed from "./feeds/homeFeed";
import topPostsFeed from "./feeds/topPostsFeed";
import Storage from "./Storage";
import { StaticArrayPaginator } from "./Paginator"
export default class TheAlgorithm {
user: mastodon.v1.Account;
fetchers = [getHomeFeed, topPostsFeed]
featureScorer = [new favsFeatureScorer(), new reblogsFeatureScorer(), new interactsFeatureScorer(), new topPostFeatureScorer()]
feedScorer = [new reblogsFeedScorer(), new diversityFeedScorer()]
feed: StatusType[] = [];
api: mastodon.Client;
constructor(api: mastodon.Client, user: mastodon.v1.Account, valueCalculator: (((scores: weightsType) => Promise<number>) | null) = null) {
this.api = api;
this.user = user;
Storage.setIdentity(user);
Storage.logOpening();
if (valueCalculator) {
this._getValueFromScores = valueCalculator;
}
this.setDefaultWeights();
}
async getFeedAdvanced(
fetchers: Array<FeedFetcher>,
featureScorer: Array<FeatureScorer>,
feedScorer: Array<FeedScorer>
) {
this.fetchers = fetchers;
this.featureScorer = featureScorer;
this.feedScorer = feedScorer;
return this.getFeed();
}
async getFeed(): Promise<StatusType[]> {
const { fetchers, featureScorer, feedScorer } = this;
const response = await Promise.all(fetchers.map(fetcher => fetcher(this.api, this.user)))
this.feed = response.flat();
// Load and Prepare Features
await Promise.all(featureScorer.map(scorer => scorer.getFeature(this.api)));
await Promise.all(feedScorer.map(scorer => scorer.setFeed(this.feed)));
// Get Score Names
const scoreNames = featureScorer.map(scorer => scorer.getVerboseName());
const feedScoreNames = feedScorer.map(scorer => scorer.getVerboseName());
// Score Feed
let scoredFeed: StatusType[] = []
for (const status of this.feed) {
// Load Scores for each status
const featureScore = await Promise.all | (featureScorer.map(scorer => scorer.score(this.api, status))); |
const feedScore = await Promise.all(feedScorer.map(scorer => scorer.score(status)));
// Turn Scores into Weight Objects
const featureScoreObj = this._getScoreObj(scoreNames, featureScore);
const feedScoreObj = this._getScoreObj(feedScoreNames, feedScore);
const scoreObj = { ...featureScoreObj, ...feedScoreObj };
// Add Weight Object to Status
status["scores"] = scoreObj;
status["value"] = await this._getValueFromScores(scoreObj);
scoredFeed.push(status);
}
// Remove Replies, Stuff Already Retweeted, and Nulls
scoredFeed = scoredFeed
.filter((item: StatusType) => item != undefined)
.filter((item: StatusType) => item.inReplyToId === null)
.filter((item: StatusType) => item.content.includes("RT @") === false)
.filter((item: StatusType) => !(item?.reblog?.reblogged ?? false))
// Add Time Penalty
scoredFeed = scoredFeed.map((item: StatusType) => {
const seconds = Math.floor((new Date().getTime() - new Date(item.createdAt).getTime()) / 1000);
const timediscount = Math.pow((1 + 0.7 * 0.2), -Math.pow((seconds / 3600), 2));
item.value = (item.value ?? 0) * timediscount
return item;
})
// Sort Feed
scoredFeed = scoredFeed.sort((a, b) => (b.value ?? 0) - (a.value ?? 0));
//Remove duplicates
scoredFeed = [...new Map(scoredFeed.map((item: StatusType) => [item["uri"], item])).values()];
this.feed = scoredFeed
console.log(this.feed);
return this.feed;
}
private _getScoreObj(scoreNames: string[], scores: number[]): weightsType {
return scoreNames.reduce((obj: weightsType, cur, i) => {
obj[cur] = scores[i];
return obj;
}, {});
}
private async _getValueFromScores(scores: weightsType): Promise<number> {
const weights = await weightsStore.getWeightsMulti(Object.keys(scores));
const weightedScores = Object.keys(scores).reduce((obj: number, cur) => {
obj = obj + (scores[cur] * weights[cur] ?? 0)
return obj;
}, 0);
return weightedScores;
}
getWeightNames(): string[] {
const scorers = [...this.featureScorer, ...this.feedScorer];
return [...scorers.map(scorer => scorer.getVerboseName())]
}
async setDefaultWeights(): Promise<void> {
//Set Default Weights if they don't exist
const scorers = [...this.featureScorer, ...this.feedScorer];
Promise.all(scorers.map(scorer => weightsStore.defaultFallback(scorer.getVerboseName(), scorer.getDefaultWeight())))
}
getWeightDescriptions(): string[] {
const scorers = [...this.featureScorer, ...this.feedScorer];
return [...scorers.map(scorer => scorer.getDescription())]
}
async getWeights(): Promise<weightsType> {
const verboseNames = this.getWeightNames();
const weights = await weightsStore.getWeightsMulti(verboseNames);
return weights;
}
async setWeights(weights: weightsType): Promise<StatusType[]> {
await weightsStore.setWeightsMulti(weights);
const scoredFeed: StatusType[] = []
for (const status of this.feed) {
if (!status["scores"]) {
return this.getFeed();
}
status["value"] = await this._getValueFromScores(status["scores"]);
scoredFeed.push(status);
}
this.feed = scoredFeed.sort((a, b) => (b.value ?? 0) - (a.value ?? 0));
return this.feed;
}
getDescription(verboseName: string): string {
const scorers = [...this.featureScorer, ...this.feedScorer];
const scorer = scorers.find(scorer => scorer.getVerboseName() === verboseName);
if (scorer) {
return scorer.getDescription();
}
return "";
}
async weightAdjust(statusWeights: weightsType): Promise<weightsType | undefined> {
//Adjust Weights based on user interaction
if (statusWeights == undefined) return;
const mean = Object.values(statusWeights).reduce((accumulator, currentValue) => accumulator + Math.abs(currentValue), 0) / Object.values(statusWeights).length;
const currentWeight: weightsType = await this.getWeights()
const currentMean = Object.values(currentWeight).reduce((accumulator, currentValue) => accumulator + currentValue, 0) / Object.values(currentWeight).length;
for (let key in currentWeight) {
let reweight = 1 - (Math.abs(statusWeights[key]) / mean) / (currentWeight[key] / currentMean);
currentWeight[key] = currentWeight[key] + 0.02 * currentWeight[key] * reweight;
console.log(reweight);
}
await this.setWeights(currentWeight);
return currentWeight;
}
} | src/index.ts | pkreissel-fedialgo-a1b7a40 | [
{
"filename": "src/feeds/topPostsFeed.ts",
"retrieved_chunk": " results = await Promise.all(servers.map(async (server: string): Promise<mastodon.v1.Status[]> => {\n if (server === \"undefined\" || typeof server == \"undefined\" || server === \"\") return [];\n let res;\n try {\n res = await fetch(\"https://\" + server + \"/api/v1/trends/statuses\")\n }\n catch (e) {\n return [];\n }\n if (!res.ok) {",
"score": 24.723392331377937
},
{
"filename": "src/feeds/topPostsFeed.ts",
"retrieved_chunk": " return [];\n }\n const data: any[] = serializer.deserialize('application/json', await res.text());\n if (data === undefined) {\n return [];\n }\n return data.map((status: any) => {\n status.topPost = true;\n return status;\n }).slice(0, 10)",
"score": 20.85619741864775
},
{
"filename": "src/scorer/FeedScorer.ts",
"retrieved_chunk": " this._description = description || \"\";\n this._defaultWeight = defaultWeight || 1;\n }\n async setFeed(feed: StatusType[]) {\n this.features = await this.feedExtractor(feed);\n this._isReady = true;\n }\n feedExtractor(feed: StatusType[]): any {\n throw new Error(\"Method not implemented.\");\n }",
"score": 15.661169148655558
},
{
"filename": "src/scorer/FeedScorer.ts",
"retrieved_chunk": " async score(status: mastodon.v1.Status) {\n if (!this._isReady) {\n throw new Error(\"FeedScorer not ready\");\n }\n return 0;\n }\n getVerboseName() {\n return this._verboseName;\n }\n getDescription() {",
"score": 14.205845570083103
},
{
"filename": "src/scorer/feed/diversityFeedScorer.ts",
"retrieved_chunk": "import FeedScorer from \"../FeedScorer\";\nimport { StatusType } from \"../../types\";\nexport default class diversityFeedScorer extends FeedScorer {\n constructor() {\n super(\"Diversity\", \"Downranks posts from users that you have seen a lot of posts from\");\n }\n feedExtractor(feed: StatusType[]) {\n return feed.reduce((obj: any, status) => {\n obj[status.account.acct] = (obj[status.account.acct] || 0) - 1;\n return obj;",
"score": 13.077712992403006
}
] | typescript | (featureScorer.map(scorer => scorer.score(this.api, status))); |
import { mastodon } from "masto";
import { FeedFetcher, Scorer, StatusType, weightsType } from "./types";
import {
favsFeatureScorer,
interactsFeatureScorer,
reblogsFeatureScorer,
diversityFeedScorer,
reblogsFeedScorer,
FeatureScorer,
FeedScorer,
topPostFeatureScorer
} from "./scorer";
import weightsStore from "./weights/weightsStore";
import getHomeFeed from "./feeds/homeFeed";
import topPostsFeed from "./feeds/topPostsFeed";
import Storage from "./Storage";
import { StaticArrayPaginator } from "./Paginator"
export default class TheAlgorithm {
user: mastodon.v1.Account;
fetchers = [getHomeFeed, topPostsFeed]
featureScorer = [new favsFeatureScorer(), new reblogsFeatureScorer(), new interactsFeatureScorer(), new topPostFeatureScorer()]
feedScorer = [new reblogsFeedScorer(), new diversityFeedScorer()]
feed: StatusType[] = [];
api: mastodon.Client;
constructor(api: mastodon.Client, user: mastodon.v1.Account, valueCalculator: (((scores: weightsType) => Promise<number>) | null) = null) {
this.api = api;
this.user = user;
Storage.setIdentity(user);
Storage.logOpening();
if (valueCalculator) {
this._getValueFromScores = valueCalculator;
}
this.setDefaultWeights();
}
async getFeedAdvanced(
fetchers: Array<FeedFetcher>,
featureScorer: Array<FeatureScorer>,
feedScorer: Array<FeedScorer>
) {
this.fetchers = fetchers;
this.featureScorer = featureScorer;
this.feedScorer = feedScorer;
return this.getFeed();
}
async getFeed(): Promise<StatusType[]> {
const { fetchers, featureScorer, feedScorer } = this;
const response = await Promise.all(fetchers.map(fetcher => fetcher(this.api, this.user)))
this.feed = response.flat();
// Load and Prepare Features
await Promise.all(featureScorer.map(scorer => scorer.getFeature(this.api)));
await Promise.all(feedScorer.map(scorer => scorer.setFeed(this.feed)));
// Get Score Names
const scoreNames = featureScorer.map(scorer => scorer.getVerboseName());
const feedScoreNames = feedScorer.map(scorer => scorer.getVerboseName());
// Score Feed
let scoredFeed: StatusType[] = []
for (const status of this.feed) {
// Load Scores for each status
const featureScore = await Promise.all(featureScorer.map(scorer => scorer.score(this.api, status)));
const feedScore = await Promise.all(feedScorer.map(scorer => scorer.score(status)));
// Turn Scores into Weight Objects
const featureScoreObj = this._getScoreObj(scoreNames, featureScore);
const feedScoreObj = this._getScoreObj(feedScoreNames, feedScore);
const scoreObj = { ...featureScoreObj, ...feedScoreObj };
// Add Weight Object to Status
status["scores"] = scoreObj;
status["value"] = await this._getValueFromScores(scoreObj);
scoredFeed.push(status);
}
// Remove Replies, Stuff Already Retweeted, and Nulls
scoredFeed = scoredFeed
.filter((item: StatusType) => item != undefined)
.filter((item: StatusType) => item.inReplyToId === null)
.filter((item: StatusType) => item.content.includes("RT @") === false)
.filter((item: StatusType) => !(item?.reblog?.reblogged ?? false))
// Add Time Penalty
scoredFeed = scoredFeed.map((item: StatusType) => {
const seconds = Math.floor((new Date().getTime() - new Date(item.createdAt).getTime()) / 1000);
const timediscount = Math.pow((1 + 0.7 * 0.2), -Math.pow((seconds / 3600), 2));
item.value = (item.value ?? 0) * timediscount
return item;
})
// Sort Feed
scoredFeed = scoredFeed.sort((a, b) => (b.value ?? 0) - (a.value ?? 0));
//Remove duplicates
scoredFeed = [...new Map(scoredFeed.map((item: StatusType) => [item["uri"], item])).values()];
this.feed = scoredFeed
console.log(this.feed);
return this.feed;
}
private _getScoreObj(scoreNames: string[], scores: number[]): weightsType {
return scoreNames.reduce((obj: weightsType, cur, i) => {
obj[cur] = scores[i];
return obj;
}, {});
}
private async _getValueFromScores(scores: weightsType): Promise<number> {
const weights = await weightsStore.getWeightsMulti(Object.keys(scores));
const weightedScores = Object.keys(scores).reduce((obj: number, cur) => {
obj = obj + (scores[cur] * weights[cur] ?? 0)
return obj;
}, 0);
return weightedScores;
}
getWeightNames(): string[] {
const scorers = [...this.featureScorer, ...this.feedScorer];
return [...scorers.map(scorer => scorer.getVerboseName())]
}
async setDefaultWeights(): Promise<void> {
//Set Default Weights if they don't exist
const scorers = [...this.featureScorer, ...this.feedScorer];
Promise.all(scorers.map(scorer => weightsStore.defaultFallback(scorer.getVerboseName(), scorer.getDefaultWeight())))
}
getWeightDescriptions(): string[] {
const scorers = [...this.featureScorer, ...this.feedScorer];
return [...scorers.map(scorer => scorer.getDescription())]
}
async getWeights(): Promise<weightsType> {
const verboseNames = this.getWeightNames();
const weights = await weightsStore.getWeightsMulti(verboseNames);
return weights;
}
| async setWeights(weights: weightsType): Promise<StatusType[]> { |
await weightsStore.setWeightsMulti(weights);
const scoredFeed: StatusType[] = []
for (const status of this.feed) {
if (!status["scores"]) {
return this.getFeed();
}
status["value"] = await this._getValueFromScores(status["scores"]);
scoredFeed.push(status);
}
this.feed = scoredFeed.sort((a, b) => (b.value ?? 0) - (a.value ?? 0));
return this.feed;
}
getDescription(verboseName: string): string {
const scorers = [...this.featureScorer, ...this.feedScorer];
const scorer = scorers.find(scorer => scorer.getVerboseName() === verboseName);
if (scorer) {
return scorer.getDescription();
}
return "";
}
async weightAdjust(statusWeights: weightsType): Promise<weightsType | undefined> {
//Adjust Weights based on user interaction
if (statusWeights == undefined) return;
const mean = Object.values(statusWeights).reduce((accumulator, currentValue) => accumulator + Math.abs(currentValue), 0) / Object.values(statusWeights).length;
const currentWeight: weightsType = await this.getWeights()
const currentMean = Object.values(currentWeight).reduce((accumulator, currentValue) => accumulator + currentValue, 0) / Object.values(currentWeight).length;
for (let key in currentWeight) {
let reweight = 1 - (Math.abs(statusWeights[key]) / mean) / (currentWeight[key] / currentMean);
currentWeight[key] = currentWeight[key] + 0.02 * currentWeight[key] * reweight;
console.log(reweight);
}
await this.setWeights(currentWeight);
return currentWeight;
}
} | src/index.ts | pkreissel-fedialgo-a1b7a40 | [
{
"filename": "src/weights/weightsStore.ts",
"retrieved_chunk": " static async setWeights(weights: weightsType, verboseName: string) {\n await this.set(Key.WEIGHTS, weights, true, verboseName);\n }\n static async getWeightsMulti(verboseNames: string[]) {\n const weights: weightsType = {}\n for (const verboseName of verboseNames) {\n const weight = await this.getWeight(verboseName);\n weights[verboseName] = weight[verboseName]\n }\n return weights;",
"score": 43.31019420231448
},
{
"filename": "src/weights/weightsStore.ts",
"retrieved_chunk": " }\n static async setWeightsMulti(weights: weightsType) {\n for (const verboseName in weights) {\n await this.setWeights({ [verboseName]: weights[verboseName] }, verboseName);\n }\n }\n static async defaultFallback(verboseName: string, defaultWeight: number): Promise<boolean> {\n // If the weight is not set, set it to the default weight\n const weight = await this.get(Key.WEIGHTS, true, verboseName) as weightsType;\n if (weight == null) {",
"score": 24.657250530796706
},
{
"filename": "src/weights/weightsStore.ts",
"retrieved_chunk": "import { weightsType } from \"../types\";\nimport Storage, { Key } from \"../Storage\";\nexport default class weightsStore extends Storage {\n static async getWeight(verboseName: string) {\n const weight = await this.get(Key.WEIGHTS, true, verboseName) as weightsType;\n if (weight != null) {\n return weight;\n }\n return { [verboseName]: 1 };\n }",
"score": 13.950645933646234
},
{
"filename": "src/Storage.ts",
"retrieved_chunk": "import AsyncStorage from '@react-native-async-storage/async-storage';\nimport { serverFeatureType, accFeatureType, weightsType } from \"./types\";\nimport { mastodon } from \"masto\";\nexport enum Key {\n TOP_FAVS = 'favs',\n TOP_REBLOGS = 'reblogs',\n TOP_INTERACTS = 'interacts',\n CORE_SERVER = 'coreServer',\n USER = 'algouser',\n WEIGHTS = 'weights',",
"score": 12.83974169336597
},
{
"filename": "src/feeds/topPostsFeed.ts",
"retrieved_chunk": " results = await Promise.all(servers.map(async (server: string): Promise<mastodon.v1.Status[]> => {\n if (server === \"undefined\" || typeof server == \"undefined\" || server === \"\") return [];\n let res;\n try {\n res = await fetch(\"https://\" + server + \"/api/v1/trends/statuses\")\n }\n catch (e) {\n return [];\n }\n if (!res.ok) {",
"score": 9.623676826294348
}
] | typescript | async setWeights(weights: weightsType): Promise<StatusType[]> { |
import type { AddTextOptions, FullSprigAPI, GameState, SpriteType } from '../api.js'
import { palette } from './palette.js'
export * from './font.js'
export * from './palette.js'
export * from './text.js'
export * from './tune.js'
// Tagged template literal factory go brrr
const _makeTag = <T>(cb: (string: string) => T) => {
return (strings: TemplateStringsArray, ...interps: string[]) => {
if (typeof strings === 'string') {
throw new Error('Tagged template literal must be used like name`text`, instead of name(`text`)')
}
const string = strings.reduce((p, c, i) => p + c + (interps[i] ?? ''), '')
return cb(string)
}
}
export type BaseEngineAPI = Pick<
FullSprigAPI,
| 'setMap'
| 'addText'
| 'clearText'
| 'addSprite'
| 'getGrid'
| 'getTile'
| 'tilesWith'
| 'clearTile'
| 'setSolids'
| 'setPushables'
| 'setBackground'
| 'map'
| 'bitmap'
| 'color'
| 'tune'
| 'getFirst'
| 'getAll'
| 'width'
| 'height'
>
| export function baseEngine(): { api: BaseEngineAPI, state: GameState } { |
const gameState: GameState = {
legend: [],
texts: [],
dimensions: {
width: 0,
height: 0,
},
sprites: [],
solids: [],
pushable: {},
background: null
}
class Sprite implements SpriteType {
_type: string
_x: number
_y: number
dx: number
dy: number
constructor(type: string, x: number, y: number) {
this._type = type
this._x = x
this._y = y
this.dx = 0
this.dy = 0
}
set type(newType) {
const legendDict = Object.fromEntries(gameState.legend)
if (!(newType in legendDict)) throw new Error(`"${newType}" isn\'t in the legend.`)
this.remove()
addSprite(this._x, this._y, newType)
}
get type() {
return this._type
}
set x(newX) {
const dx = newX - this.x
if (_canMoveToPush(this, dx, 0)) this.dx = dx
}
get x() {
return this._x
}
set y(newY) {
const dy = newY - this.y
if (_canMoveToPush(this, 0, dy)) this.dy = dy
}
get y() {
return this._y
}
remove() {
gameState.sprites = gameState.sprites.filter(s => s !== this)
return this
}
}
const _canMoveToPush = (sprite: Sprite, dx: number, dy: number): boolean => {
const { x, y, type } = sprite
const { width, height } = gameState.dimensions
const i = (x+dx)+(y+dy)*width
const inBounds = (x+dx < width && x+dx >= 0 && y+dy < height && y+dy >= 0)
if (!inBounds) return false
const grid = getGrid()
const notSolid = !gameState.solids.includes(type)
const noMovement = dx === 0 && dy === 0
const movingToEmpty = i < grid.length && grid[i]!.length === 0
if (notSolid || noMovement || movingToEmpty) {
sprite._x += dx
sprite._y += dy
return true
}
let canMove = true
const { pushable } = gameState
grid[i]!.forEach(sprite => {
const isSolid = gameState.solids.includes(sprite.type)
const isPushable = (type in pushable) && pushable[type]!.includes(sprite.type)
if (isSolid && !isPushable)
canMove = false
if (isSolid && isPushable) {
canMove = canMove && _canMoveToPush(sprite as Sprite, dx, dy)
}
})
if (canMove) {
sprite._x += dx
sprite._y += dy
}
return canMove
}
const getGrid = (): SpriteType[][] => {
const { width, height } = gameState.dimensions
const grid: SpriteType[][] = new Array(width*height).fill(0).map(_ => [])
gameState.sprites.forEach(s => {
const i = s.x+s.y*width
grid[i]!.push(s)
})
const legendIndex = (t: SpriteType) => gameState.legend.findIndex(l => l[0] == t.type)
for (const tile of grid) tile.sort((a, b) => legendIndex(a) - legendIndex(b))
return grid
}
const _checkBounds = (x: number, y: number): void => {
const { width, height } = gameState.dimensions
if (x >= width || x < 0 || y < 0 || y >= height) throw new Error(`Sprite out of bounds.`)
}
const _checkLegend = (type: string): void => {
if (!(type in Object.fromEntries(gameState.legend)))
throw new Error(`Unknown sprite type: ${type}`)
}
const addSprite = (x: number, y: number, type: string): void => {
if (type === '.') return
_checkBounds(x, y)
_checkLegend(type)
const s = new Sprite(type, x, y)
gameState.sprites.push(s)
}
const _allEqual = <T>(arr: T[]): boolean => arr.every(val => val === arr[0])
const setMap = (string: string): void => {
if (!string) throw new Error('Tried to set empty map.')
if (string.constructor == Object) throw new Error('setMap() takes a string, not a dict.') // https://stackoverflow.com/a/51285298
if (Array.isArray(string)) throw new Error('It looks like you passed an array into setMap(). Did you mean to use something like setMap(levels[level]) instead of setMap(levels)?')
const rows = string.trim().split("\n").map(x => x.trim())
const rowLengths = rows.map(x => x.length)
const isRect = _allEqual(rowLengths)
if (!isRect) throw new Error('Level must be rectangular.')
const w = rows[0]?.length ?? 0
const h = rows.length
gameState.dimensions.width = w
gameState.dimensions.height = h
gameState.sprites = []
const nonSpace = string.split("").filter(x => x !== " " && x !== "\n") // \S regex was too slow
for (let i = 0; i < w*h; i++) {
const type = nonSpace[i]!
if (type === '.') continue
const x = i%w
const y = Math.floor(i/w)
addSprite(x, y, type)
}
}
const clearTile = (x: number, y: number): void => {
gameState.sprites = gameState.sprites.filter(s => s.x !== x || s.y !== y)
}
const addText = (str: string, opts: AddTextOptions = {}): void => {
const CHARS_MAX_X = 21
const padLeft = Math.floor((CHARS_MAX_X - str.length)/2)
if (Array.isArray(opts.color)) throw new Error('addText no longer takes an RGBA color. Please use a Sprig color instead with \"{ color: color`` }\"')
const [, rgba ] = palette.find(([key]) => key === opts.color) ?? palette.find(([key]) => key === 'L')!
gameState.texts.push({
x: opts.x ?? padLeft,
y: opts.y ?? 0,
color: rgba,
content: str
})
}
const clearText = (): void => { gameState.texts = [] }
const getTile = (x: number, y: number): SpriteType[] => {
if (y < 0) return []
if (x < 0) return []
if (y >= gameState.dimensions.height) return []
if (x >= gameState.dimensions.width) return []
return getGrid()[gameState.dimensions.width*y+x] ?? []
}
const _hasDuplicates = <T>(array: T[]): boolean => (new Set(array)).size !== array.length
const tilesWith = (...matchingTypes: string[]): SpriteType[][] => {
const { width, height } = gameState.dimensions
const tiles: SpriteType[][] = []
const grid = getGrid()
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
const tile = grid[width*y+x] || []
const matchIndices = matchingTypes.map(type => {
return tile.map(s => s.type).indexOf(type)
})
if (!_hasDuplicates(matchIndices) && !matchIndices.includes(-1)) tiles.push(tile)
}
}
return tiles
}
const setSolids = (arr: string[]): void => {
if (!Array.isArray(arr)) throw new Error('The sprites passed into setSolids() need to be an array.')
gameState.solids = arr
}
const setPushables = (map: Record<string, string[]>): void => {
for (const key in map) {
if(key.length != 1) {
throw new Error('Your sprite name must be wrapped in [] brackets here.');
}
_checkLegend(key)
}
gameState.pushable = map
}
const api: BaseEngineAPI = {
setMap,
addText,
clearText,
addSprite,
getGrid,
getTile,
tilesWith,
clearTile,
setSolids,
setPushables,
setBackground: (type: string) => { gameState.background = type },
map: _makeTag(text => text),
bitmap: _makeTag(text => text),
color: _makeTag(text => text),
tune: _makeTag(text => text),
getFirst: (type: string): SpriteType | undefined => gameState.sprites.find(t => t.type === type), // **
getAll: (type: string): SpriteType[] => type ? gameState.sprites.filter(t => t.type === type) : gameState.sprites, // **
width: () => gameState.dimensions.width,
height: () => gameState.dimensions.height
}
return { api, state: gameState }
}
| src/base/index.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/image-data/index.ts",
"retrieved_chunk": "import type { FullSprigAPI, GameState, InputKey } from '../api.js'\nimport { type BaseEngineAPI, baseEngine } from '../base/index.js'\nimport { bitmapTextToImageData } from './bitmap.js'\nexport * from './bitmap.js'\nexport type ImageDataEngineAPI = BaseEngineAPI & Pick<\n\tFullSprigAPI,\n\t| 'onInput'\n\t| 'afterInput'\n\t| 'setLegend'\n\t| 'setBackground'",
"score": 21.224340267653698
},
{
"filename": "src/web/index.ts",
"retrieved_chunk": "import { type InputKey, type PlayTuneRes, VALID_INPUTS, type FullSprigAPI, type GameState } from '../api.js'\nimport { type BaseEngineAPI, baseEngine, textToTune } from '../base/index.js'\nimport { bitmapTextToImageData } from '../image-data/index.js'\nimport { getTextImg } from './text.js'\nimport { playTune } from './tune.js'\nimport { makeCanvas } from './util.js'\nexport * from './text.js'\nexport * from './tune.js'\nexport type WebEngineAPI = BaseEngineAPI & Pick<\n\tFullSprigAPI,",
"score": 16.3252775805306
},
{
"filename": "src/web/index.ts",
"retrieved_chunk": "\t| 'setLegend'\n\t| 'onInput'\n\t| 'afterInput'\n\t| 'playTune'\n> & {\n\tgetState(): GameState // For weird backwards-compatibility reasons, not part of API\n}\nexport function webEngine(canvas: HTMLCanvasElement): {\n\tapi: WebEngineAPI,\n\tstate: GameState,",
"score": 14.00094613859607
},
{
"filename": "src/api.ts",
"retrieved_chunk": "\tgetGrid(): SpriteType[][]\n\tgetTile(x: number, y: number): SpriteType[]\n\ttilesWith(...matchingTypes: string[]): SpriteType[][]\n\tclearTile(x: number, y: number): void\n\tsetSolids(types: string[]): void\n\tsetPushables(map: Record<string, string[]>): void\n\tsetBackground(type: string): void\n\tgetFirst(type: string): SpriteType | undefined\n\tgetAll(type: string): SpriteType[]\n\twidth(): number",
"score": 13.171015497044658
},
{
"filename": "src/web/util.ts",
"retrieved_chunk": "export function makeCanvas(width: number, height: number): HTMLCanvasElement {\n\tconst canvas = document.createElement('canvas')\n\tcanvas.width = width\n\tcanvas.height = height\n\treturn canvas\n}",
"score": 12.36759210845839
}
] | typescript | export function baseEngine(): { api: BaseEngineAPI, state: GameState } { |
import { type InputKey, type PlayTuneRes, VALID_INPUTS, type FullSprigAPI, type GameState } from '../api.js'
import { type BaseEngineAPI, baseEngine, textToTune } from '../base/index.js'
import { bitmapTextToImageData } from '../image-data/index.js'
import { getTextImg } from './text.js'
import { playTune } from './tune.js'
import { makeCanvas } from './util.js'
export * from './text.js'
export * from './tune.js'
export type WebEngineAPI = BaseEngineAPI & Pick<
FullSprigAPI,
| 'setLegend'
| 'onInput'
| 'afterInput'
| 'playTune'
> & {
getState(): GameState // For weird backwards-compatibility reasons, not part of API
}
export function webEngine(canvas: HTMLCanvasElement): {
api: WebEngineAPI,
state: GameState,
cleanup(): void
} {
const { api, state } = baseEngine()
const ctx = canvas.getContext('2d')!
const offscreenCanvas = makeCanvas(1, 1)
const offscreenCtx = offscreenCanvas.getContext('2d')!
const _bitmaps: Record<string, CanvasImageSource> = {}
let _zOrder: string[] = []
ctx.imageSmoothingEnabled = false
const _gameloop = (): void => {
const { width, height } = state.dimensions
if (width === 0 || height === 0) return
ctx.clearRect(0, 0, canvas.width, canvas.height)
offscreenCanvas.width = width*16
offscreenCanvas.height = height*16
offscreenCtx.fillStyle = 'white'
offscreenCtx.fillRect(0, 0, width*16, height*16)
const grid = api.getGrid()
for (let i = 0; i < width * height; i++) {
const x = i % width
const y = Math.floor(i/width)
const sprites = grid[i]!
if (state.background) {
const imgData = _bitmaps[state.background]!
offscreenCtx.drawImage(imgData, x*16, y*16)
}
sprites
.sort((a, b) => _zOrder.indexOf(b.type) - _zOrder.indexOf(a.type))
| .forEach((sprite) => { |
const imgData = _bitmaps[sprite.type]!
offscreenCtx.drawImage(imgData, x*16, y*16)
})
}
const scale = Math.min(canvas.width/(width*16), canvas.height/(height*16))
const actualWidth = offscreenCanvas.width*scale
const actualHeight = offscreenCanvas.height*scale
ctx.drawImage(
offscreenCanvas,
(canvas.width-actualWidth)/2,
(canvas.height-actualHeight)/2,
actualWidth,
actualHeight
)
const textCanvas = getTextImg(state.texts)
ctx.drawImage(
textCanvas,
0,
0,
canvas.width,
canvas.height
)
animationId = window.requestAnimationFrame(_gameloop)
}
let animationId = window.requestAnimationFrame(_gameloop)
const setLegend = (...bitmaps: [string, string][]): void => {
if (bitmaps.length == 0) throw new Error('There needs to be at least one sprite in the legend.')
if (!Array.isArray(bitmaps[0])) throw new Error('The sprites passed into setLegend each need to be in square brackets, like setLegend([player, bitmap`...`]).')
bitmaps.forEach(([ key ]) => {
if (key === '.') throw new Error(`Can't reassign "." bitmap`)
if (key.length !== 1) throw new Error(`Bitmaps must have one character names`)
})
state.legend = bitmaps
_zOrder = bitmaps.map(x => x[0])
for (let i = 0; i < bitmaps.length; i++) {
const [ key, value ] = bitmaps[i]!
const imgData = bitmapTextToImageData(value)
const littleCanvas = makeCanvas(16, 16)
littleCanvas.getContext('2d')!.putImageData(imgData, 0, 0)
_bitmaps[key] = littleCanvas
}
}
let tileInputs: Record<InputKey, (() => void)[]> = {
w: [],
s: [],
a: [],
d: [],
i: [],
j: [],
k: [],
l: []
}
const afterInputs: (() => void)[] = []
const keydown = (e: KeyboardEvent) => {
const key = e.key
if (!VALID_INPUTS.includes(key as any)) return
for (const validKey of VALID_INPUTS)
if (key === validKey) tileInputs[key].forEach(fn => fn())
afterInputs.forEach(f => f())
state.sprites.forEach((s: any) => {
s.dx = 0
s.dy = 0
})
e.preventDefault()
}
canvas.addEventListener('keydown', keydown)
const onInput = (key: InputKey, fn: () => void): void => {
if (!VALID_INPUTS.includes(key))
throw new Error(`Unknown input key, "${key}": expected one of ${VALID_INPUTS.join(', ')}`)
tileInputs[key].push(fn)
}
const afterInput = (fn: () => void): void => { afterInputs.push(fn) }
const tunes: PlayTuneRes[] = []
return {
api: {
...api,
setLegend,
onInput,
afterInput,
getState: () => state,
playTune: (text: string, n: number) => {
const tune = textToTune(text)
const playTuneRes = playTune(tune, n)
tunes.push(playTuneRes)
return playTuneRes
}
},
state,
cleanup: () => {
ctx.clearRect(0, 0, canvas.width, canvas.height)
window.cancelAnimationFrame(animationId)
canvas.removeEventListener('keydown', keydown)
tunes.forEach(tune => tune.end())
}
}
}
| src/web/index.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/base/index.ts",
"retrieved_chunk": "\t\t})\n\t\tconst legendIndex = (t: SpriteType) => gameState.legend.findIndex(l => l[0] == t.type)\n\t\tfor (const tile of grid) tile.sort((a, b) => legendIndex(a) - legendIndex(b))\n\t\treturn grid\n\t}\n\tconst _checkBounds = (x: number, y: number): void => {\n\t\tconst { width, height } = gameState.dimensions\n\t\tif (x >= width || x < 0 || y < 0 || y >= height) throw new Error(`Sprite out of bounds.`)\n\t}\n\tconst _checkLegend = (type: string): void => {",
"score": 37.85714438264844
},
{
"filename": "src/base/index.ts",
"retrieved_chunk": "\t\tconst h = rows.length\n\t\tgameState.dimensions.width = w\n\t\tgameState.dimensions.height = h\n\t\tgameState.sprites = []\n\t\tconst nonSpace = string.split(\"\").filter(x => x !== \" \" && x !== \"\\n\") // \\S regex was too slow\n\t\tfor (let i = 0; i < w*h; i++) {\n\t\t\tconst type = nonSpace[i]!\n\t\t\tif (type === '.') continue\n\t\t\tconst x = i%w \n\t\t\tconst y = Math.floor(i/w)",
"score": 36.61720779333061
},
{
"filename": "src/base/index.ts",
"retrieved_chunk": "\t\t\tsprite._y += dy\n\t\t}\n\t\treturn canMove\n\t}\n\tconst getGrid = (): SpriteType[][] => {\n\t\tconst { width, height } = gameState.dimensions\n\t\tconst grid: SpriteType[][] = new Array(width*height).fill(0).map(_ => [])\n\t\tgameState.sprites.forEach(s => {\n\t\t\tconst i = s.x+s.y*width\n\t\t\tgrid[i]!.push(s)",
"score": 35.039092639539106
},
{
"filename": "src/image-data/bitmap.ts",
"retrieved_chunk": " const colors = Object.fromEntries(palette)\n const nonSpace = text.split('').filter(x => x !== ' ' && x !== '\\n') // \\S regex led to massive perf problems\n for (let i = 0; i < width*height; i++) {\n const type = nonSpace[i] || \".\"\n if (!(type in colors)) {\n const err = `in sprite string: no known color for char \"${type}\"`\n console.error(err + '\\n' + text)\n throw new Error(err + ' (invalid sprite in console)')\n }\n const [ r, g, b, a ] = colors[type] ?? colors['.']!",
"score": 33.15632265199059
},
{
"filename": "src/base/index.ts",
"retrieved_chunk": "\t\tconst grid = getGrid()\n\t\tfor (let x = 0; x < width; x++) {\n\t\t\tfor (let y = 0; y < height; y++) {\n\t\t\t\tconst tile = grid[width*y+x] || []\n\t\t\t\tconst matchIndices = matchingTypes.map(type => {\n\t\t\t\t\treturn tile.map(s => s.type).indexOf(type)\n\t\t\t\t})\n\t\t\t\tif (!_hasDuplicates(matchIndices) && !matchIndices.includes(-1)) tiles.push(tile)\n\t\t\t}\n\t\t}",
"score": 30.17096849165999
}
] | typescript | .forEach((sprite) => { |
import type { AddTextOptions, FullSprigAPI, GameState, SpriteType } from '../api.js'
import { palette } from './palette.js'
export * from './font.js'
export * from './palette.js'
export * from './text.js'
export * from './tune.js'
// Tagged template literal factory go brrr
const _makeTag = <T>(cb: (string: string) => T) => {
return (strings: TemplateStringsArray, ...interps: string[]) => {
if (typeof strings === 'string') {
throw new Error('Tagged template literal must be used like name`text`, instead of name(`text`)')
}
const string = strings.reduce((p, c, i) => p + c + (interps[i] ?? ''), '')
return cb(string)
}
}
export type BaseEngineAPI = Pick<
FullSprigAPI,
| 'setMap'
| 'addText'
| 'clearText'
| 'addSprite'
| 'getGrid'
| 'getTile'
| 'tilesWith'
| 'clearTile'
| 'setSolids'
| 'setPushables'
| 'setBackground'
| 'map'
| 'bitmap'
| 'color'
| 'tune'
| 'getFirst'
| 'getAll'
| 'width'
| 'height'
>
export function baseEngine(): { api: BaseEngineAPI, state: GameState } {
const gameState: GameState = {
legend: [],
texts: [],
dimensions: {
width: 0,
height: 0,
},
sprites: [],
solids: [],
pushable: {},
background: null
}
class Sprite implements SpriteType {
_type: string
_x: number
_y: number
dx: number
dy: number
constructor(type: string, x: number, y: number) {
this._type = type
this._x = x
this._y = y
this.dx = 0
this.dy = 0
}
set type(newType) {
const legendDict = Object.fromEntries(gameState.legend)
if (!(newType in legendDict)) throw new Error(`"${newType}" isn\'t in the legend.`)
this.remove()
addSprite(this._x, this._y, newType)
}
get type() {
return this._type
}
set x(newX) {
const dx = newX - this.x
if (_canMoveToPush(this, dx, 0)) this.dx = dx
}
get x() {
return this._x
}
set y(newY) {
const dy = newY - this.y
if (_canMoveToPush(this, 0, dy)) this.dy = dy
}
get y() {
return this._y
}
remove() {
gameState.sprites = gameState.sprites.filter(s => s !== this)
return this
}
}
const _canMoveToPush = (sprite: Sprite, dx: number, dy: number): boolean => {
const { x, y, type } = sprite
const { width, height } = gameState.dimensions
const i = (x+dx)+(y+dy)*width
const inBounds = (x+dx < width && x+dx >= 0 && y+dy < height && y+dy >= 0)
if (!inBounds) return false
const grid = getGrid()
const notSolid = !gameState.solids.includes(type)
const noMovement = dx === 0 && dy === 0
const movingToEmpty = i < grid.length && grid[i]!.length === 0
if (notSolid || noMovement || movingToEmpty) {
sprite._x += dx
sprite._y += dy
return true
}
let canMove = true
const { pushable } = gameState
grid[i]!.forEach(sprite => {
const isSolid = gameState.solids.includes(sprite.type)
const isPushable = (type in pushable) && pushable[type]!.includes(sprite.type)
if (isSolid && !isPushable)
canMove = false
if (isSolid && isPushable) {
canMove = canMove && _canMoveToPush(sprite as Sprite, dx, dy)
}
})
if (canMove) {
sprite._x += dx
sprite._y += dy
}
return canMove
}
const getGrid = (): SpriteType[][] => {
const { width, height } = gameState.dimensions
const grid: SpriteType[][] = new Array(width*height).fill(0).map(_ => [])
gameState.sprites.forEach(s => {
const i = s.x+s.y*width
grid[i]!.push(s)
})
const legendIndex = (t: SpriteType) => gameState.legend.findIndex(l => l[0] == t.type)
for (const tile of grid) tile.sort((a, b) => legendIndex(a) - legendIndex(b))
return grid
}
const _checkBounds = (x: number, y: number): void => {
const { width, height } = gameState.dimensions
if (x >= width || x < 0 || y < 0 || y >= height) throw new Error(`Sprite out of bounds.`)
}
const _checkLegend = (type: string): void => {
if (!(type in Object.fromEntries(gameState.legend)))
throw new Error(`Unknown sprite type: ${type}`)
}
const addSprite = (x: number, y: number, type: string): void => {
if (type === '.') return
_checkBounds(x, y)
_checkLegend(type)
const s = new Sprite(type, x, y)
gameState.sprites.push(s)
}
const _allEqual = <T>(arr: T[]): boolean => arr.every(val => val === arr[0])
const setMap = (string: string): void => {
if (!string) throw new Error('Tried to set empty map.')
if (string.constructor == Object) throw new Error('setMap() takes a string, not a dict.') // https://stackoverflow.com/a/51285298
if (Array.isArray(string)) throw new Error('It looks like you passed an array into setMap(). Did you mean to use something like setMap(levels[level]) instead of setMap(levels)?')
const rows = string.trim().split("\n").map(x => x.trim())
const rowLengths = rows.map(x => x.length)
const isRect = _allEqual(rowLengths)
if (!isRect) throw new Error('Level must be rectangular.')
const w = rows[0]?.length ?? 0
const h = rows.length
gameState.dimensions.width = w
gameState.dimensions.height = h
gameState.sprites = []
const nonSpace = string.split("").filter(x => x !== " " && x !== "\n") // \S regex was too slow
for (let i = 0; i < w*h; i++) {
const type = nonSpace[i]!
if (type === '.') continue
const x = i%w
const y = Math.floor(i/w)
addSprite(x, y, type)
}
}
const clearTile = (x: number, y: number): void => {
gameState.sprites = gameState.sprites.filter(s => s.x !== x || s.y !== y)
}
const | addText = (str: string, opts: AddTextOptions = {}): void => { |
const CHARS_MAX_X = 21
const padLeft = Math.floor((CHARS_MAX_X - str.length)/2)
if (Array.isArray(opts.color)) throw new Error('addText no longer takes an RGBA color. Please use a Sprig color instead with \"{ color: color`` }\"')
const [, rgba ] = palette.find(([key]) => key === opts.color) ?? palette.find(([key]) => key === 'L')!
gameState.texts.push({
x: opts.x ?? padLeft,
y: opts.y ?? 0,
color: rgba,
content: str
})
}
const clearText = (): void => { gameState.texts = [] }
const getTile = (x: number, y: number): SpriteType[] => {
if (y < 0) return []
if (x < 0) return []
if (y >= gameState.dimensions.height) return []
if (x >= gameState.dimensions.width) return []
return getGrid()[gameState.dimensions.width*y+x] ?? []
}
const _hasDuplicates = <T>(array: T[]): boolean => (new Set(array)).size !== array.length
const tilesWith = (...matchingTypes: string[]): SpriteType[][] => {
const { width, height } = gameState.dimensions
const tiles: SpriteType[][] = []
const grid = getGrid()
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
const tile = grid[width*y+x] || []
const matchIndices = matchingTypes.map(type => {
return tile.map(s => s.type).indexOf(type)
})
if (!_hasDuplicates(matchIndices) && !matchIndices.includes(-1)) tiles.push(tile)
}
}
return tiles
}
const setSolids = (arr: string[]): void => {
if (!Array.isArray(arr)) throw new Error('The sprites passed into setSolids() need to be an array.')
gameState.solids = arr
}
const setPushables = (map: Record<string, string[]>): void => {
for (const key in map) {
if(key.length != 1) {
throw new Error('Your sprite name must be wrapped in [] brackets here.');
}
_checkLegend(key)
}
gameState.pushable = map
}
const api: BaseEngineAPI = {
setMap,
addText,
clearText,
addSprite,
getGrid,
getTile,
tilesWith,
clearTile,
setSolids,
setPushables,
setBackground: (type: string) => { gameState.background = type },
map: _makeTag(text => text),
bitmap: _makeTag(text => text),
color: _makeTag(text => text),
tune: _makeTag(text => text),
getFirst: (type: string): SpriteType | undefined => gameState.sprites.find(t => t.type === type), // **
getAll: (type: string): SpriteType[] => type ? gameState.sprites.filter(t => t.type === type) : gameState.sprites, // **
width: () => gameState.dimensions.width,
height: () => gameState.dimensions.height
}
return { api, state: gameState }
}
| src/base/index.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/api.ts",
"retrieved_chunk": "export const VALID_INPUTS = [ 'w', 's', 'a', 'd', 'i', 'j', 'k', 'l' ] as const\nexport type InputKey = typeof VALID_INPUTS[number]\nexport interface AddTextOptions {\n\tx?: number\n\ty?: number\n\tcolor?: string\n}\nexport declare class SpriteType {\n\ttype: string\n\tx: number",
"score": 56.71415685080424
},
{
"filename": "src/api.ts",
"retrieved_chunk": "export type Tune = [number, ...(InstrumentType | number | string)[]][]\nexport interface FullSprigAPI {\n\tmap(template: TemplateStringsArray, ...params: string[]): string\n\tbitmap(template: TemplateStringsArray, ...params: string[]): string\n\tcolor(template: TemplateStringsArray, ...params: string[]): string\n\ttune(template: TemplateStringsArray, ...params: string[]): string\n\tsetMap(string: string): void\n\taddText(str: string, opts?: AddTextOptions): void\n\tclearText(): void\n\taddSprite(x: number, y: number, type: string): void",
"score": 51.578778246546825
},
{
"filename": "src/web/index.ts",
"retrieved_chunk": "\t\t\tconst y = Math.floor(i/width)\n\t\t\tconst sprites = grid[i]!\n\t\t\tif (state.background) {\n\t\t\t\tconst imgData = _bitmaps[state.background]!\n\t\t\t\toffscreenCtx.drawImage(imgData, x*16, y*16)\n\t\t\t}\n\t\t\tsprites\n\t\t\t\t.sort((a, b) => _zOrder.indexOf(b.type) - _zOrder.indexOf(a.type))\n\t\t\t\t.forEach((sprite) => {\n\t\t\t\t\tconst imgData = _bitmaps[sprite.type]!",
"score": 48.300331101372386
},
{
"filename": "src/api.ts",
"retrieved_chunk": "\tgetGrid(): SpriteType[][]\n\tgetTile(x: number, y: number): SpriteType[]\n\ttilesWith(...matchingTypes: string[]): SpriteType[][]\n\tclearTile(x: number, y: number): void\n\tsetSolids(types: string[]): void\n\tsetPushables(map: Record<string, string[]>): void\n\tsetBackground(type: string): void\n\tgetFirst(type: string): SpriteType | undefined\n\tgetAll(type: string): SpriteType[]\n\twidth(): number",
"score": 46.715876557774905
},
{
"filename": "src/api.ts",
"retrieved_chunk": "\ty: number\n\treadonly dx: number\n\treadonly dy: number\n\tremove(): void\n}\nexport type Rgba = [number, number, number, number]\nexport interface TextElement {\n\tx: number\n\ty: number\n\tcolor: Rgba",
"score": 38.19828708208471
}
] | typescript | addText = (str: string, opts: AddTextOptions = {}): void => { |
import { type InstrumentType, type PlayTuneRes, type Tune, instruments, tones } from '../api.js'
export function playFrequency(frequency: number, duration: number, instrument: InstrumentType, ctx: AudioContext, dest: AudioNode) {
const osc = ctx.createOscillator()
const rampGain = ctx.createGain()
osc.connect(rampGain)
rampGain.connect(dest)
osc.frequency.value = frequency
osc.type = instrument ?? 'sine'
osc.start()
const endTime = ctx.currentTime + duration*2/1000
osc.stop(endTime)
rampGain.gain.setValueAtTime(0, ctx.currentTime)
rampGain.gain.linearRampToValueAtTime(.2, ctx.currentTime + duration/5/1000)
rampGain.gain.exponentialRampToValueAtTime(0.00001, ctx.currentTime + duration/1000)
rampGain.gain.linearRampToValueAtTime(0, ctx.currentTime + duration*2/1000) // does this ramp from the last ramp
osc.onended = () => {
osc.disconnect()
rampGain.disconnect()
}
}
const sleep = async (duration: number) => new Promise(resolve => setTimeout(resolve, duration))
export async function playTuneHelper(tune: Tune, number: number, playingRef: { playing: boolean }, ctx: AudioContext, dest: AudioNode) {
for (let i = 0; i < tune.length*number; i++) {
const index = i%tune.length
if (!playingRef.playing) break
const noteSet = tune[index]!
const sleepTime = noteSet[0]
for (let j = 1; j < noteSet.length; j += 3) {
const instrument = noteSet[j] as InstrumentType
const note = noteSet[j+1]!
const duration = noteSet[j+2] as number
const frequency = typeof note === 'string'
? tones[note.toUpperCase()]
: 2**((note-69)/12)*440
| if (instruments.includes(instrument) && frequency !== undefined) playFrequency(frequency, duration, instrument, ctx, dest)
} |
await sleep(sleepTime)
}
}
let audioCtx: AudioContext | null = null
export function playTune(tune: Tune, number = 1): PlayTuneRes {
const playingRef = { playing: true }
if (audioCtx === null) audioCtx = new AudioContext()
playTuneHelper(tune, number, playingRef, audioCtx, audioCtx.destination)
return {
end() { playingRef.playing = false },
isPlaying() { return playingRef.playing }
}
} | src/web/tune.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/base/tune.ts",
"retrieved_chunk": "\t\t}\n\t\treturn groups\n\t}\n\tconst notesToString = ([duration, ...notes]: Tune[number]) => (\n\t\tnotes.length === 0 \n\t\t\t? duration \n\t\t\t: `${duration}: ${groupNotes(notes).map(notesToStringHelper).join(' + ')}`\n\t)\n\tconst notesToStringHelper = ([instrument, duration, note]: (number | string)[]) => (\n\t\t`${duration}${reverseInstrumentKey[instrument as InstrumentType]}${note}`",
"score": 83.92762923912059
},
{
"filename": "src/api.ts",
"retrieved_chunk": "export const VALID_INPUTS = [ 'w', 's', 'a', 'd', 'i', 'j', 'k', 'l' ] as const\nexport type InputKey = typeof VALID_INPUTS[number]\nexport interface AddTextOptions {\n\tx?: number\n\ty?: number\n\tcolor?: string\n}\nexport declare class SpriteType {\n\ttype: string\n\tx: number",
"score": 44.68401045617406
},
{
"filename": "src/image-data/index.ts",
"retrieved_chunk": "\t\td: [],\n\t\ti: [],\n\t\tj: [],\n\t\tk: [],\n\t\tl: []\n\t}\n\tconst afterInputs: (() => void)[] = []\n\tconst cleanup = () => {\n\t\ttimeouts.forEach(clearTimeout)\n\t\tintervals.forEach(clearInterval)",
"score": 38.37069195944302
},
{
"filename": "src/web/index.ts",
"retrieved_chunk": "\t}\n\tlet tileInputs: Record<InputKey, (() => void)[]> = {\n\t\tw: [],\n\t\ts: [],\n\t\ta: [],\n\t\td: [],\n\t\ti: [],\n\t\tj: [],\n\t\tk: [],\n\t\tl: []",
"score": 33.6505861107366
},
{
"filename": "src/api.ts",
"retrieved_chunk": "export type InstrumentType = typeof instruments[number]\nexport const instrumentKey: Record<string, InstrumentType> = {\n\t'~': 'sine',\n\t'-': 'square',\n\t'^': 'triangle',\n\t'/': 'sawtooth'\n}\nexport const reverseInstrumentKey = Object.fromEntries(\n\tObject.entries(instrumentKey).map(([ k, v ]) => [ v, k ])\n) as Record<InstrumentType, string>",
"score": 30.81821576036705
}
] | typescript | if (instruments.includes(instrument) && frequency !== undefined) playFrequency(frequency, duration, instrument, ctx, dest)
} |
/*
song form
[
[duration, instrument, pitch, duration, ...],
]
Syntax:
500: 64.4~500 + c5~1000
[500, 'sine', 64.4, 500, 'sine', 'c5', 1000]
Comma between each tune element. Whitespace ignored.
*/
import { type Tune, instrumentKey, InstrumentType, reverseInstrumentKey } from '../api.js'
export const textToTune = (text: string): Tune => {
const elements = text.replace(/\s/g, '').split(',')
const tune = []
for (const element of elements) {
if (!element) continue
const [durationRaw, notesRaw] = element.split(':')
const duration = Math.round(parseInt(durationRaw ?? '0', 10))
const notes = (notesRaw || '').split('+').map((noteRaw) => {
if (!noteRaw) return []
const [, pitchRaw, instrumentRaw, durationRaw] = noteRaw.match(/^(.+)([~\-^\/])(.+)$/)!
return [
instrumentKey[instrumentRaw!] ?? 'sine',
isNaN(parseInt(pitchRaw ?? '', 10)) ? pitchRaw! : parseInt(pitchRaw!, 10),
parseInt(durationRaw ?? '0', 10)
]
})
tune.push([duration, ...notes].flat())
}
return tune as Tune
}
export const tuneToText = (tune: Tune): string => {
const groupNotes = (notes: (number | string)[]) => {
const groups = []
for (let i = 0; i < notes.length; i++) {
if (i % 3 === 0) {
groups.push([notes[i]!])
} else {
groups[groups.length-1]!.push(notes[i]!)
}
}
return groups
}
const notesToString = ([duration, ...notes]: Tune[number]) => (
notes.length === 0
? duration
: `${duration}: ${groupNotes(notes).map(notesToStringHelper).join(' + ')}`
)
const notesToStringHelper = ([instrument, duration, note]: (number | string)[]) => (
`${duration | }${reverseInstrumentKey[instrument as InstrumentType]}${note}`
)
return tune.map(notesToString).join(',\n')
} | src/base/tune.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/web/tune.ts",
"retrieved_chunk": "\t\t\tconst duration = noteSet[j+2] as number\n\t\t\tconst frequency = typeof note === 'string' \n\t\t\t\t? tones[note.toUpperCase()]\n\t\t\t\t: 2**((note-69)/12)*440\n\t\t\tif (instruments.includes(instrument) && frequency !== undefined) playFrequency(frequency, duration, instrument, ctx, dest)\n\t\t}\n\t\tawait sleep(sleepTime)\n\t}\n}\nlet audioCtx: AudioContext | null = null",
"score": 49.96241468711131
},
{
"filename": "src/web/tune.ts",
"retrieved_chunk": "const sleep = async (duration: number) => new Promise(resolve => setTimeout(resolve, duration))\nexport async function playTuneHelper(tune: Tune, number: number, playingRef: { playing: boolean }, ctx: AudioContext, dest: AudioNode) {\n\tfor (let i = 0; i < tune.length*number; i++) {\n\t\tconst index = i%tune.length\n\t\tif (!playingRef.playing) break\n\t\tconst noteSet = tune[index]!\n\t\tconst sleepTime = noteSet[0]\n\t\tfor (let j = 1; j < noteSet.length; j += 3) {\n\t\t\tconst instrument = noteSet[j] as InstrumentType\n\t\t\tconst note = noteSet[j+1]!",
"score": 45.06148962360298
},
{
"filename": "src/web/tune.ts",
"retrieved_chunk": "import { type InstrumentType, type PlayTuneRes, type Tune, instruments, tones } from '../api.js'\nexport function playFrequency(frequency: number, duration: number, instrument: InstrumentType, ctx: AudioContext, dest: AudioNode) {\n\tconst osc = ctx.createOscillator()\n\tconst rampGain = ctx.createGain()\n\tosc.connect(rampGain)\n\trampGain.connect(dest)\n\tosc.frequency.value = frequency\n\tosc.type = instrument ?? 'sine'\n\tosc.start()\n\tconst endTime = ctx.currentTime + duration*2/1000",
"score": 34.74546714235583
},
{
"filename": "src/base/palette.ts",
"retrieved_chunk": "\tconst [ r, g, b, a ] = hex.match(/\\w\\w/g)?.map((x) => parseInt(x, 16)) ?? []\n\treturn [ r!, g!, b!, a ?? 255 ]\n}\nexport const rgbaToHex = (rgba: Rgba): string => {\n\treturn '#' + rgba.map(n => n.toString(16).padStart(2, '0')).join('')\n}",
"score": 23.494943106585467
},
{
"filename": "src/api.ts",
"retrieved_chunk": "export type InstrumentType = typeof instruments[number]\nexport const instrumentKey: Record<string, InstrumentType> = {\n\t'~': 'sine',\n\t'-': 'square',\n\t'^': 'triangle',\n\t'/': 'sawtooth'\n}\nexport const reverseInstrumentKey = Object.fromEntries(\n\tObject.entries(instrumentKey).map(([ k, v ]) => [ v, k ])\n) as Record<InstrumentType, string>",
"score": 23.156040094548196
}
] | typescript | }${reverseInstrumentKey[instrument as InstrumentType]}${note}`
)
return tune.map(notesToString).join(',\n')
} |
|
import { type InputKey, type PlayTuneRes, VALID_INPUTS, type FullSprigAPI, type GameState } from '../api.js'
import { type BaseEngineAPI, baseEngine, textToTune } from '../base/index.js'
import { bitmapTextToImageData } from '../image-data/index.js'
import { getTextImg } from './text.js'
import { playTune } from './tune.js'
import { makeCanvas } from './util.js'
export * from './text.js'
export * from './tune.js'
export type WebEngineAPI = BaseEngineAPI & Pick<
FullSprigAPI,
| 'setLegend'
| 'onInput'
| 'afterInput'
| 'playTune'
> & {
getState(): GameState // For weird backwards-compatibility reasons, not part of API
}
export function webEngine(canvas: HTMLCanvasElement): {
api: WebEngineAPI,
state: GameState,
cleanup(): void
} {
const { api, state } = baseEngine()
const ctx = canvas.getContext('2d')!
const offscreenCanvas = makeCanvas(1, 1)
const offscreenCtx = offscreenCanvas.getContext('2d')!
const _bitmaps: Record<string, CanvasImageSource> = {}
let _zOrder: string[] = []
ctx.imageSmoothingEnabled = false
const _gameloop = (): void => {
const { width, height } = state.dimensions
if (width === 0 || height === 0) return
ctx.clearRect(0, 0, canvas.width, canvas.height)
offscreenCanvas.width = width*16
offscreenCanvas.height = height*16
offscreenCtx.fillStyle = 'white'
offscreenCtx.fillRect(0, 0, width*16, height*16)
const grid = api.getGrid()
for (let i = 0; i < width * height; i++) {
const x = i % width
const y = Math.floor(i/width)
const sprites = grid[i]!
if (state.background) {
const imgData = _bitmaps[state.background]!
offscreenCtx.drawImage(imgData, x*16, y*16)
}
sprites
.sort((a, b) => _zOrder.indexOf(b.type) - _zOrder.indexOf(a.type))
.forEach((sprite) => {
const imgData = _bitmaps[sprite.type]!
offscreenCtx.drawImage(imgData, x*16, y*16)
})
}
const scale = Math.min(canvas.width/(width*16), canvas.height/(height*16))
const actualWidth = offscreenCanvas.width*scale
const actualHeight = offscreenCanvas.height*scale
ctx.drawImage(
offscreenCanvas,
(canvas.width-actualWidth)/2,
(canvas.height-actualHeight)/2,
actualWidth,
actualHeight
)
const textCanvas = getTextImg(state.texts)
ctx.drawImage(
textCanvas,
0,
0,
canvas.width,
canvas.height
)
animationId = window.requestAnimationFrame(_gameloop)
}
let animationId = window.requestAnimationFrame(_gameloop)
const setLegend = (...bitmaps: [string, string][]): void => {
if (bitmaps.length == 0) throw new Error('There needs to be at least one sprite in the legend.')
if (!Array.isArray(bitmaps[0])) throw new Error('The sprites passed into setLegend each need to be in square brackets, like setLegend([player, bitmap`...`]).')
bitmaps.forEach(([ key ]) => {
if (key === '.') throw new Error(`Can't reassign "." bitmap`)
if (key.length !== 1) throw new Error(`Bitmaps must have one character names`)
})
state.legend = bitmaps
_zOrder = bitmaps.map(x => x[0])
for (let i = 0; i < bitmaps.length; i++) {
const [ key, value ] = bitmaps[i]!
const imgData = bitmapTextToImageData(value)
const littleCanvas = makeCanvas(16, 16)
littleCanvas.getContext('2d')!.putImageData(imgData, 0, 0)
_bitmaps[key] = littleCanvas
}
}
| let tileInputs: Record<InputKey, (() => void)[]> = { |
w: [],
s: [],
a: [],
d: [],
i: [],
j: [],
k: [],
l: []
}
const afterInputs: (() => void)[] = []
const keydown = (e: KeyboardEvent) => {
const key = e.key
if (!VALID_INPUTS.includes(key as any)) return
for (const validKey of VALID_INPUTS)
if (key === validKey) tileInputs[key].forEach(fn => fn())
afterInputs.forEach(f => f())
state.sprites.forEach((s: any) => {
s.dx = 0
s.dy = 0
})
e.preventDefault()
}
canvas.addEventListener('keydown', keydown)
const onInput = (key: InputKey, fn: () => void): void => {
if (!VALID_INPUTS.includes(key))
throw new Error(`Unknown input key, "${key}": expected one of ${VALID_INPUTS.join(', ')}`)
tileInputs[key].push(fn)
}
const afterInput = (fn: () => void): void => { afterInputs.push(fn) }
const tunes: PlayTuneRes[] = []
return {
api: {
...api,
setLegend,
onInput,
afterInput,
getState: () => state,
playTune: (text: string, n: number) => {
const tune = textToTune(text)
const playTuneRes = playTune(tune, n)
tunes.push(playTuneRes)
return playTuneRes
}
},
state,
cleanup: () => {
ctx.clearRect(0, 0, canvas.width, canvas.height)
window.cancelAnimationFrame(animationId)
canvas.removeEventListener('keydown', keydown)
tunes.forEach(tune => tune.end())
}
}
}
| src/web/index.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/image-data/index.ts",
"retrieved_chunk": "\t}\n\tconst api = {\n\t\t...game.api,\n\t\tonInput: (key: InputKey, fn: () => void) => keyHandlers[key].push(fn),\n\t\tafterInput: (fn: () => void) => afterInputs.push(fn),\n\t\tsetLegend: (...bitmaps: [string, string][]) => {\n\t\t\tgame.state.legend = bitmaps\n\t\t\tlegendImages = {}\n\t\t\tfor (const [ id, desc ] of bitmaps)\n\t\t\t\tlegendImages[id] = bitmapTextToImageData(desc)",
"score": 39.00663761355433
},
{
"filename": "src/base/tune.ts",
"retrieved_chunk": "}\nexport const tuneToText = (tune: Tune): string => {\n\tconst groupNotes = (notes: (number | string)[]) => {\n\t\tconst groups = []\n\t\tfor (let i = 0; i < notes.length; i++) {\n\t\t\tif (i % 3 === 0) {\n\t\t\t\tgroups.push([notes[i]!])\n\t\t\t} else {\n\t\t\t\tgroups[groups.length-1]!.push(notes[i]!)\n\t\t\t}",
"score": 30.862120701630438
},
{
"filename": "src/base/index.ts",
"retrieved_chunk": "\t\tconst h = rows.length\n\t\tgameState.dimensions.width = w\n\t\tgameState.dimensions.height = h\n\t\tgameState.sprites = []\n\t\tconst nonSpace = string.split(\"\").filter(x => x !== \" \" && x !== \"\\n\") // \\S regex was too slow\n\t\tfor (let i = 0; i < w*h; i++) {\n\t\t\tconst type = nonSpace[i]!\n\t\t\tif (type === '.') continue\n\t\t\tconst x = i%w \n\t\t\tconst y = Math.floor(i/w)",
"score": 30.299956952452874
},
{
"filename": "src/web/text.ts",
"retrieved_chunk": "\t\t\t\t\ty++\n\t\t\t}\n\t\t\txt += 8\n\t\t}\n\t}\n\tconst canvas = makeCanvas(160, 128)\n\tcanvas.getContext('2d')!.putImageData(img, 0, 0)\n\treturn canvas\n}",
"score": 29.05964174451739
},
{
"filename": "src/base/index.ts",
"retrieved_chunk": "\t\tconst noMovement = dx === 0 && dy === 0\n\t\tconst movingToEmpty = i < grid.length && grid[i]!.length === 0\n\t\tif (notSolid || noMovement || movingToEmpty) {\n\t\t\tsprite._x += dx\n\t\t\tsprite._y += dy\n\t\t\treturn true\n\t\t}\n\t\tlet canMove = true\n\t\tconst { pushable } = gameState\n\t\tgrid[i]!.forEach(sprite => {",
"score": 27.347950041712252
}
] | typescript | let tileInputs: Record<InputKey, (() => void)[]> = { |
import { type InputKey, type PlayTuneRes, VALID_INPUTS, type FullSprigAPI, type GameState } from '../api.js'
import { type BaseEngineAPI, baseEngine, textToTune } from '../base/index.js'
import { bitmapTextToImageData } from '../image-data/index.js'
import { getTextImg } from './text.js'
import { playTune } from './tune.js'
import { makeCanvas } from './util.js'
export * from './text.js'
export * from './tune.js'
export type WebEngineAPI = BaseEngineAPI & Pick<
FullSprigAPI,
| 'setLegend'
| 'onInput'
| 'afterInput'
| 'playTune'
> & {
getState(): GameState // For weird backwards-compatibility reasons, not part of API
}
export function webEngine(canvas: HTMLCanvasElement): {
api: WebEngineAPI,
state: GameState,
cleanup(): void
} {
const { api, state } = baseEngine()
const ctx = canvas.getContext('2d')!
const offscreenCanvas = makeCanvas(1, 1)
const offscreenCtx = offscreenCanvas.getContext('2d')!
const _bitmaps: Record<string, CanvasImageSource> = {}
let _zOrder: string[] = []
ctx.imageSmoothingEnabled = false
const _gameloop = (): void => {
const { width, height } = state.dimensions
if (width === 0 || height === 0) return
ctx.clearRect(0, 0, canvas.width, canvas.height)
offscreenCanvas.width = width*16
offscreenCanvas.height = height*16
offscreenCtx.fillStyle = 'white'
offscreenCtx.fillRect(0, 0, width*16, height*16)
const grid = api.getGrid()
for (let i = 0; i < width * height; i++) {
const x = i % width
const y = Math.floor(i/width)
const sprites = grid[i]!
if (state.background) {
const imgData = _bitmaps[state.background]!
offscreenCtx.drawImage(imgData, x*16, y*16)
}
sprites
.sort((a | , b) => _zOrder.indexOf(b.type) - _zOrder.indexOf(a.type))
.forEach((sprite) => { |
const imgData = _bitmaps[sprite.type]!
offscreenCtx.drawImage(imgData, x*16, y*16)
})
}
const scale = Math.min(canvas.width/(width*16), canvas.height/(height*16))
const actualWidth = offscreenCanvas.width*scale
const actualHeight = offscreenCanvas.height*scale
ctx.drawImage(
offscreenCanvas,
(canvas.width-actualWidth)/2,
(canvas.height-actualHeight)/2,
actualWidth,
actualHeight
)
const textCanvas = getTextImg(state.texts)
ctx.drawImage(
textCanvas,
0,
0,
canvas.width,
canvas.height
)
animationId = window.requestAnimationFrame(_gameloop)
}
let animationId = window.requestAnimationFrame(_gameloop)
const setLegend = (...bitmaps: [string, string][]): void => {
if (bitmaps.length == 0) throw new Error('There needs to be at least one sprite in the legend.')
if (!Array.isArray(bitmaps[0])) throw new Error('The sprites passed into setLegend each need to be in square brackets, like setLegend([player, bitmap`...`]).')
bitmaps.forEach(([ key ]) => {
if (key === '.') throw new Error(`Can't reassign "." bitmap`)
if (key.length !== 1) throw new Error(`Bitmaps must have one character names`)
})
state.legend = bitmaps
_zOrder = bitmaps.map(x => x[0])
for (let i = 0; i < bitmaps.length; i++) {
const [ key, value ] = bitmaps[i]!
const imgData = bitmapTextToImageData(value)
const littleCanvas = makeCanvas(16, 16)
littleCanvas.getContext('2d')!.putImageData(imgData, 0, 0)
_bitmaps[key] = littleCanvas
}
}
let tileInputs: Record<InputKey, (() => void)[]> = {
w: [],
s: [],
a: [],
d: [],
i: [],
j: [],
k: [],
l: []
}
const afterInputs: (() => void)[] = []
const keydown = (e: KeyboardEvent) => {
const key = e.key
if (!VALID_INPUTS.includes(key as any)) return
for (const validKey of VALID_INPUTS)
if (key === validKey) tileInputs[key].forEach(fn => fn())
afterInputs.forEach(f => f())
state.sprites.forEach((s: any) => {
s.dx = 0
s.dy = 0
})
e.preventDefault()
}
canvas.addEventListener('keydown', keydown)
const onInput = (key: InputKey, fn: () => void): void => {
if (!VALID_INPUTS.includes(key))
throw new Error(`Unknown input key, "${key}": expected one of ${VALID_INPUTS.join(', ')}`)
tileInputs[key].push(fn)
}
const afterInput = (fn: () => void): void => { afterInputs.push(fn) }
const tunes: PlayTuneRes[] = []
return {
api: {
...api,
setLegend,
onInput,
afterInput,
getState: () => state,
playTune: (text: string, n: number) => {
const tune = textToTune(text)
const playTuneRes = playTune(tune, n)
tunes.push(playTuneRes)
return playTuneRes
}
},
state,
cleanup: () => {
ctx.clearRect(0, 0, canvas.width, canvas.height)
window.cancelAnimationFrame(animationId)
canvas.removeEventListener('keydown', keydown)
tunes.forEach(tune => tune.end())
}
}
}
| src/web/index.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/base/index.ts",
"retrieved_chunk": "\t\t})\n\t\tconst legendIndex = (t: SpriteType) => gameState.legend.findIndex(l => l[0] == t.type)\n\t\tfor (const tile of grid) tile.sort((a, b) => legendIndex(a) - legendIndex(b))\n\t\treturn grid\n\t}\n\tconst _checkBounds = (x: number, y: number): void => {\n\t\tconst { width, height } = gameState.dimensions\n\t\tif (x >= width || x < 0 || y < 0 || y >= height) throw new Error(`Sprite out of bounds.`)\n\t}\n\tconst _checkLegend = (type: string): void => {",
"score": 33.795961957861294
},
{
"filename": "src/base/index.ts",
"retrieved_chunk": "\t\tconst h = rows.length\n\t\tgameState.dimensions.width = w\n\t\tgameState.dimensions.height = h\n\t\tgameState.sprites = []\n\t\tconst nonSpace = string.split(\"\").filter(x => x !== \" \" && x !== \"\\n\") // \\S regex was too slow\n\t\tfor (let i = 0; i < w*h; i++) {\n\t\t\tconst type = nonSpace[i]!\n\t\t\tif (type === '.') continue\n\t\t\tconst x = i%w \n\t\t\tconst y = Math.floor(i/w)",
"score": 29.10323304242373
},
{
"filename": "src/base/index.ts",
"retrieved_chunk": "\t\t\tsprite._y += dy\n\t\t}\n\t\treturn canMove\n\t}\n\tconst getGrid = (): SpriteType[][] => {\n\t\tconst { width, height } = gameState.dimensions\n\t\tconst grid: SpriteType[][] = new Array(width*height).fill(0).map(_ => [])\n\t\tgameState.sprites.forEach(s => {\n\t\t\tconst i = s.x+s.y*width\n\t\t\tgrid[i]!.push(s)",
"score": 27.92038744332249
},
{
"filename": "src/image-data/bitmap.ts",
"retrieved_chunk": " const colors = Object.fromEntries(palette)\n const nonSpace = text.split('').filter(x => x !== ' ' && x !== '\\n') // \\S regex led to massive perf problems\n for (let i = 0; i < width*height; i++) {\n const type = nonSpace[i] || \".\"\n if (!(type in colors)) {\n const err = `in sprite string: no known color for char \"${type}\"`\n console.error(err + '\\n' + text)\n throw new Error(err + ' (invalid sprite in console)')\n }\n const [ r, g, b, a ] = colors[type] ?? colors['.']!",
"score": 26.722354024233788
},
{
"filename": "src/base/palette.ts",
"retrieved_chunk": "\tconst [ r, g, b, a ] = hex.match(/\\w\\w/g)?.map((x) => parseInt(x, 16)) ?? []\n\treturn [ r!, g!, b!, a ?? 255 ]\n}\nexport const rgbaToHex = (rgba: Rgba): string => {\n\treturn '#' + rgba.map(n => n.toString(16).padStart(2, '0')).join('')\n}",
"score": 26.610913489784284
}
] | typescript | , b) => _zOrder.indexOf(b.type) - _zOrder.indexOf(a.type))
.forEach((sprite) => { |
import { type InputKey, type PlayTuneRes, VALID_INPUTS, type FullSprigAPI, type GameState } from '../api.js'
import { type BaseEngineAPI, baseEngine, textToTune } from '../base/index.js'
import { bitmapTextToImageData } from '../image-data/index.js'
import { getTextImg } from './text.js'
import { playTune } from './tune.js'
import { makeCanvas } from './util.js'
export * from './text.js'
export * from './tune.js'
export type WebEngineAPI = BaseEngineAPI & Pick<
FullSprigAPI,
| 'setLegend'
| 'onInput'
| 'afterInput'
| 'playTune'
> & {
getState(): GameState // For weird backwards-compatibility reasons, not part of API
}
export function webEngine(canvas: HTMLCanvasElement): {
api: WebEngineAPI,
state: GameState,
cleanup(): void
} {
const { api, state } = baseEngine()
const ctx = canvas.getContext('2d')!
const offscreenCanvas = makeCanvas(1, 1)
const offscreenCtx = offscreenCanvas.getContext('2d')!
const _bitmaps: Record<string, CanvasImageSource> = {}
let _zOrder: string[] = []
ctx.imageSmoothingEnabled = false
const _gameloop = (): void => {
const { width, height } = state.dimensions
if (width === 0 || height === 0) return
ctx.clearRect(0, 0, canvas.width, canvas.height)
offscreenCanvas.width = width*16
offscreenCanvas.height = height*16
offscreenCtx.fillStyle = 'white'
offscreenCtx.fillRect(0, 0, width*16, height*16)
const grid = api.getGrid()
for (let i = 0; i < width * height; i++) {
const x = i % width
const y = Math.floor(i/width)
const sprites = grid[i]!
if (state.background) {
const imgData = _bitmaps[state.background]!
offscreenCtx.drawImage(imgData, x*16, y*16)
}
sprites
.sort((a, b) => _zOrder.indexOf(b.type) - _zOrder.indexOf(a.type))
.forEach((sprite) => {
const imgData = _bitmaps[sprite.type]!
offscreenCtx.drawImage(imgData, x*16, y*16)
})
}
const scale = Math.min(canvas.width/(width*16), canvas.height/(height*16))
const actualWidth = offscreenCanvas.width*scale
const actualHeight = offscreenCanvas.height*scale
ctx.drawImage(
offscreenCanvas,
(canvas.width-actualWidth)/2,
(canvas.height-actualHeight)/2,
actualWidth,
actualHeight
)
const textCanvas = getTextImg(state.texts)
ctx.drawImage(
textCanvas,
0,
0,
canvas.width,
canvas.height
)
animationId = window.requestAnimationFrame(_gameloop)
}
let animationId = window.requestAnimationFrame(_gameloop)
const setLegend = (...bitmaps: [string, string][]): void => {
if (bitmaps.length == 0) throw new Error('There needs to be at least one sprite in the legend.')
if (!Array.isArray(bitmaps[0])) throw new Error('The sprites passed into setLegend each need to be in square brackets, like setLegend([player, bitmap`...`]).')
bitmaps.forEach(([ key ]) => {
if (key === '.') throw new Error(`Can't reassign "." bitmap`)
if (key.length !== 1) throw new Error(`Bitmaps must have one character names`)
})
state.legend = bitmaps
_zOrder = bitmaps.map(x => x[0])
for (let i = 0; i < bitmaps.length; i++) {
const [ key, value ] = bitmaps[i]!
const imgData = bitmapTextToImageData(value)
const littleCanvas = makeCanvas(16, 16)
littleCanvas.getContext('2d')!.putImageData(imgData, 0, 0)
_bitmaps[key] = littleCanvas
}
}
let tileInputs: Record<InputKey, (() => void)[]> = {
w: [],
s: [],
a: [],
d: [],
i: [],
j: [],
k: [],
l: []
}
const afterInputs: (() => void)[] = []
const keydown = (e: KeyboardEvent) => {
const key = e.key
if (!VALID_INPUTS.includes(key as any)) return
for (const validKey of VALID_INPUTS)
if (key === validKey) tileInputs[key].forEach(fn => fn())
afterInputs.forEach(f => f())
state.sprites.forEach((s: any) => {
s.dx = 0
s.dy = 0
})
e.preventDefault()
}
canvas.addEventListener('keydown', keydown)
const onInput = (key: InputKey, fn: () => void): void => {
if (!VALID_INPUTS.includes(key))
throw new Error(`Unknown input key, "${key}": expected one of ${VALID_INPUTS.join(', ')}`)
tileInputs[key].push(fn)
}
const afterInput = (fn: () => void): void => { afterInputs.push(fn) }
const tunes: PlayTuneRes[] = []
return {
api: {
...api,
setLegend,
onInput,
afterInput,
getState: () => state,
playTune: (text: string, n: number) => {
| const tune = textToTune(text)
const playTuneRes = playTune(tune, n)
tunes.push(playTuneRes)
return playTuneRes
} |
},
state,
cleanup: () => {
ctx.clearRect(0, 0, canvas.width, canvas.height)
window.cancelAnimationFrame(animationId)
canvas.removeEventListener('keydown', keydown)
tunes.forEach(tune => tune.end())
}
}
}
| src/web/index.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/api.ts",
"retrieved_chunk": "\theight(): number\n\tsetLegend(...bitmaps: [string, string][]): void\n\tonInput(key: InputKey, fn: () => void): void \n\tafterInput(fn: () => void): void\n\tplayTune(text: string, n?: number): PlayTuneRes\n\tsetTimeout(fn: TimerHandler, ms: number): number\n\tsetInterval(fn: TimerHandler, ms: number): number\n\tclearTimeout(id: number): void\n\tclearInterval(id: number): void\n}",
"score": 31.829763717194457
},
{
"filename": "src/image-data/index.ts",
"retrieved_chunk": "\t}\n\tconst api = {\n\t\t...game.api,\n\t\tonInput: (key: InputKey, fn: () => void) => keyHandlers[key].push(fn),\n\t\tafterInput: (fn: () => void) => afterInputs.push(fn),\n\t\tsetLegend: (...bitmaps: [string, string][]) => {\n\t\t\tgame.state.legend = bitmaps\n\t\t\tlegendImages = {}\n\t\t\tfor (const [ id, desc ] of bitmaps)\n\t\t\t\tlegendImages[id] = bitmapTextToImageData(desc)",
"score": 19.26799944682592
},
{
"filename": "src/web/tune.ts",
"retrieved_chunk": "export function playTune(tune: Tune, number = 1): PlayTuneRes {\n\tconst playingRef = { playing: true }\n\tif (audioCtx === null) audioCtx = new AudioContext()\n\tplayTuneHelper(tune, number, playingRef, audioCtx, audioCtx.destination)\n\treturn {\n\t\tend() { playingRef.playing = false },\n\t\tisPlaying() { return playingRef.playing }\n\t}\n}",
"score": 17.603336684723853
},
{
"filename": "src/base/index.ts",
"retrieved_chunk": "\t\ttune: _makeTag(text => text),\n\t\tgetFirst: (type: string): SpriteType | undefined => gameState.sprites.find(t => t.type === type), // **\n\t\tgetAll: (type: string): SpriteType[] => type ? gameState.sprites.filter(t => t.type === type) : gameState.sprites, // **\n\t\twidth: () => gameState.dimensions.width,\n\t\theight: () => gameState.dimensions.height\n\t}\n\treturn { api, state: gameState }\n}",
"score": 17.03271348073588
},
{
"filename": "src/base/tune.ts",
"retrieved_chunk": "\t)\n\treturn tune.map(notesToString).join(',\\n')\n}",
"score": 16.795983970128493
}
] | typescript | const tune = textToTune(text)
const playTuneRes = playTune(tune, n)
tunes.push(playTuneRes)
return playTuneRes
} |
import type { AddTextOptions, FullSprigAPI, GameState, SpriteType } from '../api.js'
import { palette } from './palette.js'
export * from './font.js'
export * from './palette.js'
export * from './text.js'
export * from './tune.js'
// Tagged template literal factory go brrr
const _makeTag = <T>(cb: (string: string) => T) => {
return (strings: TemplateStringsArray, ...interps: string[]) => {
if (typeof strings === 'string') {
throw new Error('Tagged template literal must be used like name`text`, instead of name(`text`)')
}
const string = strings.reduce((p, c, i) => p + c + (interps[i] ?? ''), '')
return cb(string)
}
}
export type BaseEngineAPI = Pick<
FullSprigAPI,
| 'setMap'
| 'addText'
| 'clearText'
| 'addSprite'
| 'getGrid'
| 'getTile'
| 'tilesWith'
| 'clearTile'
| 'setSolids'
| 'setPushables'
| 'setBackground'
| 'map'
| 'bitmap'
| 'color'
| 'tune'
| 'getFirst'
| 'getAll'
| 'width'
| 'height'
>
export function baseEngine(): { api: BaseEngineAPI, state: GameState } {
const gameState: GameState = {
legend: [],
texts: [],
dimensions: {
width: 0,
height: 0,
},
sprites: [],
solids: [],
pushable: {},
background: null
}
class | Sprite implements SpriteType { |
_type: string
_x: number
_y: number
dx: number
dy: number
constructor(type: string, x: number, y: number) {
this._type = type
this._x = x
this._y = y
this.dx = 0
this.dy = 0
}
set type(newType) {
const legendDict = Object.fromEntries(gameState.legend)
if (!(newType in legendDict)) throw new Error(`"${newType}" isn\'t in the legend.`)
this.remove()
addSprite(this._x, this._y, newType)
}
get type() {
return this._type
}
set x(newX) {
const dx = newX - this.x
if (_canMoveToPush(this, dx, 0)) this.dx = dx
}
get x() {
return this._x
}
set y(newY) {
const dy = newY - this.y
if (_canMoveToPush(this, 0, dy)) this.dy = dy
}
get y() {
return this._y
}
remove() {
gameState.sprites = gameState.sprites.filter(s => s !== this)
return this
}
}
const _canMoveToPush = (sprite: Sprite, dx: number, dy: number): boolean => {
const { x, y, type } = sprite
const { width, height } = gameState.dimensions
const i = (x+dx)+(y+dy)*width
const inBounds = (x+dx < width && x+dx >= 0 && y+dy < height && y+dy >= 0)
if (!inBounds) return false
const grid = getGrid()
const notSolid = !gameState.solids.includes(type)
const noMovement = dx === 0 && dy === 0
const movingToEmpty = i < grid.length && grid[i]!.length === 0
if (notSolid || noMovement || movingToEmpty) {
sprite._x += dx
sprite._y += dy
return true
}
let canMove = true
const { pushable } = gameState
grid[i]!.forEach(sprite => {
const isSolid = gameState.solids.includes(sprite.type)
const isPushable = (type in pushable) && pushable[type]!.includes(sprite.type)
if (isSolid && !isPushable)
canMove = false
if (isSolid && isPushable) {
canMove = canMove && _canMoveToPush(sprite as Sprite, dx, dy)
}
})
if (canMove) {
sprite._x += dx
sprite._y += dy
}
return canMove
}
const getGrid = (): SpriteType[][] => {
const { width, height } = gameState.dimensions
const grid: SpriteType[][] = new Array(width*height).fill(0).map(_ => [])
gameState.sprites.forEach(s => {
const i = s.x+s.y*width
grid[i]!.push(s)
})
const legendIndex = (t: SpriteType) => gameState.legend.findIndex(l => l[0] == t.type)
for (const tile of grid) tile.sort((a, b) => legendIndex(a) - legendIndex(b))
return grid
}
const _checkBounds = (x: number, y: number): void => {
const { width, height } = gameState.dimensions
if (x >= width || x < 0 || y < 0 || y >= height) throw new Error(`Sprite out of bounds.`)
}
const _checkLegend = (type: string): void => {
if (!(type in Object.fromEntries(gameState.legend)))
throw new Error(`Unknown sprite type: ${type}`)
}
const addSprite = (x: number, y: number, type: string): void => {
if (type === '.') return
_checkBounds(x, y)
_checkLegend(type)
const s = new Sprite(type, x, y)
gameState.sprites.push(s)
}
const _allEqual = <T>(arr: T[]): boolean => arr.every(val => val === arr[0])
const setMap = (string: string): void => {
if (!string) throw new Error('Tried to set empty map.')
if (string.constructor == Object) throw new Error('setMap() takes a string, not a dict.') // https://stackoverflow.com/a/51285298
if (Array.isArray(string)) throw new Error('It looks like you passed an array into setMap(). Did you mean to use something like setMap(levels[level]) instead of setMap(levels)?')
const rows = string.trim().split("\n").map(x => x.trim())
const rowLengths = rows.map(x => x.length)
const isRect = _allEqual(rowLengths)
if (!isRect) throw new Error('Level must be rectangular.')
const w = rows[0]?.length ?? 0
const h = rows.length
gameState.dimensions.width = w
gameState.dimensions.height = h
gameState.sprites = []
const nonSpace = string.split("").filter(x => x !== " " && x !== "\n") // \S regex was too slow
for (let i = 0; i < w*h; i++) {
const type = nonSpace[i]!
if (type === '.') continue
const x = i%w
const y = Math.floor(i/w)
addSprite(x, y, type)
}
}
const clearTile = (x: number, y: number): void => {
gameState.sprites = gameState.sprites.filter(s => s.x !== x || s.y !== y)
}
const addText = (str: string, opts: AddTextOptions = {}): void => {
const CHARS_MAX_X = 21
const padLeft = Math.floor((CHARS_MAX_X - str.length)/2)
if (Array.isArray(opts.color)) throw new Error('addText no longer takes an RGBA color. Please use a Sprig color instead with \"{ color: color`` }\"')
const [, rgba ] = palette.find(([key]) => key === opts.color) ?? palette.find(([key]) => key === 'L')!
gameState.texts.push({
x: opts.x ?? padLeft,
y: opts.y ?? 0,
color: rgba,
content: str
})
}
const clearText = (): void => { gameState.texts = [] }
const getTile = (x: number, y: number): SpriteType[] => {
if (y < 0) return []
if (x < 0) return []
if (y >= gameState.dimensions.height) return []
if (x >= gameState.dimensions.width) return []
return getGrid()[gameState.dimensions.width*y+x] ?? []
}
const _hasDuplicates = <T>(array: T[]): boolean => (new Set(array)).size !== array.length
const tilesWith = (...matchingTypes: string[]): SpriteType[][] => {
const { width, height } = gameState.dimensions
const tiles: SpriteType[][] = []
const grid = getGrid()
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
const tile = grid[width*y+x] || []
const matchIndices = matchingTypes.map(type => {
return tile.map(s => s.type).indexOf(type)
})
if (!_hasDuplicates(matchIndices) && !matchIndices.includes(-1)) tiles.push(tile)
}
}
return tiles
}
const setSolids = (arr: string[]): void => {
if (!Array.isArray(arr)) throw new Error('The sprites passed into setSolids() need to be an array.')
gameState.solids = arr
}
const setPushables = (map: Record<string, string[]>): void => {
for (const key in map) {
if(key.length != 1) {
throw new Error('Your sprite name must be wrapped in [] brackets here.');
}
_checkLegend(key)
}
gameState.pushable = map
}
const api: BaseEngineAPI = {
setMap,
addText,
clearText,
addSprite,
getGrid,
getTile,
tilesWith,
clearTile,
setSolids,
setPushables,
setBackground: (type: string) => { gameState.background = type },
map: _makeTag(text => text),
bitmap: _makeTag(text => text),
color: _makeTag(text => text),
tune: _makeTag(text => text),
getFirst: (type: string): SpriteType | undefined => gameState.sprites.find(t => t.type === type), // **
getAll: (type: string): SpriteType[] => type ? gameState.sprites.filter(t => t.type === type) : gameState.sprites, // **
width: () => gameState.dimensions.width,
height: () => gameState.dimensions.height
}
return { api, state: gameState }
}
| src/base/index.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/api.ts",
"retrieved_chunk": "\tsolids: string[]\n\tpushable: Record<string, string[]>\n\tbackground: string | null\n}\nexport interface PlayTuneRes {\n\tend(): void\n\tisPlaying(): boolean\n}\nexport const tones: Record<string, number> = {\n\t'B0': 31,",
"score": 18.776235778893493
},
{
"filename": "src/api.ts",
"retrieved_chunk": "\tcontent: string\n}\nexport interface GameState {\n\tlegend: [string, string][]\n\ttexts: TextElement[]\n\tdimensions: {\n\t\twidth: number\n\t\theight: number\n\t}\n\tsprites: SpriteType[]",
"score": 14.036491807804808
},
{
"filename": "src/web/index.ts",
"retrieved_chunk": "\t\tconst { width, height } = state.dimensions\n\t\tif (width === 0 || height === 0) return\n\t\tctx.clearRect(0, 0, canvas.width, canvas.height)\n\t\toffscreenCanvas.width = width*16\n\t\toffscreenCanvas.height = height*16\n\t\toffscreenCtx.fillStyle = 'white'\n\t\toffscreenCtx.fillRect(0, 0, width*16, height*16)\n\t\tconst grid = api.getGrid()\n\t\tfor (let i = 0; i < width * height; i++) {\n\t\t\tconst x = i % width",
"score": 11.899608378619346
},
{
"filename": "src/image-data/index.ts",
"retrieved_chunk": "\t\t\t\ts.dx = 0\n\t\t\t\ts.dy = 0\n\t\t\t})\n\t\t},\n\t\trender(): ImageData {\n\t\t\tconst width = () => game.state.dimensions.width\n\t\t\tconst height = () => game.state.dimensions.height\n\t\t\tconst tSize = () => 16\n\t\t\tconst sw = width() * tSize()\n\t\t\tconst sh = height() * tSize()",
"score": 10.256242049223832
},
{
"filename": "src/web/index.ts",
"retrieved_chunk": "\t\t\tconst y = Math.floor(i/width)\n\t\t\tconst sprites = grid[i]!\n\t\t\tif (state.background) {\n\t\t\t\tconst imgData = _bitmaps[state.background]!\n\t\t\t\toffscreenCtx.drawImage(imgData, x*16, y*16)\n\t\t\t}\n\t\t\tsprites\n\t\t\t\t.sort((a, b) => _zOrder.indexOf(b.type) - _zOrder.indexOf(a.type))\n\t\t\t\t.forEach((sprite) => {\n\t\t\t\t\tconst imgData = _bitmaps[sprite.type]!",
"score": 10.24199887153003
}
] | typescript | Sprite implements SpriteType { |
import { type InputKey, type PlayTuneRes, VALID_INPUTS, type FullSprigAPI, type GameState } from '../api.js'
import { type BaseEngineAPI, baseEngine, textToTune } from '../base/index.js'
import { bitmapTextToImageData } from '../image-data/index.js'
import { getTextImg } from './text.js'
import { playTune } from './tune.js'
import { makeCanvas } from './util.js'
export * from './text.js'
export * from './tune.js'
export type WebEngineAPI = BaseEngineAPI & Pick<
FullSprigAPI,
| 'setLegend'
| 'onInput'
| 'afterInput'
| 'playTune'
> & {
getState(): GameState // For weird backwards-compatibility reasons, not part of API
}
export function webEngine(canvas: HTMLCanvasElement): {
api: WebEngineAPI,
state: GameState,
cleanup(): void
} {
const { api, state } = baseEngine()
const ctx = canvas.getContext('2d')!
const offscreenCanvas = makeCanvas(1, 1)
const offscreenCtx = offscreenCanvas.getContext('2d')!
const _bitmaps: Record<string, CanvasImageSource> = {}
let _zOrder: string[] = []
ctx.imageSmoothingEnabled = false
const _gameloop = (): void => {
const { width, height } = state.dimensions
if (width === 0 || height === 0) return
ctx.clearRect(0, 0, canvas.width, canvas.height)
offscreenCanvas.width = width*16
offscreenCanvas.height = height*16
offscreenCtx.fillStyle = 'white'
offscreenCtx.fillRect(0, 0, width*16, height*16)
const grid = api.getGrid()
for (let i = 0; i < width * height; i++) {
const x = i % width
const y = Math.floor(i/width)
const sprites = grid[i]!
if (state.background) {
const imgData = _bitmaps[state.background]!
offscreenCtx.drawImage(imgData, x*16, y*16)
}
sprites
.sort((a, b) => _zOrder.indexOf(b.type) - _zOrder.indexOf(a.type))
.forEach((sprite) => {
const imgData = _bitmaps[sprite.type]!
offscreenCtx.drawImage(imgData, x*16, y*16)
})
}
const scale = Math.min(canvas.width/(width*16), canvas.height/(height*16))
const actualWidth = offscreenCanvas.width*scale
const actualHeight = offscreenCanvas.height*scale
ctx.drawImage(
offscreenCanvas,
(canvas.width-actualWidth)/2,
(canvas.height-actualHeight)/2,
actualWidth,
actualHeight
)
const textCanvas = getTextImg(state.texts)
ctx.drawImage(
textCanvas,
0,
0,
canvas.width,
canvas.height
)
animationId = window.requestAnimationFrame(_gameloop)
}
let animationId = window.requestAnimationFrame(_gameloop)
const setLegend = (...bitmaps: [string, string][]): void => {
if (bitmaps.length == 0) throw new Error('There needs to be at least one sprite in the legend.')
if (!Array.isArray(bitmaps[0])) throw new Error('The sprites passed into setLegend each need to be in square brackets, like setLegend([player, bitmap`...`]).')
bitmaps.forEach(([ key ]) => {
if (key === '.') throw new Error(`Can't reassign "." bitmap`)
if (key.length !== 1) throw new Error(`Bitmaps must have one character names`)
})
state.legend = bitmaps
_zOrder = bitmaps.map(x => x[0])
for (let i = 0; i < bitmaps.length; i++) {
const [ key, value ] = bitmaps[i]!
const imgData = bitmapTextToImageData(value)
const littleCanvas = makeCanvas(16, 16)
littleCanvas.getContext('2d')!.putImageData(imgData, 0, 0)
_bitmaps[key] = littleCanvas
}
}
let tileInputs: Record<InputKey, (() => void)[]> = {
w: [],
s: [],
a: [],
d: [],
i: [],
j: [],
k: [],
l: []
}
const afterInputs: (() => void)[] = []
const keydown = (e: KeyboardEvent) => {
const key = e.key
if (!VALID_INPUTS.includes(key as any)) return
for (const validKey of VALID_INPUTS)
if (key === validKey) tileInputs[key].forEach(fn => fn())
afterInputs.forEach(f => f())
state.sprites.forEach((s: any) => {
s.dx = 0
s.dy = 0
})
e.preventDefault()
}
canvas.addEventListener('keydown', keydown)
const onInput = (key: InputKey, fn: () => void): void => {
if (!VALID_INPUTS.includes(key))
throw new Error(`Unknown input key, "${key}": expected one of ${VALID_INPUTS.join(', ')}`)
tileInputs[key].push(fn)
}
const afterInput = (fn: () => void): void => { afterInputs.push(fn) }
const tunes: PlayTuneRes[] = []
return {
api: {
...api,
setLegend,
onInput,
afterInput,
getState: () => state,
playTune: (text: string, n: number) => {
const tune = textToTune(text)
| const playTuneRes = playTune(tune, n)
tunes.push(playTuneRes)
return playTuneRes
} |
},
state,
cleanup: () => {
ctx.clearRect(0, 0, canvas.width, canvas.height)
window.cancelAnimationFrame(animationId)
canvas.removeEventListener('keydown', keydown)
tunes.forEach(tune => tune.end())
}
}
}
| src/web/index.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/api.ts",
"retrieved_chunk": "\theight(): number\n\tsetLegend(...bitmaps: [string, string][]): void\n\tonInput(key: InputKey, fn: () => void): void \n\tafterInput(fn: () => void): void\n\tplayTune(text: string, n?: number): PlayTuneRes\n\tsetTimeout(fn: TimerHandler, ms: number): number\n\tsetInterval(fn: TimerHandler, ms: number): number\n\tclearTimeout(id: number): void\n\tclearInterval(id: number): void\n}",
"score": 31.829763717194457
},
{
"filename": "src/image-data/index.ts",
"retrieved_chunk": "\t}\n\tconst api = {\n\t\t...game.api,\n\t\tonInput: (key: InputKey, fn: () => void) => keyHandlers[key].push(fn),\n\t\tafterInput: (fn: () => void) => afterInputs.push(fn),\n\t\tsetLegend: (...bitmaps: [string, string][]) => {\n\t\t\tgame.state.legend = bitmaps\n\t\t\tlegendImages = {}\n\t\t\tfor (const [ id, desc ] of bitmaps)\n\t\t\t\tlegendImages[id] = bitmapTextToImageData(desc)",
"score": 19.26799944682592
},
{
"filename": "src/web/tune.ts",
"retrieved_chunk": "export function playTune(tune: Tune, number = 1): PlayTuneRes {\n\tconst playingRef = { playing: true }\n\tif (audioCtx === null) audioCtx = new AudioContext()\n\tplayTuneHelper(tune, number, playingRef, audioCtx, audioCtx.destination)\n\treturn {\n\t\tend() { playingRef.playing = false },\n\t\tisPlaying() { return playingRef.playing }\n\t}\n}",
"score": 17.603336684723853
},
{
"filename": "src/base/index.ts",
"retrieved_chunk": "\t\ttune: _makeTag(text => text),\n\t\tgetFirst: (type: string): SpriteType | undefined => gameState.sprites.find(t => t.type === type), // **\n\t\tgetAll: (type: string): SpriteType[] => type ? gameState.sprites.filter(t => t.type === type) : gameState.sprites, // **\n\t\twidth: () => gameState.dimensions.width,\n\t\theight: () => gameState.dimensions.height\n\t}\n\treturn { api, state: gameState }\n}",
"score": 17.03271348073588
},
{
"filename": "src/base/tune.ts",
"retrieved_chunk": "\t)\n\treturn tune.map(notesToString).join(',\\n')\n}",
"score": 16.795983970128493
}
] | typescript | const playTuneRes = playTune(tune, n)
tunes.push(playTuneRes)
return playTuneRes
} |
import type { AddTextOptions, FullSprigAPI, GameState, SpriteType } from '../api.js'
import { palette } from './palette.js'
export * from './font.js'
export * from './palette.js'
export * from './text.js'
export * from './tune.js'
// Tagged template literal factory go brrr
const _makeTag = <T>(cb: (string: string) => T) => {
return (strings: TemplateStringsArray, ...interps: string[]) => {
if (typeof strings === 'string') {
throw new Error('Tagged template literal must be used like name`text`, instead of name(`text`)')
}
const string = strings.reduce((p, c, i) => p + c + (interps[i] ?? ''), '')
return cb(string)
}
}
export type BaseEngineAPI = Pick<
FullSprigAPI,
| 'setMap'
| 'addText'
| 'clearText'
| 'addSprite'
| 'getGrid'
| 'getTile'
| 'tilesWith'
| 'clearTile'
| 'setSolids'
| 'setPushables'
| 'setBackground'
| 'map'
| 'bitmap'
| 'color'
| 'tune'
| 'getFirst'
| 'getAll'
| 'width'
| 'height'
>
export function baseEngine(): { api: BaseEngineAPI, state: GameState } {
const gameState: GameState = {
legend: [],
texts: [],
dimensions: {
width: 0,
height: 0,
},
sprites: [],
solids: [],
pushable: {},
background: null
}
class Sprite implements SpriteType {
_type: string
_x: number
_y: number
dx: number
dy: number
constructor(type: string, x: number, y: number) {
this._type = type
this._x = x
this._y = y
this.dx = 0
this.dy = 0
}
set type(newType) {
const legendDict = Object.fromEntries(gameState.legend)
if (!(newType in legendDict)) throw new Error(`"${newType}" isn\'t in the legend.`)
this.remove()
addSprite(this._x, this._y, newType)
}
get type() {
return this._type
}
set x(newX) {
const dx = newX - this.x
if (_canMoveToPush(this, dx, 0)) this.dx = dx
}
get x() {
return this._x
}
set y(newY) {
const dy = newY - this.y
if (_canMoveToPush(this, 0, dy)) this.dy = dy
}
get y() {
return this._y
}
remove() {
gameState | .sprites = gameState.sprites.filter(s => s !== this)
return this
} |
}
const _canMoveToPush = (sprite: Sprite, dx: number, dy: number): boolean => {
const { x, y, type } = sprite
const { width, height } = gameState.dimensions
const i = (x+dx)+(y+dy)*width
const inBounds = (x+dx < width && x+dx >= 0 && y+dy < height && y+dy >= 0)
if (!inBounds) return false
const grid = getGrid()
const notSolid = !gameState.solids.includes(type)
const noMovement = dx === 0 && dy === 0
const movingToEmpty = i < grid.length && grid[i]!.length === 0
if (notSolid || noMovement || movingToEmpty) {
sprite._x += dx
sprite._y += dy
return true
}
let canMove = true
const { pushable } = gameState
grid[i]!.forEach(sprite => {
const isSolid = gameState.solids.includes(sprite.type)
const isPushable = (type in pushable) && pushable[type]!.includes(sprite.type)
if (isSolid && !isPushable)
canMove = false
if (isSolid && isPushable) {
canMove = canMove && _canMoveToPush(sprite as Sprite, dx, dy)
}
})
if (canMove) {
sprite._x += dx
sprite._y += dy
}
return canMove
}
const getGrid = (): SpriteType[][] => {
const { width, height } = gameState.dimensions
const grid: SpriteType[][] = new Array(width*height).fill(0).map(_ => [])
gameState.sprites.forEach(s => {
const i = s.x+s.y*width
grid[i]!.push(s)
})
const legendIndex = (t: SpriteType) => gameState.legend.findIndex(l => l[0] == t.type)
for (const tile of grid) tile.sort((a, b) => legendIndex(a) - legendIndex(b))
return grid
}
const _checkBounds = (x: number, y: number): void => {
const { width, height } = gameState.dimensions
if (x >= width || x < 0 || y < 0 || y >= height) throw new Error(`Sprite out of bounds.`)
}
const _checkLegend = (type: string): void => {
if (!(type in Object.fromEntries(gameState.legend)))
throw new Error(`Unknown sprite type: ${type}`)
}
const addSprite = (x: number, y: number, type: string): void => {
if (type === '.') return
_checkBounds(x, y)
_checkLegend(type)
const s = new Sprite(type, x, y)
gameState.sprites.push(s)
}
const _allEqual = <T>(arr: T[]): boolean => arr.every(val => val === arr[0])
const setMap = (string: string): void => {
if (!string) throw new Error('Tried to set empty map.')
if (string.constructor == Object) throw new Error('setMap() takes a string, not a dict.') // https://stackoverflow.com/a/51285298
if (Array.isArray(string)) throw new Error('It looks like you passed an array into setMap(). Did you mean to use something like setMap(levels[level]) instead of setMap(levels)?')
const rows = string.trim().split("\n").map(x => x.trim())
const rowLengths = rows.map(x => x.length)
const isRect = _allEqual(rowLengths)
if (!isRect) throw new Error('Level must be rectangular.')
const w = rows[0]?.length ?? 0
const h = rows.length
gameState.dimensions.width = w
gameState.dimensions.height = h
gameState.sprites = []
const nonSpace = string.split("").filter(x => x !== " " && x !== "\n") // \S regex was too slow
for (let i = 0; i < w*h; i++) {
const type = nonSpace[i]!
if (type === '.') continue
const x = i%w
const y = Math.floor(i/w)
addSprite(x, y, type)
}
}
const clearTile = (x: number, y: number): void => {
gameState.sprites = gameState.sprites.filter(s => s.x !== x || s.y !== y)
}
const addText = (str: string, opts: AddTextOptions = {}): void => {
const CHARS_MAX_X = 21
const padLeft = Math.floor((CHARS_MAX_X - str.length)/2)
if (Array.isArray(opts.color)) throw new Error('addText no longer takes an RGBA color. Please use a Sprig color instead with \"{ color: color`` }\"')
const [, rgba ] = palette.find(([key]) => key === opts.color) ?? palette.find(([key]) => key === 'L')!
gameState.texts.push({
x: opts.x ?? padLeft,
y: opts.y ?? 0,
color: rgba,
content: str
})
}
const clearText = (): void => { gameState.texts = [] }
const getTile = (x: number, y: number): SpriteType[] => {
if (y < 0) return []
if (x < 0) return []
if (y >= gameState.dimensions.height) return []
if (x >= gameState.dimensions.width) return []
return getGrid()[gameState.dimensions.width*y+x] ?? []
}
const _hasDuplicates = <T>(array: T[]): boolean => (new Set(array)).size !== array.length
const tilesWith = (...matchingTypes: string[]): SpriteType[][] => {
const { width, height } = gameState.dimensions
const tiles: SpriteType[][] = []
const grid = getGrid()
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
const tile = grid[width*y+x] || []
const matchIndices = matchingTypes.map(type => {
return tile.map(s => s.type).indexOf(type)
})
if (!_hasDuplicates(matchIndices) && !matchIndices.includes(-1)) tiles.push(tile)
}
}
return tiles
}
const setSolids = (arr: string[]): void => {
if (!Array.isArray(arr)) throw new Error('The sprites passed into setSolids() need to be an array.')
gameState.solids = arr
}
const setPushables = (map: Record<string, string[]>): void => {
for (const key in map) {
if(key.length != 1) {
throw new Error('Your sprite name must be wrapped in [] brackets here.');
}
_checkLegend(key)
}
gameState.pushable = map
}
const api: BaseEngineAPI = {
setMap,
addText,
clearText,
addSprite,
getGrid,
getTile,
tilesWith,
clearTile,
setSolids,
setPushables,
setBackground: (type: string) => { gameState.background = type },
map: _makeTag(text => text),
bitmap: _makeTag(text => text),
color: _makeTag(text => text),
tune: _makeTag(text => text),
getFirst: (type: string): SpriteType | undefined => gameState.sprites.find(t => t.type === type), // **
getAll: (type: string): SpriteType[] => type ? gameState.sprites.filter(t => t.type === type) : gameState.sprites, // **
width: () => gameState.dimensions.width,
height: () => gameState.dimensions.height
}
return { api, state: gameState }
}
| src/base/index.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/web/tune.ts",
"retrieved_chunk": "\tosc.stop(endTime)\n\trampGain.gain.setValueAtTime(0, ctx.currentTime)\n\trampGain.gain.linearRampToValueAtTime(.2, ctx.currentTime + duration/5/1000)\n\trampGain.gain.exponentialRampToValueAtTime(0.00001, ctx.currentTime + duration/1000)\n\trampGain.gain.linearRampToValueAtTime(0, ctx.currentTime + duration*2/1000) // does this ramp from the last ramp\n\tosc.onended = () => {\n\t\tosc.disconnect()\n\t\trampGain.disconnect()\n\t}\n}",
"score": 22.684916676026706
},
{
"filename": "src/image-data/index.ts",
"retrieved_chunk": "\t\t\t\ts.dx = 0\n\t\t\t\ts.dy = 0\n\t\t\t})\n\t\t},\n\t\trender(): ImageData {\n\t\t\tconst width = () => game.state.dimensions.width\n\t\t\tconst height = () => game.state.dimensions.height\n\t\t\tconst tSize = () => 16\n\t\t\tconst sw = width() * tSize()\n\t\t\tconst sh = height() * tSize()",
"score": 21.089928019136657
},
{
"filename": "src/api.ts",
"retrieved_chunk": "\ty: number\n\treadonly dx: number\n\treadonly dy: number\n\tremove(): void\n}\nexport type Rgba = [number, number, number, number]\nexport interface TextElement {\n\tx: number\n\ty: number\n\tcolor: Rgba",
"score": 21.041639028018782
},
{
"filename": "src/web/index.ts",
"retrieved_chunk": "\t}\n\tconst afterInputs: (() => void)[] = []\n\tconst keydown = (e: KeyboardEvent) => {\n\t\tconst key = e.key\n\t\tif (!VALID_INPUTS.includes(key as any)) return\n\t\tfor (const validKey of VALID_INPUTS)\n\t\t\tif (key === validKey) tileInputs[key].forEach(fn => fn())\n\t\tafterInputs.forEach(f => f())\n\t\tstate.sprites.forEach((s: any) => {\n\t\t\ts.dx = 0",
"score": 19.698126143971123
},
{
"filename": "src/web/index.ts",
"retrieved_chunk": "\t\t\ts.dy = 0\n\t\t})\n\t\te.preventDefault()\n\t}\n\tcanvas.addEventListener('keydown', keydown)\n\tconst onInput = (key: InputKey, fn: () => void): void => {\n\t\tif (!VALID_INPUTS.includes(key))\n\t\t\tthrow new Error(`Unknown input key, \"${key}\": expected one of ${VALID_INPUTS.join(', ')}`)\n\t\ttileInputs[key].push(fn)\n\t}",
"score": 19.645005854633876
}
] | typescript | .sprites = gameState.sprites.filter(s => s !== this)
return this
} |
import type { AddTextOptions, FullSprigAPI, GameState, SpriteType } from '../api.js'
import { palette } from './palette.js'
export * from './font.js'
export * from './palette.js'
export * from './text.js'
export * from './tune.js'
// Tagged template literal factory go brrr
const _makeTag = <T>(cb: (string: string) => T) => {
return (strings: TemplateStringsArray, ...interps: string[]) => {
if (typeof strings === 'string') {
throw new Error('Tagged template literal must be used like name`text`, instead of name(`text`)')
}
const string = strings.reduce((p, c, i) => p + c + (interps[i] ?? ''), '')
return cb(string)
}
}
export type BaseEngineAPI = Pick<
FullSprigAPI,
| 'setMap'
| 'addText'
| 'clearText'
| 'addSprite'
| 'getGrid'
| 'getTile'
| 'tilesWith'
| 'clearTile'
| 'setSolids'
| 'setPushables'
| 'setBackground'
| 'map'
| 'bitmap'
| 'color'
| 'tune'
| 'getFirst'
| 'getAll'
| 'width'
| 'height'
>
export function baseEngine(): { api | : BaseEngineAPI, state: GameState } { |
const gameState: GameState = {
legend: [],
texts: [],
dimensions: {
width: 0,
height: 0,
},
sprites: [],
solids: [],
pushable: {},
background: null
}
class Sprite implements SpriteType {
_type: string
_x: number
_y: number
dx: number
dy: number
constructor(type: string, x: number, y: number) {
this._type = type
this._x = x
this._y = y
this.dx = 0
this.dy = 0
}
set type(newType) {
const legendDict = Object.fromEntries(gameState.legend)
if (!(newType in legendDict)) throw new Error(`"${newType}" isn\'t in the legend.`)
this.remove()
addSprite(this._x, this._y, newType)
}
get type() {
return this._type
}
set x(newX) {
const dx = newX - this.x
if (_canMoveToPush(this, dx, 0)) this.dx = dx
}
get x() {
return this._x
}
set y(newY) {
const dy = newY - this.y
if (_canMoveToPush(this, 0, dy)) this.dy = dy
}
get y() {
return this._y
}
remove() {
gameState.sprites = gameState.sprites.filter(s => s !== this)
return this
}
}
const _canMoveToPush = (sprite: Sprite, dx: number, dy: number): boolean => {
const { x, y, type } = sprite
const { width, height } = gameState.dimensions
const i = (x+dx)+(y+dy)*width
const inBounds = (x+dx < width && x+dx >= 0 && y+dy < height && y+dy >= 0)
if (!inBounds) return false
const grid = getGrid()
const notSolid = !gameState.solids.includes(type)
const noMovement = dx === 0 && dy === 0
const movingToEmpty = i < grid.length && grid[i]!.length === 0
if (notSolid || noMovement || movingToEmpty) {
sprite._x += dx
sprite._y += dy
return true
}
let canMove = true
const { pushable } = gameState
grid[i]!.forEach(sprite => {
const isSolid = gameState.solids.includes(sprite.type)
const isPushable = (type in pushable) && pushable[type]!.includes(sprite.type)
if (isSolid && !isPushable)
canMove = false
if (isSolid && isPushable) {
canMove = canMove && _canMoveToPush(sprite as Sprite, dx, dy)
}
})
if (canMove) {
sprite._x += dx
sprite._y += dy
}
return canMove
}
const getGrid = (): SpriteType[][] => {
const { width, height } = gameState.dimensions
const grid: SpriteType[][] = new Array(width*height).fill(0).map(_ => [])
gameState.sprites.forEach(s => {
const i = s.x+s.y*width
grid[i]!.push(s)
})
const legendIndex = (t: SpriteType) => gameState.legend.findIndex(l => l[0] == t.type)
for (const tile of grid) tile.sort((a, b) => legendIndex(a) - legendIndex(b))
return grid
}
const _checkBounds = (x: number, y: number): void => {
const { width, height } = gameState.dimensions
if (x >= width || x < 0 || y < 0 || y >= height) throw new Error(`Sprite out of bounds.`)
}
const _checkLegend = (type: string): void => {
if (!(type in Object.fromEntries(gameState.legend)))
throw new Error(`Unknown sprite type: ${type}`)
}
const addSprite = (x: number, y: number, type: string): void => {
if (type === '.') return
_checkBounds(x, y)
_checkLegend(type)
const s = new Sprite(type, x, y)
gameState.sprites.push(s)
}
const _allEqual = <T>(arr: T[]): boolean => arr.every(val => val === arr[0])
const setMap = (string: string): void => {
if (!string) throw new Error('Tried to set empty map.')
if (string.constructor == Object) throw new Error('setMap() takes a string, not a dict.') // https://stackoverflow.com/a/51285298
if (Array.isArray(string)) throw new Error('It looks like you passed an array into setMap(). Did you mean to use something like setMap(levels[level]) instead of setMap(levels)?')
const rows = string.trim().split("\n").map(x => x.trim())
const rowLengths = rows.map(x => x.length)
const isRect = _allEqual(rowLengths)
if (!isRect) throw new Error('Level must be rectangular.')
const w = rows[0]?.length ?? 0
const h = rows.length
gameState.dimensions.width = w
gameState.dimensions.height = h
gameState.sprites = []
const nonSpace = string.split("").filter(x => x !== " " && x !== "\n") // \S regex was too slow
for (let i = 0; i < w*h; i++) {
const type = nonSpace[i]!
if (type === '.') continue
const x = i%w
const y = Math.floor(i/w)
addSprite(x, y, type)
}
}
const clearTile = (x: number, y: number): void => {
gameState.sprites = gameState.sprites.filter(s => s.x !== x || s.y !== y)
}
const addText = (str: string, opts: AddTextOptions = {}): void => {
const CHARS_MAX_X = 21
const padLeft = Math.floor((CHARS_MAX_X - str.length)/2)
if (Array.isArray(opts.color)) throw new Error('addText no longer takes an RGBA color. Please use a Sprig color instead with \"{ color: color`` }\"')
const [, rgba ] = palette.find(([key]) => key === opts.color) ?? palette.find(([key]) => key === 'L')!
gameState.texts.push({
x: opts.x ?? padLeft,
y: opts.y ?? 0,
color: rgba,
content: str
})
}
const clearText = (): void => { gameState.texts = [] }
const getTile = (x: number, y: number): SpriteType[] => {
if (y < 0) return []
if (x < 0) return []
if (y >= gameState.dimensions.height) return []
if (x >= gameState.dimensions.width) return []
return getGrid()[gameState.dimensions.width*y+x] ?? []
}
const _hasDuplicates = <T>(array: T[]): boolean => (new Set(array)).size !== array.length
const tilesWith = (...matchingTypes: string[]): SpriteType[][] => {
const { width, height } = gameState.dimensions
const tiles: SpriteType[][] = []
const grid = getGrid()
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
const tile = grid[width*y+x] || []
const matchIndices = matchingTypes.map(type => {
return tile.map(s => s.type).indexOf(type)
})
if (!_hasDuplicates(matchIndices) && !matchIndices.includes(-1)) tiles.push(tile)
}
}
return tiles
}
const setSolids = (arr: string[]): void => {
if (!Array.isArray(arr)) throw new Error('The sprites passed into setSolids() need to be an array.')
gameState.solids = arr
}
const setPushables = (map: Record<string, string[]>): void => {
for (const key in map) {
if(key.length != 1) {
throw new Error('Your sprite name must be wrapped in [] brackets here.');
}
_checkLegend(key)
}
gameState.pushable = map
}
const api: BaseEngineAPI = {
setMap,
addText,
clearText,
addSprite,
getGrid,
getTile,
tilesWith,
clearTile,
setSolids,
setPushables,
setBackground: (type: string) => { gameState.background = type },
map: _makeTag(text => text),
bitmap: _makeTag(text => text),
color: _makeTag(text => text),
tune: _makeTag(text => text),
getFirst: (type: string): SpriteType | undefined => gameState.sprites.find(t => t.type === type), // **
getAll: (type: string): SpriteType[] => type ? gameState.sprites.filter(t => t.type === type) : gameState.sprites, // **
width: () => gameState.dimensions.width,
height: () => gameState.dimensions.height
}
return { api, state: gameState }
}
| src/base/index.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/image-data/index.ts",
"retrieved_chunk": "import type { FullSprigAPI, GameState, InputKey } from '../api.js'\nimport { type BaseEngineAPI, baseEngine } from '../base/index.js'\nimport { bitmapTextToImageData } from './bitmap.js'\nexport * from './bitmap.js'\nexport type ImageDataEngineAPI = BaseEngineAPI & Pick<\n\tFullSprigAPI,\n\t| 'onInput'\n\t| 'afterInput'\n\t| 'setLegend'\n\t| 'setBackground'",
"score": 21.224340267653698
},
{
"filename": "src/web/index.ts",
"retrieved_chunk": "import { type InputKey, type PlayTuneRes, VALID_INPUTS, type FullSprigAPI, type GameState } from '../api.js'\nimport { type BaseEngineAPI, baseEngine, textToTune } from '../base/index.js'\nimport { bitmapTextToImageData } from '../image-data/index.js'\nimport { getTextImg } from './text.js'\nimport { playTune } from './tune.js'\nimport { makeCanvas } from './util.js'\nexport * from './text.js'\nexport * from './tune.js'\nexport type WebEngineAPI = BaseEngineAPI & Pick<\n\tFullSprigAPI,",
"score": 16.3252775805306
},
{
"filename": "src/web/index.ts",
"retrieved_chunk": "\t| 'setLegend'\n\t| 'onInput'\n\t| 'afterInput'\n\t| 'playTune'\n> & {\n\tgetState(): GameState // For weird backwards-compatibility reasons, not part of API\n}\nexport function webEngine(canvas: HTMLCanvasElement): {\n\tapi: WebEngineAPI,\n\tstate: GameState,",
"score": 14.00094613859607
},
{
"filename": "src/web/util.ts",
"retrieved_chunk": "export function makeCanvas(width: number, height: number): HTMLCanvasElement {\n\tconst canvas = document.createElement('canvas')\n\tcanvas.width = width\n\tcanvas.height = height\n\treturn canvas\n}",
"score": 12.36759210845839
},
{
"filename": "src/web/index.ts",
"retrieved_chunk": "\t\tconst { width, height } = state.dimensions\n\t\tif (width === 0 || height === 0) return\n\t\tctx.clearRect(0, 0, canvas.width, canvas.height)\n\t\toffscreenCanvas.width = width*16\n\t\toffscreenCanvas.height = height*16\n\t\toffscreenCtx.fillStyle = 'white'\n\t\toffscreenCtx.fillRect(0, 0, width*16, height*16)\n\t\tconst grid = api.getGrid()\n\t\tfor (let i = 0; i < width * height; i++) {\n\t\t\tconst x = i % width",
"score": 11.06205992792433
}
] | typescript | : BaseEngineAPI, state: GameState } { |
import { type InputKey, type PlayTuneRes, VALID_INPUTS, type FullSprigAPI, type GameState } from '../api.js'
import { type BaseEngineAPI, baseEngine, textToTune } from '../base/index.js'
import { bitmapTextToImageData } from '../image-data/index.js'
import { getTextImg } from './text.js'
import { playTune } from './tune.js'
import { makeCanvas } from './util.js'
export * from './text.js'
export * from './tune.js'
export type WebEngineAPI = BaseEngineAPI & Pick<
FullSprigAPI,
| 'setLegend'
| 'onInput'
| 'afterInput'
| 'playTune'
> & {
getState(): GameState // For weird backwards-compatibility reasons, not part of API
}
export function webEngine(canvas: HTMLCanvasElement): {
api: WebEngineAPI,
state: GameState,
cleanup(): void
} {
const { api, state } = baseEngine()
const ctx = canvas.getContext('2d')!
const offscreenCanvas = makeCanvas(1, 1)
const offscreenCtx = offscreenCanvas.getContext('2d')!
const _bitmaps: Record<string, CanvasImageSource> = {}
let _zOrder: string[] = []
ctx.imageSmoothingEnabled = false
const _gameloop = (): void => {
const { width, height } = state.dimensions
if (width === 0 || height === 0) return
ctx.clearRect(0, 0, canvas.width, canvas.height)
offscreenCanvas.width = width*16
offscreenCanvas.height = height*16
offscreenCtx.fillStyle = 'white'
offscreenCtx.fillRect(0, 0, width*16, height*16)
const grid = api.getGrid()
for (let i = 0; i < width * height; i++) {
const x = i % width
const y = Math.floor(i/width)
const sprites = grid[i]!
if (state.background) {
const imgData = _bitmaps[state.background]!
offscreenCtx.drawImage(imgData, x*16, y*16)
}
sprites
.sort((a, b) => _zOrder.indexOf(b.type) - _zOrder.indexOf(a.type))
.forEach((sprite) => {
const imgData = _bitmaps[sprite.type]!
offscreenCtx.drawImage(imgData, x*16, y*16)
})
}
const scale = Math.min(canvas.width/(width*16), canvas.height/(height*16))
const actualWidth = offscreenCanvas.width*scale
const actualHeight = offscreenCanvas.height*scale
ctx.drawImage(
offscreenCanvas,
(canvas.width-actualWidth)/2,
(canvas.height-actualHeight)/2,
actualWidth,
actualHeight
)
const textCanvas = getTextImg(state.texts)
ctx.drawImage(
textCanvas,
0,
0,
canvas.width,
canvas.height
)
animationId = window.requestAnimationFrame(_gameloop)
}
let animationId = window.requestAnimationFrame(_gameloop)
const setLegend = (...bitmaps: [string, string][]): void => {
if (bitmaps.length == 0) throw new Error('There needs to be at least one sprite in the legend.')
if (!Array.isArray(bitmaps[0])) throw new Error('The sprites passed into setLegend each need to be in square brackets, like setLegend([player, bitmap`...`]).')
bitmaps.forEach(([ key ]) => {
if (key === '.') throw new Error(`Can't reassign "." bitmap`)
if (key.length !== 1) throw new Error(`Bitmaps must have one character names`)
})
state.legend = bitmaps
_zOrder = bitmaps.map(x => x[0])
for (let i = 0; i < bitmaps.length; i++) {
const [ key, value ] = bitmaps[i]!
const imgData = bitmapTextToImageData(value)
const littleCanvas = makeCanvas(16, 16)
littleCanvas.getContext('2d')!.putImageData(imgData, 0, 0)
_bitmaps[key] = littleCanvas
}
}
let tileInputs: Record<InputKey, (() => void)[]> = {
w: [],
s: [],
a: [],
d: [],
i: [],
j: [],
k: [],
l: []
}
const afterInputs: (() => void)[] = []
const keydown = (e: KeyboardEvent) => {
const key = e.key
if (!VALID_INPUTS.includes(key as any)) return
for (const validKey of VALID_INPUTS)
if (key === validKey) tileInputs[key].forEach(fn => fn())
afterInputs.forEach(f => f())
state.sprites.forEach((s: any) => {
s.dx = 0
s.dy = 0
})
e.preventDefault()
}
canvas.addEventListener('keydown', keydown)
const onInput = (key: InputKey, fn: () => void): void => {
if (!VALID_INPUTS.includes(key))
throw new Error(`Unknown input key, "${key}": expected one of ${VALID_INPUTS.join(', ')}`)
tileInputs[key].push(fn)
}
const afterInput = (fn: () => void): void => { afterInputs.push(fn) }
const tunes: | PlayTuneRes[] = []
return { |
api: {
...api,
setLegend,
onInput,
afterInput,
getState: () => state,
playTune: (text: string, n: number) => {
const tune = textToTune(text)
const playTuneRes = playTune(tune, n)
tunes.push(playTuneRes)
return playTuneRes
}
},
state,
cleanup: () => {
ctx.clearRect(0, 0, canvas.width, canvas.height)
window.cancelAnimationFrame(animationId)
canvas.removeEventListener('keydown', keydown)
tunes.forEach(tune => tune.end())
}
}
}
| src/web/index.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/image-data/index.ts",
"retrieved_chunk": "\t}\n\tconst api = {\n\t\t...game.api,\n\t\tonInput: (key: InputKey, fn: () => void) => keyHandlers[key].push(fn),\n\t\tafterInput: (fn: () => void) => afterInputs.push(fn),\n\t\tsetLegend: (...bitmaps: [string, string][]) => {\n\t\t\tgame.state.legend = bitmaps\n\t\t\tlegendImages = {}\n\t\t\tfor (const [ id, desc ] of bitmaps)\n\t\t\t\tlegendImages[id] = bitmapTextToImageData(desc)",
"score": 76.65952287132416
},
{
"filename": "src/image-data/index.ts",
"retrieved_chunk": "\t\t\treturn timer\n\t\t},\n\t\tplayTune: () => ({ end() {}, isPlaying() { return false } })\n\t}\n\treturn {\n\t\tapi,\n\t\tbutton(key: InputKey): void {\n\t\t\tfor (const fn of keyHandlers[key]) fn()\n\t\t\tfor (const fn of afterInputs) fn()\n\t\t\tgame.state.sprites.forEach((s: any) => {",
"score": 64.05778656894103
},
{
"filename": "src/api.ts",
"retrieved_chunk": "\theight(): number\n\tsetLegend(...bitmaps: [string, string][]): void\n\tonInput(key: InputKey, fn: () => void): void \n\tafterInput(fn: () => void): void\n\tplayTune(text: string, n?: number): PlayTuneRes\n\tsetTimeout(fn: TimerHandler, ms: number): number\n\tsetInterval(fn: TimerHandler, ms: number): number\n\tclearTimeout(id: number): void\n\tclearInterval(id: number): void\n}",
"score": 62.85792937448801
},
{
"filename": "src/base/index.ts",
"retrieved_chunk": "\t\treturn tiles\n\t}\n\tconst setSolids = (arr: string[]): void => { \n\t\tif (!Array.isArray(arr)) throw new Error('The sprites passed into setSolids() need to be an array.')\n\t\tgameState.solids = arr \n\t}\n\tconst setPushables = (map: Record<string, string[]>): void => { \n\t\tfor (const key in map) {\n\t\t\tif(key.length != 1) {\n\t\t\t\tthrow new Error('Your sprite name must be wrapped in [] brackets here.');",
"score": 38.0980491743673
},
{
"filename": "src/base/index.ts",
"retrieved_chunk": "\t\tconst [, rgba ] = palette.find(([key]) => key === opts.color) ?? palette.find(([key]) => key === 'L')!\n\t\tgameState.texts.push({\n\t\t\tx: opts.x ?? padLeft,\n\t\t\ty: opts.y ?? 0,\n\t\t\tcolor: rgba,\n\t\t\tcontent: str\n\t\t})\n\t}\n\tconst clearText = (): void => { gameState.texts = [] }\n\tconst getTile = (x: number, y: number): SpriteType[] => {",
"score": 37.12255354280949
}
] | typescript | PlayTuneRes[] = []
return { |
import { type InstrumentType, type PlayTuneRes, type Tune, instruments, tones } from '../api.js'
export function playFrequency(frequency: number, duration: number, instrument: InstrumentType, ctx: AudioContext, dest: AudioNode) {
const osc = ctx.createOscillator()
const rampGain = ctx.createGain()
osc.connect(rampGain)
rampGain.connect(dest)
osc.frequency.value = frequency
osc.type = instrument ?? 'sine'
osc.start()
const endTime = ctx.currentTime + duration*2/1000
osc.stop(endTime)
rampGain.gain.setValueAtTime(0, ctx.currentTime)
rampGain.gain.linearRampToValueAtTime(.2, ctx.currentTime + duration/5/1000)
rampGain.gain.exponentialRampToValueAtTime(0.00001, ctx.currentTime + duration/1000)
rampGain.gain.linearRampToValueAtTime(0, ctx.currentTime + duration*2/1000) // does this ramp from the last ramp
osc.onended = () => {
osc.disconnect()
rampGain.disconnect()
}
}
const sleep = async (duration: number) => new Promise(resolve => setTimeout(resolve, duration))
export async function playTuneHelper(tune: Tune, number: number, playingRef: { playing: boolean }, ctx: AudioContext, dest: AudioNode) {
for (let i = 0; i < tune.length*number; i++) {
const index = i%tune.length
if (!playingRef.playing) break
const noteSet = tune[index]!
const sleepTime = noteSet[0]
for (let j = 1; j < noteSet.length; j += 3) {
const instrument = noteSet[j] as InstrumentType
const note = noteSet[j+1]!
const duration = noteSet[j+2] as number
const frequency = typeof note === 'string'
? tones[note.toUpperCase()]
: 2**((note-69)/12)*440
if (instruments.includes(instrument) && frequency !== undefined) playFrequency(frequency, duration, instrument, ctx, dest)
}
await sleep(sleepTime)
}
}
let audioCtx: AudioContext | null = null
export function playTune(tune | : Tune, number = 1): PlayTuneRes { |
const playingRef = { playing: true }
if (audioCtx === null) audioCtx = new AudioContext()
playTuneHelper(tune, number, playingRef, audioCtx, audioCtx.destination)
return {
end() { playingRef.playing = false },
isPlaying() { return playingRef.playing }
}
} | src/web/tune.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/base/tune.ts",
"retrieved_chunk": "\t\t}\n\t\treturn groups\n\t}\n\tconst notesToString = ([duration, ...notes]: Tune[number]) => (\n\t\tnotes.length === 0 \n\t\t\t? duration \n\t\t\t: `${duration}: ${groupNotes(notes).map(notesToStringHelper).join(' + ')}`\n\t)\n\tconst notesToStringHelper = ([instrument, duration, note]: (number | string)[]) => (\n\t\t`${duration}${reverseInstrumentKey[instrument as InstrumentType]}${note}`",
"score": 38.82436536656625
},
{
"filename": "src/api.ts",
"retrieved_chunk": "\tsolids: string[]\n\tpushable: Record<string, string[]>\n\tbackground: string | null\n}\nexport interface PlayTuneRes {\n\tend(): void\n\tisPlaying(): boolean\n}\nexport const tones: Record<string, number> = {\n\t'B0': 31,",
"score": 23.74609199817165
},
{
"filename": "src/base/tune.ts",
"retrieved_chunk": "/*\nsong form\n[\n\t[duration, instrument, pitch, duration, ...],\n]\nSyntax:\n500: 64.4~500 + c5~1000\n[500, 'sine', 64.4, 500, 'sine', 'c5', 1000]\nComma between each tune element. Whitespace ignored.\n*/",
"score": 17.306923915769268
},
{
"filename": "src/base/tune.ts",
"retrieved_chunk": "}\nexport const tuneToText = (tune: Tune): string => {\n\tconst groupNotes = (notes: (number | string)[]) => {\n\t\tconst groups = []\n\t\tfor (let i = 0; i < notes.length; i++) {\n\t\t\tif (i % 3 === 0) {\n\t\t\t\tgroups.push([notes[i]!])\n\t\t\t} else {\n\t\t\t\tgroups[groups.length-1]!.push(notes[i]!)\n\t\t\t}",
"score": 14.292072349947833
},
{
"filename": "src/api.ts",
"retrieved_chunk": "\t'A#1': 58,\n\t'B1': 62,\n\t'C2': 65,\n\t'C#2': 69,\n\t'D2': 73,\n\t'D#2': 78,\n\t'E2': 82,\n\t'F2': 87,\n\t'F#2': 93,\n\t'G2': 98,",
"score": 12.033032276438973
}
] | typescript | : Tune, number = 1): PlayTuneRes { |
import { type InstrumentType, type PlayTuneRes, type Tune, instruments, tones } from '../api.js'
export function playFrequency(frequency: number, duration: number, instrument: InstrumentType, ctx: AudioContext, dest: AudioNode) {
const osc = ctx.createOscillator()
const rampGain = ctx.createGain()
osc.connect(rampGain)
rampGain.connect(dest)
osc.frequency.value = frequency
osc.type = instrument ?? 'sine'
osc.start()
const endTime = ctx.currentTime + duration*2/1000
osc.stop(endTime)
rampGain.gain.setValueAtTime(0, ctx.currentTime)
rampGain.gain.linearRampToValueAtTime(.2, ctx.currentTime + duration/5/1000)
rampGain.gain.exponentialRampToValueAtTime(0.00001, ctx.currentTime + duration/1000)
rampGain.gain.linearRampToValueAtTime(0, ctx.currentTime + duration*2/1000) // does this ramp from the last ramp
osc.onended = () => {
osc.disconnect()
rampGain.disconnect()
}
}
const sleep = async (duration: number) => new Promise(resolve => setTimeout(resolve, duration))
export async function playTuneHelper(tune: Tune, number: number, playingRef: { playing: boolean }, ctx: AudioContext, dest: AudioNode) {
for (let i = 0; i < tune.length*number; i++) {
const index = i%tune.length
if (!playingRef.playing) break
const noteSet = tune[index]!
const sleepTime = noteSet[0]
for (let j = 1; j < noteSet.length; j += 3) {
const instrument = noteSet[j] as InstrumentType
const note = noteSet[j+1]!
const duration = noteSet[j+2] as number
const frequency = typeof note === 'string'
? tones[note.toUpperCase()]
: 2**((note-69)/12)*440
if (instruments.includes(instrument) && frequency !== undefined) playFrequency(frequency, duration, instrument, ctx, dest)
}
await sleep(sleepTime)
}
}
let audioCtx: AudioContext | null = null
| export function playTune(tune: Tune, number = 1): PlayTuneRes { |
const playingRef = { playing: true }
if (audioCtx === null) audioCtx = new AudioContext()
playTuneHelper(tune, number, playingRef, audioCtx, audioCtx.destination)
return {
end() { playingRef.playing = false },
isPlaying() { return playingRef.playing }
}
} | src/web/tune.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/base/tune.ts",
"retrieved_chunk": "\t\t}\n\t\treturn groups\n\t}\n\tconst notesToString = ([duration, ...notes]: Tune[number]) => (\n\t\tnotes.length === 0 \n\t\t\t? duration \n\t\t\t: `${duration}: ${groupNotes(notes).map(notesToStringHelper).join(' + ')}`\n\t)\n\tconst notesToStringHelper = ([instrument, duration, note]: (number | string)[]) => (\n\t\t`${duration}${reverseInstrumentKey[instrument as InstrumentType]}${note}`",
"score": 48.363464157883854
},
{
"filename": "src/api.ts",
"retrieved_chunk": "\tsolids: string[]\n\tpushable: Record<string, string[]>\n\tbackground: string | null\n}\nexport interface PlayTuneRes {\n\tend(): void\n\tisPlaying(): boolean\n}\nexport const tones: Record<string, number> = {\n\t'B0': 31,",
"score": 26.75780958614191
},
{
"filename": "src/base/tune.ts",
"retrieved_chunk": "/*\nsong form\n[\n\t[duration, instrument, pitch, duration, ...],\n]\nSyntax:\n500: 64.4~500 + c5~1000\n[500, 'sine', 64.4, 500, 'sine', 'c5', 1000]\nComma between each tune element. Whitespace ignored.\n*/",
"score": 17.306923915769268
},
{
"filename": "src/base/tune.ts",
"retrieved_chunk": "}\nexport const tuneToText = (tune: Tune): string => {\n\tconst groupNotes = (notes: (number | string)[]) => {\n\t\tconst groups = []\n\t\tfor (let i = 0; i < notes.length; i++) {\n\t\t\tif (i % 3 === 0) {\n\t\t\t\tgroups.push([notes[i]!])\n\t\t\t} else {\n\t\t\t\tgroups[groups.length-1]!.push(notes[i]!)\n\t\t\t}",
"score": 17.280876240883238
},
{
"filename": "src/api.ts",
"retrieved_chunk": "export type InstrumentType = typeof instruments[number]\nexport const instrumentKey: Record<string, InstrumentType> = {\n\t'~': 'sine',\n\t'-': 'square',\n\t'^': 'triangle',\n\t'/': 'sawtooth'\n}\nexport const reverseInstrumentKey = Object.fromEntries(\n\tObject.entries(instrumentKey).map(([ k, v ]) => [ v, k ])\n) as Record<InstrumentType, string>",
"score": 15.44261106121618
}
] | typescript | export function playTune(tune: Tune, number = 1): PlayTuneRes { |
import type { AddTextOptions, FullSprigAPI, GameState, SpriteType } from '../api.js'
import { palette } from './palette.js'
export * from './font.js'
export * from './palette.js'
export * from './text.js'
export * from './tune.js'
// Tagged template literal factory go brrr
const _makeTag = <T>(cb: (string: string) => T) => {
return (strings: TemplateStringsArray, ...interps: string[]) => {
if (typeof strings === 'string') {
throw new Error('Tagged template literal must be used like name`text`, instead of name(`text`)')
}
const string = strings.reduce((p, c, i) => p + c + (interps[i] ?? ''), '')
return cb(string)
}
}
export type BaseEngineAPI = Pick<
FullSprigAPI,
| 'setMap'
| 'addText'
| 'clearText'
| 'addSprite'
| 'getGrid'
| 'getTile'
| 'tilesWith'
| 'clearTile'
| 'setSolids'
| 'setPushables'
| 'setBackground'
| 'map'
| 'bitmap'
| 'color'
| 'tune'
| 'getFirst'
| 'getAll'
| 'width'
| 'height'
>
export function baseEngine() | : { api: BaseEngineAPI, state: GameState } { |
const gameState: GameState = {
legend: [],
texts: [],
dimensions: {
width: 0,
height: 0,
},
sprites: [],
solids: [],
pushable: {},
background: null
}
class Sprite implements SpriteType {
_type: string
_x: number
_y: number
dx: number
dy: number
constructor(type: string, x: number, y: number) {
this._type = type
this._x = x
this._y = y
this.dx = 0
this.dy = 0
}
set type(newType) {
const legendDict = Object.fromEntries(gameState.legend)
if (!(newType in legendDict)) throw new Error(`"${newType}" isn\'t in the legend.`)
this.remove()
addSprite(this._x, this._y, newType)
}
get type() {
return this._type
}
set x(newX) {
const dx = newX - this.x
if (_canMoveToPush(this, dx, 0)) this.dx = dx
}
get x() {
return this._x
}
set y(newY) {
const dy = newY - this.y
if (_canMoveToPush(this, 0, dy)) this.dy = dy
}
get y() {
return this._y
}
remove() {
gameState.sprites = gameState.sprites.filter(s => s !== this)
return this
}
}
const _canMoveToPush = (sprite: Sprite, dx: number, dy: number): boolean => {
const { x, y, type } = sprite
const { width, height } = gameState.dimensions
const i = (x+dx)+(y+dy)*width
const inBounds = (x+dx < width && x+dx >= 0 && y+dy < height && y+dy >= 0)
if (!inBounds) return false
const grid = getGrid()
const notSolid = !gameState.solids.includes(type)
const noMovement = dx === 0 && dy === 0
const movingToEmpty = i < grid.length && grid[i]!.length === 0
if (notSolid || noMovement || movingToEmpty) {
sprite._x += dx
sprite._y += dy
return true
}
let canMove = true
const { pushable } = gameState
grid[i]!.forEach(sprite => {
const isSolid = gameState.solids.includes(sprite.type)
const isPushable = (type in pushable) && pushable[type]!.includes(sprite.type)
if (isSolid && !isPushable)
canMove = false
if (isSolid && isPushable) {
canMove = canMove && _canMoveToPush(sprite as Sprite, dx, dy)
}
})
if (canMove) {
sprite._x += dx
sprite._y += dy
}
return canMove
}
const getGrid = (): SpriteType[][] => {
const { width, height } = gameState.dimensions
const grid: SpriteType[][] = new Array(width*height).fill(0).map(_ => [])
gameState.sprites.forEach(s => {
const i = s.x+s.y*width
grid[i]!.push(s)
})
const legendIndex = (t: SpriteType) => gameState.legend.findIndex(l => l[0] == t.type)
for (const tile of grid) tile.sort((a, b) => legendIndex(a) - legendIndex(b))
return grid
}
const _checkBounds = (x: number, y: number): void => {
const { width, height } = gameState.dimensions
if (x >= width || x < 0 || y < 0 || y >= height) throw new Error(`Sprite out of bounds.`)
}
const _checkLegend = (type: string): void => {
if (!(type in Object.fromEntries(gameState.legend)))
throw new Error(`Unknown sprite type: ${type}`)
}
const addSprite = (x: number, y: number, type: string): void => {
if (type === '.') return
_checkBounds(x, y)
_checkLegend(type)
const s = new Sprite(type, x, y)
gameState.sprites.push(s)
}
const _allEqual = <T>(arr: T[]): boolean => arr.every(val => val === arr[0])
const setMap = (string: string): void => {
if (!string) throw new Error('Tried to set empty map.')
if (string.constructor == Object) throw new Error('setMap() takes a string, not a dict.') // https://stackoverflow.com/a/51285298
if (Array.isArray(string)) throw new Error('It looks like you passed an array into setMap(). Did you mean to use something like setMap(levels[level]) instead of setMap(levels)?')
const rows = string.trim().split("\n").map(x => x.trim())
const rowLengths = rows.map(x => x.length)
const isRect = _allEqual(rowLengths)
if (!isRect) throw new Error('Level must be rectangular.')
const w = rows[0]?.length ?? 0
const h = rows.length
gameState.dimensions.width = w
gameState.dimensions.height = h
gameState.sprites = []
const nonSpace = string.split("").filter(x => x !== " " && x !== "\n") // \S regex was too slow
for (let i = 0; i < w*h; i++) {
const type = nonSpace[i]!
if (type === '.') continue
const x = i%w
const y = Math.floor(i/w)
addSprite(x, y, type)
}
}
const clearTile = (x: number, y: number): void => {
gameState.sprites = gameState.sprites.filter(s => s.x !== x || s.y !== y)
}
const addText = (str: string, opts: AddTextOptions = {}): void => {
const CHARS_MAX_X = 21
const padLeft = Math.floor((CHARS_MAX_X - str.length)/2)
if (Array.isArray(opts.color)) throw new Error('addText no longer takes an RGBA color. Please use a Sprig color instead with \"{ color: color`` }\"')
const [, rgba ] = palette.find(([key]) => key === opts.color) ?? palette.find(([key]) => key === 'L')!
gameState.texts.push({
x: opts.x ?? padLeft,
y: opts.y ?? 0,
color: rgba,
content: str
})
}
const clearText = (): void => { gameState.texts = [] }
const getTile = (x: number, y: number): SpriteType[] => {
if (y < 0) return []
if (x < 0) return []
if (y >= gameState.dimensions.height) return []
if (x >= gameState.dimensions.width) return []
return getGrid()[gameState.dimensions.width*y+x] ?? []
}
const _hasDuplicates = <T>(array: T[]): boolean => (new Set(array)).size !== array.length
const tilesWith = (...matchingTypes: string[]): SpriteType[][] => {
const { width, height } = gameState.dimensions
const tiles: SpriteType[][] = []
const grid = getGrid()
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
const tile = grid[width*y+x] || []
const matchIndices = matchingTypes.map(type => {
return tile.map(s => s.type).indexOf(type)
})
if (!_hasDuplicates(matchIndices) && !matchIndices.includes(-1)) tiles.push(tile)
}
}
return tiles
}
const setSolids = (arr: string[]): void => {
if (!Array.isArray(arr)) throw new Error('The sprites passed into setSolids() need to be an array.')
gameState.solids = arr
}
const setPushables = (map: Record<string, string[]>): void => {
for (const key in map) {
if(key.length != 1) {
throw new Error('Your sprite name must be wrapped in [] brackets here.');
}
_checkLegend(key)
}
gameState.pushable = map
}
const api: BaseEngineAPI = {
setMap,
addText,
clearText,
addSprite,
getGrid,
getTile,
tilesWith,
clearTile,
setSolids,
setPushables,
setBackground: (type: string) => { gameState.background = type },
map: _makeTag(text => text),
bitmap: _makeTag(text => text),
color: _makeTag(text => text),
tune: _makeTag(text => text),
getFirst: (type: string): SpriteType | undefined => gameState.sprites.find(t => t.type === type), // **
getAll: (type: string): SpriteType[] => type ? gameState.sprites.filter(t => t.type === type) : gameState.sprites, // **
width: () => gameState.dimensions.width,
height: () => gameState.dimensions.height
}
return { api, state: gameState }
}
| src/base/index.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/image-data/index.ts",
"retrieved_chunk": "import type { FullSprigAPI, GameState, InputKey } from '../api.js'\nimport { type BaseEngineAPI, baseEngine } from '../base/index.js'\nimport { bitmapTextToImageData } from './bitmap.js'\nexport * from './bitmap.js'\nexport type ImageDataEngineAPI = BaseEngineAPI & Pick<\n\tFullSprigAPI,\n\t| 'onInput'\n\t| 'afterInput'\n\t| 'setLegend'\n\t| 'setBackground'",
"score": 21.224340267653698
},
{
"filename": "src/web/index.ts",
"retrieved_chunk": "import { type InputKey, type PlayTuneRes, VALID_INPUTS, type FullSprigAPI, type GameState } from '../api.js'\nimport { type BaseEngineAPI, baseEngine, textToTune } from '../base/index.js'\nimport { bitmapTextToImageData } from '../image-data/index.js'\nimport { getTextImg } from './text.js'\nimport { playTune } from './tune.js'\nimport { makeCanvas } from './util.js'\nexport * from './text.js'\nexport * from './tune.js'\nexport type WebEngineAPI = BaseEngineAPI & Pick<\n\tFullSprigAPI,",
"score": 16.3252775805306
},
{
"filename": "src/web/index.ts",
"retrieved_chunk": "\t| 'setLegend'\n\t| 'onInput'\n\t| 'afterInput'\n\t| 'playTune'\n> & {\n\tgetState(): GameState // For weird backwards-compatibility reasons, not part of API\n}\nexport function webEngine(canvas: HTMLCanvasElement): {\n\tapi: WebEngineAPI,\n\tstate: GameState,",
"score": 14.00094613859607
},
{
"filename": "src/web/util.ts",
"retrieved_chunk": "export function makeCanvas(width: number, height: number): HTMLCanvasElement {\n\tconst canvas = document.createElement('canvas')\n\tcanvas.width = width\n\tcanvas.height = height\n\treturn canvas\n}",
"score": 12.36759210845839
},
{
"filename": "src/web/index.ts",
"retrieved_chunk": "\t\tconst { width, height } = state.dimensions\n\t\tif (width === 0 || height === 0) return\n\t\tctx.clearRect(0, 0, canvas.width, canvas.height)\n\t\toffscreenCanvas.width = width*16\n\t\toffscreenCanvas.height = height*16\n\t\toffscreenCtx.fillStyle = 'white'\n\t\toffscreenCtx.fillRect(0, 0, width*16, height*16)\n\t\tconst grid = api.getGrid()\n\t\tfor (let i = 0; i < width * height; i++) {\n\t\t\tconst x = i % width",
"score": 11.06205992792433
}
] | typescript | : { api: BaseEngineAPI, state: GameState } { |
import type { AddTextOptions, FullSprigAPI, GameState, SpriteType } from '../api.js'
import { palette } from './palette.js'
export * from './font.js'
export * from './palette.js'
export * from './text.js'
export * from './tune.js'
// Tagged template literal factory go brrr
const _makeTag = <T>(cb: (string: string) => T) => {
return (strings: TemplateStringsArray, ...interps: string[]) => {
if (typeof strings === 'string') {
throw new Error('Tagged template literal must be used like name`text`, instead of name(`text`)')
}
const string = strings.reduce((p, c, i) => p + c + (interps[i] ?? ''), '')
return cb(string)
}
}
export type BaseEngineAPI = Pick<
FullSprigAPI,
| 'setMap'
| 'addText'
| 'clearText'
| 'addSprite'
| 'getGrid'
| 'getTile'
| 'tilesWith'
| 'clearTile'
| 'setSolids'
| 'setPushables'
| 'setBackground'
| 'map'
| 'bitmap'
| 'color'
| 'tune'
| 'getFirst'
| 'getAll'
| 'width'
| 'height'
>
export function baseEngine(): { api: BaseEngineAPI, state: GameState } {
const gameState: GameState = {
legend: [],
texts: [],
dimensions: {
width: 0,
height: 0,
},
sprites: [],
solids: [],
pushable: {},
background: null
}
| class Sprite implements SpriteType { |
_type: string
_x: number
_y: number
dx: number
dy: number
constructor(type: string, x: number, y: number) {
this._type = type
this._x = x
this._y = y
this.dx = 0
this.dy = 0
}
set type(newType) {
const legendDict = Object.fromEntries(gameState.legend)
if (!(newType in legendDict)) throw new Error(`"${newType}" isn\'t in the legend.`)
this.remove()
addSprite(this._x, this._y, newType)
}
get type() {
return this._type
}
set x(newX) {
const dx = newX - this.x
if (_canMoveToPush(this, dx, 0)) this.dx = dx
}
get x() {
return this._x
}
set y(newY) {
const dy = newY - this.y
if (_canMoveToPush(this, 0, dy)) this.dy = dy
}
get y() {
return this._y
}
remove() {
gameState.sprites = gameState.sprites.filter(s => s !== this)
return this
}
}
const _canMoveToPush = (sprite: Sprite, dx: number, dy: number): boolean => {
const { x, y, type } = sprite
const { width, height } = gameState.dimensions
const i = (x+dx)+(y+dy)*width
const inBounds = (x+dx < width && x+dx >= 0 && y+dy < height && y+dy >= 0)
if (!inBounds) return false
const grid = getGrid()
const notSolid = !gameState.solids.includes(type)
const noMovement = dx === 0 && dy === 0
const movingToEmpty = i < grid.length && grid[i]!.length === 0
if (notSolid || noMovement || movingToEmpty) {
sprite._x += dx
sprite._y += dy
return true
}
let canMove = true
const { pushable } = gameState
grid[i]!.forEach(sprite => {
const isSolid = gameState.solids.includes(sprite.type)
const isPushable = (type in pushable) && pushable[type]!.includes(sprite.type)
if (isSolid && !isPushable)
canMove = false
if (isSolid && isPushable) {
canMove = canMove && _canMoveToPush(sprite as Sprite, dx, dy)
}
})
if (canMove) {
sprite._x += dx
sprite._y += dy
}
return canMove
}
const getGrid = (): SpriteType[][] => {
const { width, height } = gameState.dimensions
const grid: SpriteType[][] = new Array(width*height).fill(0).map(_ => [])
gameState.sprites.forEach(s => {
const i = s.x+s.y*width
grid[i]!.push(s)
})
const legendIndex = (t: SpriteType) => gameState.legend.findIndex(l => l[0] == t.type)
for (const tile of grid) tile.sort((a, b) => legendIndex(a) - legendIndex(b))
return grid
}
const _checkBounds = (x: number, y: number): void => {
const { width, height } = gameState.dimensions
if (x >= width || x < 0 || y < 0 || y >= height) throw new Error(`Sprite out of bounds.`)
}
const _checkLegend = (type: string): void => {
if (!(type in Object.fromEntries(gameState.legend)))
throw new Error(`Unknown sprite type: ${type}`)
}
const addSprite = (x: number, y: number, type: string): void => {
if (type === '.') return
_checkBounds(x, y)
_checkLegend(type)
const s = new Sprite(type, x, y)
gameState.sprites.push(s)
}
const _allEqual = <T>(arr: T[]): boolean => arr.every(val => val === arr[0])
const setMap = (string: string): void => {
if (!string) throw new Error('Tried to set empty map.')
if (string.constructor == Object) throw new Error('setMap() takes a string, not a dict.') // https://stackoverflow.com/a/51285298
if (Array.isArray(string)) throw new Error('It looks like you passed an array into setMap(). Did you mean to use something like setMap(levels[level]) instead of setMap(levels)?')
const rows = string.trim().split("\n").map(x => x.trim())
const rowLengths = rows.map(x => x.length)
const isRect = _allEqual(rowLengths)
if (!isRect) throw new Error('Level must be rectangular.')
const w = rows[0]?.length ?? 0
const h = rows.length
gameState.dimensions.width = w
gameState.dimensions.height = h
gameState.sprites = []
const nonSpace = string.split("").filter(x => x !== " " && x !== "\n") // \S regex was too slow
for (let i = 0; i < w*h; i++) {
const type = nonSpace[i]!
if (type === '.') continue
const x = i%w
const y = Math.floor(i/w)
addSprite(x, y, type)
}
}
const clearTile = (x: number, y: number): void => {
gameState.sprites = gameState.sprites.filter(s => s.x !== x || s.y !== y)
}
const addText = (str: string, opts: AddTextOptions = {}): void => {
const CHARS_MAX_X = 21
const padLeft = Math.floor((CHARS_MAX_X - str.length)/2)
if (Array.isArray(opts.color)) throw new Error('addText no longer takes an RGBA color. Please use a Sprig color instead with \"{ color: color`` }\"')
const [, rgba ] = palette.find(([key]) => key === opts.color) ?? palette.find(([key]) => key === 'L')!
gameState.texts.push({
x: opts.x ?? padLeft,
y: opts.y ?? 0,
color: rgba,
content: str
})
}
const clearText = (): void => { gameState.texts = [] }
const getTile = (x: number, y: number): SpriteType[] => {
if (y < 0) return []
if (x < 0) return []
if (y >= gameState.dimensions.height) return []
if (x >= gameState.dimensions.width) return []
return getGrid()[gameState.dimensions.width*y+x] ?? []
}
const _hasDuplicates = <T>(array: T[]): boolean => (new Set(array)).size !== array.length
const tilesWith = (...matchingTypes: string[]): SpriteType[][] => {
const { width, height } = gameState.dimensions
const tiles: SpriteType[][] = []
const grid = getGrid()
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
const tile = grid[width*y+x] || []
const matchIndices = matchingTypes.map(type => {
return tile.map(s => s.type).indexOf(type)
})
if (!_hasDuplicates(matchIndices) && !matchIndices.includes(-1)) tiles.push(tile)
}
}
return tiles
}
const setSolids = (arr: string[]): void => {
if (!Array.isArray(arr)) throw new Error('The sprites passed into setSolids() need to be an array.')
gameState.solids = arr
}
const setPushables = (map: Record<string, string[]>): void => {
for (const key in map) {
if(key.length != 1) {
throw new Error('Your sprite name must be wrapped in [] brackets here.');
}
_checkLegend(key)
}
gameState.pushable = map
}
const api: BaseEngineAPI = {
setMap,
addText,
clearText,
addSprite,
getGrid,
getTile,
tilesWith,
clearTile,
setSolids,
setPushables,
setBackground: (type: string) => { gameState.background = type },
map: _makeTag(text => text),
bitmap: _makeTag(text => text),
color: _makeTag(text => text),
tune: _makeTag(text => text),
getFirst: (type: string): SpriteType | undefined => gameState.sprites.find(t => t.type === type), // **
getAll: (type: string): SpriteType[] => type ? gameState.sprites.filter(t => t.type === type) : gameState.sprites, // **
width: () => gameState.dimensions.width,
height: () => gameState.dimensions.height
}
return { api, state: gameState }
}
| src/base/index.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/api.ts",
"retrieved_chunk": "\tsolids: string[]\n\tpushable: Record<string, string[]>\n\tbackground: string | null\n}\nexport interface PlayTuneRes {\n\tend(): void\n\tisPlaying(): boolean\n}\nexport const tones: Record<string, number> = {\n\t'B0': 31,",
"score": 18.776235778893493
},
{
"filename": "src/api.ts",
"retrieved_chunk": "\tcontent: string\n}\nexport interface GameState {\n\tlegend: [string, string][]\n\ttexts: TextElement[]\n\tdimensions: {\n\t\twidth: number\n\t\theight: number\n\t}\n\tsprites: SpriteType[]",
"score": 18.6949810017683
},
{
"filename": "src/image-data/index.ts",
"retrieved_chunk": "\t\t\t\ts.dx = 0\n\t\t\t\ts.dy = 0\n\t\t\t})\n\t\t},\n\t\trender(): ImageData {\n\t\t\tconst width = () => game.state.dimensions.width\n\t\t\tconst height = () => game.state.dimensions.height\n\t\t\tconst tSize = () => 16\n\t\t\tconst sw = width() * tSize()\n\t\t\tconst sh = height() * tSize()",
"score": 15.586442611447463
},
{
"filename": "src/web/index.ts",
"retrieved_chunk": "\t\tconst { width, height } = state.dimensions\n\t\tif (width === 0 || height === 0) return\n\t\tctx.clearRect(0, 0, canvas.width, canvas.height)\n\t\toffscreenCanvas.width = width*16\n\t\toffscreenCanvas.height = height*16\n\t\toffscreenCtx.fillStyle = 'white'\n\t\toffscreenCtx.fillRect(0, 0, width*16, height*16)\n\t\tconst grid = api.getGrid()\n\t\tfor (let i = 0; i < width * height; i++) {\n\t\t\tconst x = i % width",
"score": 15.073470930865824
},
{
"filename": "src/web/index.ts",
"retrieved_chunk": "\t\t\tconst y = Math.floor(i/width)\n\t\t\tconst sprites = grid[i]!\n\t\t\tif (state.background) {\n\t\t\t\tconst imgData = _bitmaps[state.background]!\n\t\t\t\toffscreenCtx.drawImage(imgData, x*16, y*16)\n\t\t\t}\n\t\t\tsprites\n\t\t\t\t.sort((a, b) => _zOrder.indexOf(b.type) - _zOrder.indexOf(a.type))\n\t\t\t\t.forEach((sprite) => {\n\t\t\t\t\tconst imgData = _bitmaps[sprite.type]!",
"score": 10.24199887153003
}
] | typescript | class Sprite implements SpriteType { |
import type { AddTextOptions, FullSprigAPI, GameState, SpriteType } from '../api.js'
import { palette } from './palette.js'
export * from './font.js'
export * from './palette.js'
export * from './text.js'
export * from './tune.js'
// Tagged template literal factory go brrr
const _makeTag = <T>(cb: (string: string) => T) => {
return (strings: TemplateStringsArray, ...interps: string[]) => {
if (typeof strings === 'string') {
throw new Error('Tagged template literal must be used like name`text`, instead of name(`text`)')
}
const string = strings.reduce((p, c, i) => p + c + (interps[i] ?? ''), '')
return cb(string)
}
}
export type BaseEngineAPI = Pick<
FullSprigAPI,
| 'setMap'
| 'addText'
| 'clearText'
| 'addSprite'
| 'getGrid'
| 'getTile'
| 'tilesWith'
| 'clearTile'
| 'setSolids'
| 'setPushables'
| 'setBackground'
| 'map'
| 'bitmap'
| 'color'
| 'tune'
| 'getFirst'
| 'getAll'
| 'width'
| 'height'
>
export function baseEngine(): { api: BaseEngineAPI, state: GameState } {
const gameState: GameState = {
legend: [],
texts: [],
dimensions: {
width: 0,
height: 0,
},
sprites: [],
solids: [],
pushable: {},
background: null
}
class Sprite implements SpriteType {
_type: string
_x: number
_y: number
dx: number
dy: number
constructor(type: string, x: number, y: number) {
this._type = type
this._x = x
this._y = y
this.dx = 0
this.dy = 0
}
set type(newType) {
const legendDict = Object.fromEntries(gameState.legend)
if (!(newType in legendDict)) throw new Error(`"${newType}" isn\'t in the legend.`)
this.remove()
addSprite(this._x, this._y, newType)
}
get type() {
return this._type
}
set x(newX) {
const dx = newX - this.x
if (_canMoveToPush(this, dx, 0)) this.dx = dx
}
get x() {
return this._x
}
set y(newY) {
const dy = newY - this.y
if (_canMoveToPush(this, 0, dy)) this.dy = dy
}
get y() {
return this._y
}
remove() {
gameState.sprites = gameState.sprites.filter(s => s !== this)
return this
}
}
const _canMoveToPush = (sprite: Sprite, dx: number, dy: number): boolean => {
const { x, y, type } = sprite
const { width, height } = gameState.dimensions
const i = (x+dx)+(y+dy)*width
const inBounds = (x+dx < width && x+dx >= 0 && y+dy < height && y+dy >= 0)
if (!inBounds) return false
const grid = getGrid()
const notSolid = !gameState.solids.includes(type)
const noMovement = dx === 0 && dy === 0
const movingToEmpty = i < grid.length && grid[i]!.length === 0
if (notSolid || noMovement || movingToEmpty) {
sprite._x += dx
sprite._y += dy
return true
}
let canMove = true
const { pushable } = gameState
grid[i]!.forEach(sprite => {
const isSolid = gameState.solids.includes(sprite.type)
const isPushable = (type in pushable) && pushable[type]!.includes(sprite.type)
if (isSolid && !isPushable)
canMove = false
if (isSolid && isPushable) {
canMove = canMove && _canMoveToPush(sprite as Sprite, dx, dy)
}
})
if (canMove) {
sprite._x += dx
sprite._y += dy
}
return canMove
}
const getGrid = (): SpriteType[][] => {
const { width, height } = gameState.dimensions
const grid: SpriteType[][] = new Array(width*height).fill(0).map(_ => [])
gameState.sprites.forEach(s => {
const i = s.x+s.y*width
grid[i]!.push(s)
})
const legendIndex = (t: SpriteType) => gameState.legend.findIndex(l => l[0] == t.type)
for (const tile of grid) tile.sort((a, b) => legendIndex(a) - legendIndex(b))
return grid
}
const _checkBounds = (x: number, y: number): void => {
const { width, height } = gameState.dimensions
if (x >= width || x < 0 || y < 0 || y >= height) throw new Error(`Sprite out of bounds.`)
}
const _checkLegend = (type: string): void => {
if (!(type in Object.fromEntries(gameState.legend)))
throw new Error(`Unknown sprite type: ${type}`)
}
const addSprite = (x: number, y: number, type: string): void => {
if (type === '.') return
_checkBounds(x, y)
_checkLegend(type)
const s = new Sprite(type, x, y)
gameState.sprites.push(s)
}
const _allEqual = <T>(arr: T[]): boolean => arr.every(val => val === arr[0])
const setMap = (string: string): void => {
if (!string) throw new Error('Tried to set empty map.')
if (string.constructor == Object) throw new Error('setMap() takes a string, not a dict.') // https://stackoverflow.com/a/51285298
if (Array.isArray(string)) throw new Error('It looks like you passed an array into setMap(). Did you mean to use something like setMap(levels[level]) instead of setMap(levels)?')
const rows = string.trim().split("\n").map(x => x.trim())
const rowLengths = rows.map(x => x.length)
const isRect = _allEqual(rowLengths)
if (!isRect) throw new Error('Level must be rectangular.')
const w = rows[0]?.length ?? 0
const h = rows.length
gameState.dimensions.width = w
gameState.dimensions.height = h
gameState.sprites = []
const nonSpace = string.split("").filter(x => x !== " " && x !== "\n") // \S regex was too slow
for (let i = 0; i < w*h; i++) {
const type = nonSpace[i]!
if (type === '.') continue
const x = i%w
const y = Math.floor(i/w)
addSprite(x, y, type)
}
}
const clearTile = (x: number, y: number): void => {
gameState.sprites = gameState.sprites.filter(s => s.x !== x || s.y !== y)
}
const addText = (str: string, opts: AddTextOptions = {}): void => {
const CHARS_MAX_X = 21
const padLeft = Math.floor((CHARS_MAX_X - str.length)/2)
if (Array.isArray(opts.color)) throw new Error('addText no longer takes an RGBA color. Please use a Sprig color instead with \"{ color: color`` }\"')
const [, rgba ] = palette.find(([key]) => key === opts.color) ?? palette.find(([key]) => key === 'L')!
gameState.texts.push({
x: opts.x ?? padLeft,
y: | opts.y ?? 0,
color: rgba,
content: str
})
} |
const clearText = (): void => { gameState.texts = [] }
const getTile = (x: number, y: number): SpriteType[] => {
if (y < 0) return []
if (x < 0) return []
if (y >= gameState.dimensions.height) return []
if (x >= gameState.dimensions.width) return []
return getGrid()[gameState.dimensions.width*y+x] ?? []
}
const _hasDuplicates = <T>(array: T[]): boolean => (new Set(array)).size !== array.length
const tilesWith = (...matchingTypes: string[]): SpriteType[][] => {
const { width, height } = gameState.dimensions
const tiles: SpriteType[][] = []
const grid = getGrid()
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
const tile = grid[width*y+x] || []
const matchIndices = matchingTypes.map(type => {
return tile.map(s => s.type).indexOf(type)
})
if (!_hasDuplicates(matchIndices) && !matchIndices.includes(-1)) tiles.push(tile)
}
}
return tiles
}
const setSolids = (arr: string[]): void => {
if (!Array.isArray(arr)) throw new Error('The sprites passed into setSolids() need to be an array.')
gameState.solids = arr
}
const setPushables = (map: Record<string, string[]>): void => {
for (const key in map) {
if(key.length != 1) {
throw new Error('Your sprite name must be wrapped in [] brackets here.');
}
_checkLegend(key)
}
gameState.pushable = map
}
const api: BaseEngineAPI = {
setMap,
addText,
clearText,
addSprite,
getGrid,
getTile,
tilesWith,
clearTile,
setSolids,
setPushables,
setBackground: (type: string) => { gameState.background = type },
map: _makeTag(text => text),
bitmap: _makeTag(text => text),
color: _makeTag(text => text),
tune: _makeTag(text => text),
getFirst: (type: string): SpriteType | undefined => gameState.sprites.find(t => t.type === type), // **
getAll: (type: string): SpriteType[] => type ? gameState.sprites.filter(t => t.type === type) : gameState.sprites, // **
width: () => gameState.dimensions.width,
height: () => gameState.dimensions.height
}
return { api, state: gameState }
}
| src/base/index.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/base/text.ts",
"retrieved_chunk": "\t\tfor (const line of content.split('\\n')) {\n\t\t\tlet x = sx\n\t\t\tfor (const char of line.split('')) {\n\t\t\t\tif (\" !\\\"#%&\\'()*+,./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\\\^_-`abcdefghijklmnopqrstuvwxyz|~¦§¨©¬®¯°±´¶·¸ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ÙÚÛÜÝÞßàáâãäåæçèéêëìíîïñòóôõö÷ùúûüýþÿĀāĂ㥹ĆćĊċČčĎĐđĒēĖėĘęĚěĞğĠġĦħĪīĮįİıŃńŇňŌōŒœŞşŨũŪūŮůŲųŴŵŶŷŸǍǎǏǐǑǒǓǔˆˇ˘˙˚˛˜˝ẀẁẂẃẄẅỲỳ†‡•…‰⁄™∂∅∏∑−√∞∫≈≠≤≥◊\".indexOf(char) === -1)\n\t\t\t\t\tthrow new Error(`Character ${char} is not in the font. It will be rendered incorrectly.`)\n\t\t\t\tif (x <= CHARS_MAX_X && y < CHARS_MAX_Y)\n\t\t\t\t\tgrid[y]![x++] = {color: color, char}\n\t\t\t}\n\t\t\ty++\n\t\t}",
"score": 46.905644090137294
},
{
"filename": "src/api.ts",
"retrieved_chunk": "export type Tune = [number, ...(InstrumentType | number | string)[]][]\nexport interface FullSprigAPI {\n\tmap(template: TemplateStringsArray, ...params: string[]): string\n\tbitmap(template: TemplateStringsArray, ...params: string[]): string\n\tcolor(template: TemplateStringsArray, ...params: string[]): string\n\ttune(template: TemplateStringsArray, ...params: string[]): string\n\tsetMap(string: string): void\n\taddText(str: string, opts?: AddTextOptions): void\n\tclearText(): void\n\taddSprite(x: number, y: number, type: string): void",
"score": 46.611602492850835
},
{
"filename": "src/base/text.ts",
"retrieved_chunk": "import type { Rgba, TextElement } from '../api.js'\nexport function composeText(texts: TextElement[]): { char: string, color: Rgba }[][] {\n\tconst emptyCell = () => ({ char: ' ', color: [0, 0, 0, 0] as Rgba })\n\tconst range = <T>(length: number, fn: () => T): T[] => Array.from({ length }, fn)\n\tconst gridFromSize = (w: number, h: number) => range(h, () => range(w, emptyCell))\n\tconst CHARS_MAX_X = 20\n\tconst CHARS_MAX_Y = 16\n\tconst grid = gridFromSize(CHARS_MAX_X, CHARS_MAX_Y)\n\tfor (const { x: sx, y: sy, content, color } of texts) {\n\t\tlet y = sy",
"score": 43.24498890658981
},
{
"filename": "src/image-data/bitmap.ts",
"retrieved_chunk": " const colors = Object.fromEntries(palette)\n const nonSpace = text.split('').filter(x => x !== ' ' && x !== '\\n') // \\S regex led to massive perf problems\n for (let i = 0; i < width*height; i++) {\n const type = nonSpace[i] || \".\"\n if (!(type in colors)) {\n const err = `in sprite string: no known color for char \"${type}\"`\n console.error(err + '\\n' + text)\n throw new Error(err + ' (invalid sprite in console)')\n }\n const [ r, g, b, a ] = colors[type] ?? colors['.']!",
"score": 38.66393693472755
},
{
"filename": "src/web/text.ts",
"retrieved_chunk": "\t\t\tconst cc = char.charCodeAt(0)\n\t\t\tlet y = Number(i)*8\n\t\t\tfor (const bits of font.slice(cc*8, (1+cc)*8)) {\n\t\t\t\t\tfor (let x = 0; x < 8; x++) {\n\t\t\t\t\t\tconst val = (bits>>(7-x)) & 1\n\t\t\t\t\t\timg.data[(y*img.width + xt + x)*4 + 0] = val*color[0]\n\t\t\t\t\t\timg.data[(y*img.width + xt + x)*4 + 1] = val*color[1]\n\t\t\t\t\t\timg.data[(y*img.width + xt + x)*4 + 2] = val*color[2]\n\t\t\t\t\t\timg.data[(y*img.width + xt + x)*4 + 3] = val*255\n\t\t\t\t\t}",
"score": 38.15372910797296
}
] | typescript | opts.y ?? 0,
color: rgba,
content: str
})
} |
import { type InputKey, type PlayTuneRes, VALID_INPUTS, type FullSprigAPI, type GameState } from '../api.js'
import { type BaseEngineAPI, baseEngine, textToTune } from '../base/index.js'
import { bitmapTextToImageData } from '../image-data/index.js'
import { getTextImg } from './text.js'
import { playTune } from './tune.js'
import { makeCanvas } from './util.js'
export * from './text.js'
export * from './tune.js'
export type WebEngineAPI = BaseEngineAPI & Pick<
FullSprigAPI,
| 'setLegend'
| 'onInput'
| 'afterInput'
| 'playTune'
> & {
getState(): GameState // For weird backwards-compatibility reasons, not part of API
}
export function webEngine(canvas: HTMLCanvasElement): {
api: WebEngineAPI,
state: GameState,
cleanup(): void
} {
const { api, state } = baseEngine()
const ctx = canvas.getContext('2d')!
const offscreenCanvas = makeCanvas(1, 1)
const offscreenCtx = offscreenCanvas.getContext('2d')!
const _bitmaps: Record<string, CanvasImageSource> = {}
let _zOrder: string[] = []
ctx.imageSmoothingEnabled = false
const _gameloop = (): void => {
const { width, height } = state.dimensions
if (width === 0 || height === 0) return
ctx.clearRect(0, 0, canvas.width, canvas.height)
offscreenCanvas.width = width*16
offscreenCanvas.height = height*16
offscreenCtx.fillStyle = 'white'
offscreenCtx.fillRect(0, 0, width*16, height*16)
const grid = api.getGrid()
for (let i = 0; i < width * height; i++) {
const x = i % width
const y = Math.floor(i/width)
const sprites = grid[i]!
if (state.background) {
const imgData = _bitmaps[state.background]!
offscreenCtx.drawImage(imgData, x*16, y*16)
}
sprites
.sort((a, b) => _zOrder.indexOf(b.type) - _zOrder.indexOf(a.type))
.forEach((sprite) => {
const imgData = _bitmaps[sprite.type]!
offscreenCtx.drawImage(imgData, x*16, y*16)
})
}
const scale = Math.min(canvas.width/(width*16), canvas.height/(height*16))
const actualWidth = offscreenCanvas.width*scale
const actualHeight = offscreenCanvas.height*scale
ctx.drawImage(
offscreenCanvas,
(canvas.width-actualWidth)/2,
(canvas.height-actualHeight)/2,
actualWidth,
actualHeight
)
const textCanvas = getTextImg(state.texts)
ctx.drawImage(
textCanvas,
0,
0,
canvas.width,
canvas.height
)
animationId = window.requestAnimationFrame(_gameloop)
}
let animationId = window.requestAnimationFrame(_gameloop)
const setLegend = (...bitmaps: [string, string][]): void => {
if (bitmaps.length == 0) throw new Error('There needs to be at least one sprite in the legend.')
if (!Array.isArray(bitmaps[0])) throw new Error('The sprites passed into setLegend each need to be in square brackets, like setLegend([player, bitmap`...`]).')
bitmaps.forEach(([ key ]) => {
if (key === '.') throw new Error(`Can't reassign "." bitmap`)
if (key.length !== 1) throw new Error(`Bitmaps must have one character names`)
})
state.legend = bitmaps
_zOrder = bitmaps.map(x => x[0])
for (let i = 0; i < bitmaps.length; i++) {
const [ key, value ] = bitmaps[i]!
const imgData = bitmapTextToImageData(value)
const littleCanvas = makeCanvas(16, 16)
littleCanvas.getContext('2d')!.putImageData(imgData, 0, 0)
_bitmaps[key] = littleCanvas
}
}
let tileInputs: Record<InputKey, (() => void)[]> = {
w: [],
s: [],
a: [],
d: [],
i: [],
j: [],
k: [],
l: []
}
const afterInputs: (() => void)[] = []
const keydown = (e: KeyboardEvent) => {
const key = e.key
if (!VALID_INPUTS.includes(key as any)) return
for (const validKey of VALID_INPUTS)
if (key === validKey) tileInputs[key].forEach(fn => fn())
afterInputs.forEach(f => f())
state.sprites.forEach((s: any) => {
s.dx = 0
s.dy = 0
})
e.preventDefault()
}
canvas.addEventListener('keydown', keydown)
const onInput = (key: InputKey, fn: () => void): void => {
if (!VALID_INPUTS.includes(key))
throw new Error(`Unknown input key, "${key}": expected one of ${VALID_INPUTS.join(', ')}`)
tileInputs[key].push(fn)
}
const afterInput = (fn: () => void): void => { afterInputs.push(fn) }
const tunes: PlayTuneRes[] = []
return {
api: {
...api,
setLegend,
onInput,
afterInput,
getState: () => state,
playTune: (text: string, n: number) => {
const tune = textToTune(text)
const playTuneRes = playTune(tune, n)
tunes.push(playTuneRes)
return playTuneRes
}
},
state,
cleanup: () => {
ctx.clearRect(0, 0, canvas.width, canvas.height)
window.cancelAnimationFrame(animationId)
canvas.removeEventListener('keydown', keydown)
| tunes.forEach(tune => tune.end())
} |
}
}
| src/web/index.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/web/util.ts",
"retrieved_chunk": "export function makeCanvas(width: number, height: number): HTMLCanvasElement {\n\tconst canvas = document.createElement('canvas')\n\tcanvas.width = width\n\tcanvas.height = height\n\treturn canvas\n}",
"score": 31.725516614952262
},
{
"filename": "src/web/text.ts",
"retrieved_chunk": "\t\t\t\t\ty++\n\t\t\t}\n\t\t\txt += 8\n\t\t}\n\t}\n\tconst canvas = makeCanvas(160, 128)\n\tcanvas.getContext('2d')!.putImageData(img, 0, 0)\n\treturn canvas\n}",
"score": 26.88325645888077
},
{
"filename": "src/base/index.ts",
"retrieved_chunk": "\t| 'bitmap'\n\t| 'color'\n\t| 'tune'\n\t| 'getFirst'\n\t| 'getAll'\n\t| 'width'\n\t| 'height'\n>\nexport function baseEngine(): { api: BaseEngineAPI, state: GameState } {\n\tconst gameState: GameState = {",
"score": 14.318809094236585
},
{
"filename": "src/base/index.ts",
"retrieved_chunk": "\t\ttune: _makeTag(text => text),\n\t\tgetFirst: (type: string): SpriteType | undefined => gameState.sprites.find(t => t.type === type), // **\n\t\tgetAll: (type: string): SpriteType[] => type ? gameState.sprites.filter(t => t.type === type) : gameState.sprites, // **\n\t\twidth: () => gameState.dimensions.width,\n\t\theight: () => gameState.dimensions.height\n\t}\n\treturn { api, state: gameState }\n}",
"score": 13.450381740052055
},
{
"filename": "src/image-data/index.ts",
"retrieved_chunk": "\t\t\t\ts.dx = 0\n\t\t\t\ts.dy = 0\n\t\t\t})\n\t\t},\n\t\trender(): ImageData {\n\t\t\tconst width = () => game.state.dimensions.width\n\t\t\tconst height = () => game.state.dimensions.height\n\t\t\tconst tSize = () => 16\n\t\t\tconst sw = width() * tSize()\n\t\t\tconst sh = height() * tSize()",
"score": 13.013878348438038
}
] | typescript | tunes.forEach(tune => tune.end())
} |
import { type InputKey, type PlayTuneRes, VALID_INPUTS, type FullSprigAPI, type GameState } from '../api.js'
import { type BaseEngineAPI, baseEngine, textToTune } from '../base/index.js'
import { bitmapTextToImageData } from '../image-data/index.js'
import { getTextImg } from './text.js'
import { playTune } from './tune.js'
import { makeCanvas } from './util.js'
export * from './text.js'
export * from './tune.js'
export type WebEngineAPI = BaseEngineAPI & Pick<
FullSprigAPI,
| 'setLegend'
| 'onInput'
| 'afterInput'
| 'playTune'
> & {
getState(): GameState // For weird backwards-compatibility reasons, not part of API
}
export function webEngine(canvas: HTMLCanvasElement): {
api: WebEngineAPI,
state: GameState,
cleanup(): void
} {
const { api, state } = baseEngine()
const ctx = canvas.getContext('2d')!
const offscreenCanvas = makeCanvas(1, 1)
const offscreenCtx = offscreenCanvas.getContext('2d')!
const _bitmaps: Record<string, CanvasImageSource> = {}
let _zOrder: string[] = []
ctx.imageSmoothingEnabled = false
const _gameloop = (): void => {
const { width, height } = state.dimensions
if (width === 0 || height === 0) return
ctx.clearRect(0, 0, canvas.width, canvas.height)
offscreenCanvas.width = width*16
offscreenCanvas.height = height*16
offscreenCtx.fillStyle = 'white'
offscreenCtx.fillRect(0, 0, width*16, height*16)
const grid = api.getGrid()
for (let i = 0; i < width * height; i++) {
const x = i % width
const y = Math.floor(i/width)
const sprites = grid[i]!
if (state.background) {
const imgData = _bitmaps[state.background]!
offscreenCtx.drawImage(imgData, x*16, y*16)
}
sprites
.sort((a, b) => _zOrder.indexOf(b.type) - _zOrder.indexOf(a.type))
.forEach((sprite) => {
const imgData = _bitmaps[sprite.type]!
offscreenCtx.drawImage(imgData, x*16, y*16)
})
}
const scale = Math.min(canvas.width/(width*16), canvas.height/(height*16))
const actualWidth = offscreenCanvas.width*scale
const actualHeight = offscreenCanvas.height*scale
ctx.drawImage(
offscreenCanvas,
(canvas.width-actualWidth)/2,
(canvas.height-actualHeight)/2,
actualWidth,
actualHeight
)
const textCanvas = getTextImg(state.texts)
ctx.drawImage(
textCanvas,
0,
0,
canvas.width,
canvas.height
)
animationId = window.requestAnimationFrame(_gameloop)
}
let animationId = window.requestAnimationFrame(_gameloop)
const setLegend = (...bitmaps: [string, string][]): void => {
if (bitmaps.length == 0) throw new Error('There needs to be at least one sprite in the legend.')
if (!Array.isArray(bitmaps[0])) throw new Error('The sprites passed into setLegend each need to be in square brackets, like setLegend([player, bitmap`...`]).')
bitmaps.forEach(([ key ]) => {
if (key === '.') throw new Error(`Can't reassign "." bitmap`)
if (key.length !== 1) throw new Error(`Bitmaps must have one character names`)
})
state.legend = bitmaps
_zOrder = bitmaps.map(x => x[0])
for (let i = 0; i < bitmaps.length; i++) {
const [ key, value ] = bitmaps[i]!
const imgData = bitmapTextToImageData(value)
const littleCanvas = makeCanvas(16, 16)
littleCanvas.getContext('2d')!.putImageData(imgData, 0, 0)
_bitmaps[key] = littleCanvas
}
}
let tileInputs: Record<InputKey, (() => void)[]> = {
w: [],
s: [],
a: [],
d: [],
i: [],
j: [],
k: [],
l: []
}
const afterInputs: (() => void)[] = []
const keydown = (e: KeyboardEvent) => {
const key = e.key
if (!VALID_INPUTS.includes(key as any)) return
for (const validKey of VALID_INPUTS)
if (key === validKey) tileInputs[key].forEach(fn => fn())
afterInputs.forEach(f => f())
state.sprites.forEach((s: any) => {
s.dx = 0
s.dy = 0
})
e.preventDefault()
}
canvas.addEventListener('keydown', keydown)
const onInput = (key: InputKey, fn: () => void): void => {
if (!VALID_INPUTS.includes(key))
| throw new Error(`Unknown input key, "${key}": expected one of ${VALID_INPUTS.join(', ')}`)
tileInputs[key].push(fn)
} |
const afterInput = (fn: () => void): void => { afterInputs.push(fn) }
const tunes: PlayTuneRes[] = []
return {
api: {
...api,
setLegend,
onInput,
afterInput,
getState: () => state,
playTune: (text: string, n: number) => {
const tune = textToTune(text)
const playTuneRes = playTune(tune, n)
tunes.push(playTuneRes)
return playTuneRes
}
},
state,
cleanup: () => {
ctx.clearRect(0, 0, canvas.width, canvas.height)
window.cancelAnimationFrame(animationId)
canvas.removeEventListener('keydown', keydown)
tunes.forEach(tune => tune.end())
}
}
}
| src/web/index.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/image-data/index.ts",
"retrieved_chunk": "\t}\n\tconst api = {\n\t\t...game.api,\n\t\tonInput: (key: InputKey, fn: () => void) => keyHandlers[key].push(fn),\n\t\tafterInput: (fn: () => void) => afterInputs.push(fn),\n\t\tsetLegend: (...bitmaps: [string, string][]) => {\n\t\t\tgame.state.legend = bitmaps\n\t\t\tlegendImages = {}\n\t\t\tfor (const [ id, desc ] of bitmaps)\n\t\t\t\tlegendImages[id] = bitmapTextToImageData(desc)",
"score": 49.008706247421856
},
{
"filename": "src/image-data/index.ts",
"retrieved_chunk": "\t\t\treturn timer\n\t\t},\n\t\tplayTune: () => ({ end() {}, isPlaying() { return false } })\n\t}\n\treturn {\n\t\tapi,\n\t\tbutton(key: InputKey): void {\n\t\t\tfor (const fn of keyHandlers[key]) fn()\n\t\t\tfor (const fn of afterInputs) fn()\n\t\t\tgame.state.sprites.forEach((s: any) => {",
"score": 45.26180863911229
},
{
"filename": "src/api.ts",
"retrieved_chunk": "\theight(): number\n\tsetLegend(...bitmaps: [string, string][]): void\n\tonInput(key: InputKey, fn: () => void): void \n\tafterInput(fn: () => void): void\n\tplayTune(text: string, n?: number): PlayTuneRes\n\tsetTimeout(fn: TimerHandler, ms: number): number\n\tsetInterval(fn: TimerHandler, ms: number): number\n\tclearTimeout(id: number): void\n\tclearInterval(id: number): void\n}",
"score": 38.00960745788661
},
{
"filename": "src/base/index.ts",
"retrieved_chunk": "\t\treturn tiles\n\t}\n\tconst setSolids = (arr: string[]): void => { \n\t\tif (!Array.isArray(arr)) throw new Error('The sprites passed into setSolids() need to be an array.')\n\t\tgameState.solids = arr \n\t}\n\tconst setPushables = (map: Record<string, string[]>): void => { \n\t\tfor (const key in map) {\n\t\t\tif(key.length != 1) {\n\t\t\t\tthrow new Error('Your sprite name must be wrapped in [] brackets here.');",
"score": 32.3894023731152
},
{
"filename": "src/base/index.ts",
"retrieved_chunk": "\t\tconst [, rgba ] = palette.find(([key]) => key === opts.color) ?? palette.find(([key]) => key === 'L')!\n\t\tgameState.texts.push({\n\t\t\tx: opts.x ?? padLeft,\n\t\t\ty: opts.y ?? 0,\n\t\t\tcolor: rgba,\n\t\t\tcontent: str\n\t\t})\n\t}\n\tconst clearText = (): void => { gameState.texts = [] }\n\tconst getTile = (x: number, y: number): SpriteType[] => {",
"score": 31.671837613604772
}
] | typescript | throw new Error(`Unknown input key, "${key}": expected one of ${VALID_INPUTS.join(', ')}`)
tileInputs[key].push(fn)
} |
/*
song form
[
[duration, instrument, pitch, duration, ...],
]
Syntax:
500: 64.4~500 + c5~1000
[500, 'sine', 64.4, 500, 'sine', 'c5', 1000]
Comma between each tune element. Whitespace ignored.
*/
import { type Tune, instrumentKey, InstrumentType, reverseInstrumentKey } from '../api.js'
export const textToTune = (text: string): Tune => {
const elements = text.replace(/\s/g, '').split(',')
const tune = []
for (const element of elements) {
if (!element) continue
const [durationRaw, notesRaw] = element.split(':')
const duration = Math.round(parseInt(durationRaw ?? '0', 10))
const notes = (notesRaw || '').split('+').map((noteRaw) => {
if (!noteRaw) return []
const [, pitchRaw, instrumentRaw, durationRaw] = noteRaw.match(/^(.+)([~\-^\/])(.+)$/)!
return [
instrumentKey[instrumentRaw!] ?? 'sine',
isNaN(parseInt(pitchRaw ?? '', 10)) ? pitchRaw! : parseInt(pitchRaw!, 10),
parseInt(durationRaw ?? '0', 10)
]
})
tune.push([duration, ...notes].flat())
}
return tune as Tune
}
export const tuneToText = (tune: Tune): string => {
const groupNotes = (notes: (number | string)[]) => {
const groups = []
for (let i = 0; i < notes.length; i++) {
if (i % 3 === 0) {
groups.push([notes[i]!])
} else {
groups[groups.length-1]!.push(notes[i]!)
}
}
return groups
}
const notesToString = ([duration, ...notes]: Tune[number]) => (
notes.length === 0
? duration
: `${duration}: ${groupNotes(notes).map(notesToStringHelper).join(' + ')}`
)
const notesToStringHelper = ([instrument, duration, note]: (number | string)[]) => (
`${duration}${ | reverseInstrumentKey[instrument as InstrumentType]}${note}`
)
return tune.map(notesToString).join(',\n')
} | src/base/tune.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/web/tune.ts",
"retrieved_chunk": "\t\t\tconst duration = noteSet[j+2] as number\n\t\t\tconst frequency = typeof note === 'string' \n\t\t\t\t? tones[note.toUpperCase()]\n\t\t\t\t: 2**((note-69)/12)*440\n\t\t\tif (instruments.includes(instrument) && frequency !== undefined) playFrequency(frequency, duration, instrument, ctx, dest)\n\t\t}\n\t\tawait sleep(sleepTime)\n\t}\n}\nlet audioCtx: AudioContext | null = null",
"score": 49.96241468711131
},
{
"filename": "src/web/tune.ts",
"retrieved_chunk": "const sleep = async (duration: number) => new Promise(resolve => setTimeout(resolve, duration))\nexport async function playTuneHelper(tune: Tune, number: number, playingRef: { playing: boolean }, ctx: AudioContext, dest: AudioNode) {\n\tfor (let i = 0; i < tune.length*number; i++) {\n\t\tconst index = i%tune.length\n\t\tif (!playingRef.playing) break\n\t\tconst noteSet = tune[index]!\n\t\tconst sleepTime = noteSet[0]\n\t\tfor (let j = 1; j < noteSet.length; j += 3) {\n\t\t\tconst instrument = noteSet[j] as InstrumentType\n\t\t\tconst note = noteSet[j+1]!",
"score": 45.06148962360298
},
{
"filename": "src/web/tune.ts",
"retrieved_chunk": "import { type InstrumentType, type PlayTuneRes, type Tune, instruments, tones } from '../api.js'\nexport function playFrequency(frequency: number, duration: number, instrument: InstrumentType, ctx: AudioContext, dest: AudioNode) {\n\tconst osc = ctx.createOscillator()\n\tconst rampGain = ctx.createGain()\n\tosc.connect(rampGain)\n\trampGain.connect(dest)\n\tosc.frequency.value = frequency\n\tosc.type = instrument ?? 'sine'\n\tosc.start()\n\tconst endTime = ctx.currentTime + duration*2/1000",
"score": 34.74546714235583
},
{
"filename": "src/base/palette.ts",
"retrieved_chunk": "\tconst [ r, g, b, a ] = hex.match(/\\w\\w/g)?.map((x) => parseInt(x, 16)) ?? []\n\treturn [ r!, g!, b!, a ?? 255 ]\n}\nexport const rgbaToHex = (rgba: Rgba): string => {\n\treturn '#' + rgba.map(n => n.toString(16).padStart(2, '0')).join('')\n}",
"score": 23.494943106585467
},
{
"filename": "src/api.ts",
"retrieved_chunk": "export type InstrumentType = typeof instruments[number]\nexport const instrumentKey: Record<string, InstrumentType> = {\n\t'~': 'sine',\n\t'-': 'square',\n\t'^': 'triangle',\n\t'/': 'sawtooth'\n}\nexport const reverseInstrumentKey = Object.fromEntries(\n\tObject.entries(instrumentKey).map(([ k, v ]) => [ v, k ])\n) as Record<InstrumentType, string>",
"score": 23.156040094548196
}
] | typescript | reverseInstrumentKey[instrument as InstrumentType]}${note}`
)
return tune.map(notesToString).join(',\n')
} |
|
import { type InstrumentType, type PlayTuneRes, type Tune, instruments, tones } from '../api.js'
export function playFrequency(frequency: number, duration: number, instrument: InstrumentType, ctx: AudioContext, dest: AudioNode) {
const osc = ctx.createOscillator()
const rampGain = ctx.createGain()
osc.connect(rampGain)
rampGain.connect(dest)
osc.frequency.value = frequency
osc.type = instrument ?? 'sine'
osc.start()
const endTime = ctx.currentTime + duration*2/1000
osc.stop(endTime)
rampGain.gain.setValueAtTime(0, ctx.currentTime)
rampGain.gain.linearRampToValueAtTime(.2, ctx.currentTime + duration/5/1000)
rampGain.gain.exponentialRampToValueAtTime(0.00001, ctx.currentTime + duration/1000)
rampGain.gain.linearRampToValueAtTime(0, ctx.currentTime + duration*2/1000) // does this ramp from the last ramp
osc.onended = () => {
osc.disconnect()
rampGain.disconnect()
}
}
const sleep = async (duration: number) => new Promise(resolve => setTimeout(resolve, duration))
export async function playTuneHelper(tune: Tune, number: number, playingRef: { playing: boolean }, ctx: AudioContext, dest: AudioNode) {
for (let i = 0; i < tune.length*number; i++) {
const index = i%tune.length
if (!playingRef.playing) break
const noteSet = tune[index]!
const sleepTime = noteSet[0]
for (let j = 1; j < noteSet.length; j += 3) {
const instrument = noteSet[j] as InstrumentType
const note = noteSet[j+1]!
const duration = noteSet[j+2] as number
const frequency = typeof note === 'string'
? tones[note.toUpperCase()]
: 2**((note-69)/12)*440
if (instruments.includes(instrument) && frequency !== undefined) playFrequency(frequency, duration, instrument, ctx, dest)
}
await sleep(sleepTime)
}
}
let audioCtx: AudioContext | null = null
export function playTune(tune: Tune, number = 1 | ): PlayTuneRes { |
const playingRef = { playing: true }
if (audioCtx === null) audioCtx = new AudioContext()
playTuneHelper(tune, number, playingRef, audioCtx, audioCtx.destination)
return {
end() { playingRef.playing = false },
isPlaying() { return playingRef.playing }
}
} | src/web/tune.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/base/tune.ts",
"retrieved_chunk": "\t\t}\n\t\treturn groups\n\t}\n\tconst notesToString = ([duration, ...notes]: Tune[number]) => (\n\t\tnotes.length === 0 \n\t\t\t? duration \n\t\t\t: `${duration}: ${groupNotes(notes).map(notesToStringHelper).join(' + ')}`\n\t)\n\tconst notesToStringHelper = ([instrument, duration, note]: (number | string)[]) => (\n\t\t`${duration}${reverseInstrumentKey[instrument as InstrumentType]}${note}`",
"score": 38.82436536656625
},
{
"filename": "src/api.ts",
"retrieved_chunk": "\tsolids: string[]\n\tpushable: Record<string, string[]>\n\tbackground: string | null\n}\nexport interface PlayTuneRes {\n\tend(): void\n\tisPlaying(): boolean\n}\nexport const tones: Record<string, number> = {\n\t'B0': 31,",
"score": 23.74609199817165
},
{
"filename": "src/base/tune.ts",
"retrieved_chunk": "/*\nsong form\n[\n\t[duration, instrument, pitch, duration, ...],\n]\nSyntax:\n500: 64.4~500 + c5~1000\n[500, 'sine', 64.4, 500, 'sine', 'c5', 1000]\nComma between each tune element. Whitespace ignored.\n*/",
"score": 17.306923915769268
},
{
"filename": "src/base/tune.ts",
"retrieved_chunk": "}\nexport const tuneToText = (tune: Tune): string => {\n\tconst groupNotes = (notes: (number | string)[]) => {\n\t\tconst groups = []\n\t\tfor (let i = 0; i < notes.length; i++) {\n\t\t\tif (i % 3 === 0) {\n\t\t\t\tgroups.push([notes[i]!])\n\t\t\t} else {\n\t\t\t\tgroups[groups.length-1]!.push(notes[i]!)\n\t\t\t}",
"score": 14.292072349947833
},
{
"filename": "src/api.ts",
"retrieved_chunk": "\t'A#1': 58,\n\t'B1': 62,\n\t'C2': 65,\n\t'C#2': 69,\n\t'D2': 73,\n\t'D#2': 78,\n\t'E2': 82,\n\t'F2': 87,\n\t'F#2': 93,\n\t'G2': 98,",
"score": 12.033032276438973
}
] | typescript | ): PlayTuneRes { |
import type { AddTextOptions, FullSprigAPI, GameState, SpriteType } from '../api.js'
import { palette } from './palette.js'
export * from './font.js'
export * from './palette.js'
export * from './text.js'
export * from './tune.js'
// Tagged template literal factory go brrr
const _makeTag = <T>(cb: (string: string) => T) => {
return (strings: TemplateStringsArray, ...interps: string[]) => {
if (typeof strings === 'string') {
throw new Error('Tagged template literal must be used like name`text`, instead of name(`text`)')
}
const string = strings.reduce((p, c, i) => p + c + (interps[i] ?? ''), '')
return cb(string)
}
}
export type BaseEngineAPI = Pick<
FullSprigAPI,
| 'setMap'
| 'addText'
| 'clearText'
| 'addSprite'
| 'getGrid'
| 'getTile'
| 'tilesWith'
| 'clearTile'
| 'setSolids'
| 'setPushables'
| 'setBackground'
| 'map'
| 'bitmap'
| 'color'
| 'tune'
| 'getFirst'
| 'getAll'
| 'width'
| 'height'
>
export function baseEngine(): { api: BaseEngineAPI, state: GameState } {
const gameState: GameState = {
legend: [],
texts: [],
dimensions: {
width: 0,
height: 0,
},
sprites: [],
solids: [],
pushable: {},
background: null
}
class Sprite implements SpriteType {
_type: string
_x: number
_y: number
dx: number
dy: number
constructor(type: string, x: number, y: number) {
this._type = type
this._x = x
this._y = y
this.dx = 0
this.dy = 0
}
set type(newType) {
const legendDict = Object.fromEntries(gameState.legend)
if (!(newType in legendDict)) throw new Error(`"${newType}" isn\'t in the legend.`)
this.remove()
addSprite(this._x, this._y, newType)
}
get type() {
return this._type
}
set x(newX) {
const dx = newX - this.x
if (_canMoveToPush(this, dx, 0)) this.dx = dx
}
get x() {
return this._x
}
set y(newY) {
const dy = newY - this.y
if (_canMoveToPush(this, 0, dy)) this.dy = dy
}
get y() {
return this._y
}
remove() {
| gameState.sprites = gameState.sprites.filter(s => s !== this)
return this
} |
}
const _canMoveToPush = (sprite: Sprite, dx: number, dy: number): boolean => {
const { x, y, type } = sprite
const { width, height } = gameState.dimensions
const i = (x+dx)+(y+dy)*width
const inBounds = (x+dx < width && x+dx >= 0 && y+dy < height && y+dy >= 0)
if (!inBounds) return false
const grid = getGrid()
const notSolid = !gameState.solids.includes(type)
const noMovement = dx === 0 && dy === 0
const movingToEmpty = i < grid.length && grid[i]!.length === 0
if (notSolid || noMovement || movingToEmpty) {
sprite._x += dx
sprite._y += dy
return true
}
let canMove = true
const { pushable } = gameState
grid[i]!.forEach(sprite => {
const isSolid = gameState.solids.includes(sprite.type)
const isPushable = (type in pushable) && pushable[type]!.includes(sprite.type)
if (isSolid && !isPushable)
canMove = false
if (isSolid && isPushable) {
canMove = canMove && _canMoveToPush(sprite as Sprite, dx, dy)
}
})
if (canMove) {
sprite._x += dx
sprite._y += dy
}
return canMove
}
const getGrid = (): SpriteType[][] => {
const { width, height } = gameState.dimensions
const grid: SpriteType[][] = new Array(width*height).fill(0).map(_ => [])
gameState.sprites.forEach(s => {
const i = s.x+s.y*width
grid[i]!.push(s)
})
const legendIndex = (t: SpriteType) => gameState.legend.findIndex(l => l[0] == t.type)
for (const tile of grid) tile.sort((a, b) => legendIndex(a) - legendIndex(b))
return grid
}
const _checkBounds = (x: number, y: number): void => {
const { width, height } = gameState.dimensions
if (x >= width || x < 0 || y < 0 || y >= height) throw new Error(`Sprite out of bounds.`)
}
const _checkLegend = (type: string): void => {
if (!(type in Object.fromEntries(gameState.legend)))
throw new Error(`Unknown sprite type: ${type}`)
}
const addSprite = (x: number, y: number, type: string): void => {
if (type === '.') return
_checkBounds(x, y)
_checkLegend(type)
const s = new Sprite(type, x, y)
gameState.sprites.push(s)
}
const _allEqual = <T>(arr: T[]): boolean => arr.every(val => val === arr[0])
const setMap = (string: string): void => {
if (!string) throw new Error('Tried to set empty map.')
if (string.constructor == Object) throw new Error('setMap() takes a string, not a dict.') // https://stackoverflow.com/a/51285298
if (Array.isArray(string)) throw new Error('It looks like you passed an array into setMap(). Did you mean to use something like setMap(levels[level]) instead of setMap(levels)?')
const rows = string.trim().split("\n").map(x => x.trim())
const rowLengths = rows.map(x => x.length)
const isRect = _allEqual(rowLengths)
if (!isRect) throw new Error('Level must be rectangular.')
const w = rows[0]?.length ?? 0
const h = rows.length
gameState.dimensions.width = w
gameState.dimensions.height = h
gameState.sprites = []
const nonSpace = string.split("").filter(x => x !== " " && x !== "\n") // \S regex was too slow
for (let i = 0; i < w*h; i++) {
const type = nonSpace[i]!
if (type === '.') continue
const x = i%w
const y = Math.floor(i/w)
addSprite(x, y, type)
}
}
const clearTile = (x: number, y: number): void => {
gameState.sprites = gameState.sprites.filter(s => s.x !== x || s.y !== y)
}
const addText = (str: string, opts: AddTextOptions = {}): void => {
const CHARS_MAX_X = 21
const padLeft = Math.floor((CHARS_MAX_X - str.length)/2)
if (Array.isArray(opts.color)) throw new Error('addText no longer takes an RGBA color. Please use a Sprig color instead with \"{ color: color`` }\"')
const [, rgba ] = palette.find(([key]) => key === opts.color) ?? palette.find(([key]) => key === 'L')!
gameState.texts.push({
x: opts.x ?? padLeft,
y: opts.y ?? 0,
color: rgba,
content: str
})
}
const clearText = (): void => { gameState.texts = [] }
const getTile = (x: number, y: number): SpriteType[] => {
if (y < 0) return []
if (x < 0) return []
if (y >= gameState.dimensions.height) return []
if (x >= gameState.dimensions.width) return []
return getGrid()[gameState.dimensions.width*y+x] ?? []
}
const _hasDuplicates = <T>(array: T[]): boolean => (new Set(array)).size !== array.length
const tilesWith = (...matchingTypes: string[]): SpriteType[][] => {
const { width, height } = gameState.dimensions
const tiles: SpriteType[][] = []
const grid = getGrid()
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
const tile = grid[width*y+x] || []
const matchIndices = matchingTypes.map(type => {
return tile.map(s => s.type).indexOf(type)
})
if (!_hasDuplicates(matchIndices) && !matchIndices.includes(-1)) tiles.push(tile)
}
}
return tiles
}
const setSolids = (arr: string[]): void => {
if (!Array.isArray(arr)) throw new Error('The sprites passed into setSolids() need to be an array.')
gameState.solids = arr
}
const setPushables = (map: Record<string, string[]>): void => {
for (const key in map) {
if(key.length != 1) {
throw new Error('Your sprite name must be wrapped in [] brackets here.');
}
_checkLegend(key)
}
gameState.pushable = map
}
const api: BaseEngineAPI = {
setMap,
addText,
clearText,
addSprite,
getGrid,
getTile,
tilesWith,
clearTile,
setSolids,
setPushables,
setBackground: (type: string) => { gameState.background = type },
map: _makeTag(text => text),
bitmap: _makeTag(text => text),
color: _makeTag(text => text),
tune: _makeTag(text => text),
getFirst: (type: string): SpriteType | undefined => gameState.sprites.find(t => t.type === type), // **
getAll: (type: string): SpriteType[] => type ? gameState.sprites.filter(t => t.type === type) : gameState.sprites, // **
width: () => gameState.dimensions.width,
height: () => gameState.dimensions.height
}
return { api, state: gameState }
}
| src/base/index.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/api.ts",
"retrieved_chunk": "\ty: number\n\treadonly dx: number\n\treadonly dy: number\n\tremove(): void\n}\nexport type Rgba = [number, number, number, number]\nexport interface TextElement {\n\tx: number\n\ty: number\n\tcolor: Rgba",
"score": 28.42190295498473
},
{
"filename": "src/web/tune.ts",
"retrieved_chunk": "\tosc.stop(endTime)\n\trampGain.gain.setValueAtTime(0, ctx.currentTime)\n\trampGain.gain.linearRampToValueAtTime(.2, ctx.currentTime + duration/5/1000)\n\trampGain.gain.exponentialRampToValueAtTime(0.00001, ctx.currentTime + duration/1000)\n\trampGain.gain.linearRampToValueAtTime(0, ctx.currentTime + duration*2/1000) // does this ramp from the last ramp\n\tosc.onended = () => {\n\t\tosc.disconnect()\n\t\trampGain.disconnect()\n\t}\n}",
"score": 26.884683132760106
},
{
"filename": "src/image-data/index.ts",
"retrieved_chunk": "\t\t\t\ts.dx = 0\n\t\t\t\ts.dy = 0\n\t\t\t})\n\t\t},\n\t\trender(): ImageData {\n\t\t\tconst width = () => game.state.dimensions.width\n\t\t\tconst height = () => game.state.dimensions.height\n\t\t\tconst tSize = () => 16\n\t\t\tconst sw = width() * tSize()\n\t\t\tconst sh = height() * tSize()",
"score": 25.39603457865112
},
{
"filename": "src/web/index.ts",
"retrieved_chunk": "\t\t\ts.dy = 0\n\t\t})\n\t\te.preventDefault()\n\t}\n\tcanvas.addEventListener('keydown', keydown)\n\tconst onInput = (key: InputKey, fn: () => void): void => {\n\t\tif (!VALID_INPUTS.includes(key))\n\t\t\tthrow new Error(`Unknown input key, \"${key}\": expected one of ${VALID_INPUTS.join(', ')}`)\n\t\ttileInputs[key].push(fn)\n\t}",
"score": 23.595537825708895
},
{
"filename": "src/web/index.ts",
"retrieved_chunk": "\t}\n\tconst afterInputs: (() => void)[] = []\n\tconst keydown = (e: KeyboardEvent) => {\n\t\tconst key = e.key\n\t\tif (!VALID_INPUTS.includes(key as any)) return\n\t\tfor (const validKey of VALID_INPUTS)\n\t\t\tif (key === validKey) tileInputs[key].forEach(fn => fn())\n\t\tafterInputs.forEach(f => f())\n\t\tstate.sprites.forEach((s: any) => {\n\t\t\ts.dx = 0",
"score": 20.015035408320955
}
] | typescript | gameState.sprites = gameState.sprites.filter(s => s !== this)
return this
} |
import { type InputKey, type PlayTuneRes, VALID_INPUTS, type FullSprigAPI, type GameState } from '../api.js'
import { type BaseEngineAPI, baseEngine, textToTune } from '../base/index.js'
import { bitmapTextToImageData } from '../image-data/index.js'
import { getTextImg } from './text.js'
import { playTune } from './tune.js'
import { makeCanvas } from './util.js'
export * from './text.js'
export * from './tune.js'
export type WebEngineAPI = BaseEngineAPI & Pick<
FullSprigAPI,
| 'setLegend'
| 'onInput'
| 'afterInput'
| 'playTune'
> & {
getState(): GameState // For weird backwards-compatibility reasons, not part of API
}
export function webEngine(canvas: HTMLCanvasElement): {
api: WebEngineAPI,
state: GameState,
cleanup(): void
} {
const { api, state } = baseEngine()
const ctx = canvas.getContext('2d')!
const offscreenCanvas = makeCanvas(1, 1)
const offscreenCtx = offscreenCanvas.getContext('2d')!
const _bitmaps: Record<string, CanvasImageSource> = {}
let _zOrder: string[] = []
ctx.imageSmoothingEnabled = false
const _gameloop = (): void => {
const { width, height } = state.dimensions
if (width === 0 || height === 0) return
ctx.clearRect(0, 0, canvas.width, canvas.height)
offscreenCanvas.width = width*16
offscreenCanvas.height = height*16
offscreenCtx.fillStyle = 'white'
offscreenCtx.fillRect(0, 0, width*16, height*16)
const grid = api.getGrid()
for (let i = 0; i < width * height; i++) {
const x = i % width
const y = Math.floor(i/width)
const sprites = grid[i]!
if (state.background) {
const imgData = _bitmaps[state.background]!
offscreenCtx.drawImage(imgData, x*16, y*16)
}
sprites
.sort((a, b) => _zOrder.indexOf(b.type) - _zOrder.indexOf(a.type))
.forEach | ((sprite) => { |
const imgData = _bitmaps[sprite.type]!
offscreenCtx.drawImage(imgData, x*16, y*16)
})
}
const scale = Math.min(canvas.width/(width*16), canvas.height/(height*16))
const actualWidth = offscreenCanvas.width*scale
const actualHeight = offscreenCanvas.height*scale
ctx.drawImage(
offscreenCanvas,
(canvas.width-actualWidth)/2,
(canvas.height-actualHeight)/2,
actualWidth,
actualHeight
)
const textCanvas = getTextImg(state.texts)
ctx.drawImage(
textCanvas,
0,
0,
canvas.width,
canvas.height
)
animationId = window.requestAnimationFrame(_gameloop)
}
let animationId = window.requestAnimationFrame(_gameloop)
const setLegend = (...bitmaps: [string, string][]): void => {
if (bitmaps.length == 0) throw new Error('There needs to be at least one sprite in the legend.')
if (!Array.isArray(bitmaps[0])) throw new Error('The sprites passed into setLegend each need to be in square brackets, like setLegend([player, bitmap`...`]).')
bitmaps.forEach(([ key ]) => {
if (key === '.') throw new Error(`Can't reassign "." bitmap`)
if (key.length !== 1) throw new Error(`Bitmaps must have one character names`)
})
state.legend = bitmaps
_zOrder = bitmaps.map(x => x[0])
for (let i = 0; i < bitmaps.length; i++) {
const [ key, value ] = bitmaps[i]!
const imgData = bitmapTextToImageData(value)
const littleCanvas = makeCanvas(16, 16)
littleCanvas.getContext('2d')!.putImageData(imgData, 0, 0)
_bitmaps[key] = littleCanvas
}
}
let tileInputs: Record<InputKey, (() => void)[]> = {
w: [],
s: [],
a: [],
d: [],
i: [],
j: [],
k: [],
l: []
}
const afterInputs: (() => void)[] = []
const keydown = (e: KeyboardEvent) => {
const key = e.key
if (!VALID_INPUTS.includes(key as any)) return
for (const validKey of VALID_INPUTS)
if (key === validKey) tileInputs[key].forEach(fn => fn())
afterInputs.forEach(f => f())
state.sprites.forEach((s: any) => {
s.dx = 0
s.dy = 0
})
e.preventDefault()
}
canvas.addEventListener('keydown', keydown)
const onInput = (key: InputKey, fn: () => void): void => {
if (!VALID_INPUTS.includes(key))
throw new Error(`Unknown input key, "${key}": expected one of ${VALID_INPUTS.join(', ')}`)
tileInputs[key].push(fn)
}
const afterInput = (fn: () => void): void => { afterInputs.push(fn) }
const tunes: PlayTuneRes[] = []
return {
api: {
...api,
setLegend,
onInput,
afterInput,
getState: () => state,
playTune: (text: string, n: number) => {
const tune = textToTune(text)
const playTuneRes = playTune(tune, n)
tunes.push(playTuneRes)
return playTuneRes
}
},
state,
cleanup: () => {
ctx.clearRect(0, 0, canvas.width, canvas.height)
window.cancelAnimationFrame(animationId)
canvas.removeEventListener('keydown', keydown)
tunes.forEach(tune => tune.end())
}
}
}
| src/web/index.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/base/index.ts",
"retrieved_chunk": "\t\t})\n\t\tconst legendIndex = (t: SpriteType) => gameState.legend.findIndex(l => l[0] == t.type)\n\t\tfor (const tile of grid) tile.sort((a, b) => legendIndex(a) - legendIndex(b))\n\t\treturn grid\n\t}\n\tconst _checkBounds = (x: number, y: number): void => {\n\t\tconst { width, height } = gameState.dimensions\n\t\tif (x >= width || x < 0 || y < 0 || y >= height) throw new Error(`Sprite out of bounds.`)\n\t}\n\tconst _checkLegend = (type: string): void => {",
"score": 33.795961957861294
},
{
"filename": "src/base/index.ts",
"retrieved_chunk": "\t\tconst h = rows.length\n\t\tgameState.dimensions.width = w\n\t\tgameState.dimensions.height = h\n\t\tgameState.sprites = []\n\t\tconst nonSpace = string.split(\"\").filter(x => x !== \" \" && x !== \"\\n\") // \\S regex was too slow\n\t\tfor (let i = 0; i < w*h; i++) {\n\t\t\tconst type = nonSpace[i]!\n\t\t\tif (type === '.') continue\n\t\t\tconst x = i%w \n\t\t\tconst y = Math.floor(i/w)",
"score": 29.10323304242373
},
{
"filename": "src/base/index.ts",
"retrieved_chunk": "\t\t\tsprite._y += dy\n\t\t}\n\t\treturn canMove\n\t}\n\tconst getGrid = (): SpriteType[][] => {\n\t\tconst { width, height } = gameState.dimensions\n\t\tconst grid: SpriteType[][] = new Array(width*height).fill(0).map(_ => [])\n\t\tgameState.sprites.forEach(s => {\n\t\t\tconst i = s.x+s.y*width\n\t\t\tgrid[i]!.push(s)",
"score": 27.92038744332249
},
{
"filename": "src/image-data/bitmap.ts",
"retrieved_chunk": " const colors = Object.fromEntries(palette)\n const nonSpace = text.split('').filter(x => x !== ' ' && x !== '\\n') // \\S regex led to massive perf problems\n for (let i = 0; i < width*height; i++) {\n const type = nonSpace[i] || \".\"\n if (!(type in colors)) {\n const err = `in sprite string: no known color for char \"${type}\"`\n console.error(err + '\\n' + text)\n throw new Error(err + ' (invalid sprite in console)')\n }\n const [ r, g, b, a ] = colors[type] ?? colors['.']!",
"score": 26.722354024233788
},
{
"filename": "src/base/palette.ts",
"retrieved_chunk": "\tconst [ r, g, b, a ] = hex.match(/\\w\\w/g)?.map((x) => parseInt(x, 16)) ?? []\n\treturn [ r!, g!, b!, a ?? 255 ]\n}\nexport const rgbaToHex = (rgba: Rgba): string => {\n\treturn '#' + rgba.map(n => n.toString(16).padStart(2, '0')).join('')\n}",
"score": 26.610913489784284
}
] | typescript | ((sprite) => { |
import { type InstrumentType, type PlayTuneRes, type Tune, instruments, tones } from '../api.js'
export function playFrequency(frequency: number, duration: number, instrument: InstrumentType, ctx: AudioContext, dest: AudioNode) {
const osc = ctx.createOscillator()
const rampGain = ctx.createGain()
osc.connect(rampGain)
rampGain.connect(dest)
osc.frequency.value = frequency
osc.type = instrument ?? 'sine'
osc.start()
const endTime = ctx.currentTime + duration*2/1000
osc.stop(endTime)
rampGain.gain.setValueAtTime(0, ctx.currentTime)
rampGain.gain.linearRampToValueAtTime(.2, ctx.currentTime + duration/5/1000)
rampGain.gain.exponentialRampToValueAtTime(0.00001, ctx.currentTime + duration/1000)
rampGain.gain.linearRampToValueAtTime(0, ctx.currentTime + duration*2/1000) // does this ramp from the last ramp
osc.onended = () => {
osc.disconnect()
rampGain.disconnect()
}
}
const sleep = async (duration: number) => new Promise(resolve => setTimeout(resolve, duration))
export async function playTuneHelper(tune: Tune, number: number, playingRef: { playing: boolean }, ctx: AudioContext, dest: AudioNode) {
for (let i = 0; i < tune.length*number; i++) {
const index = i%tune.length
if (!playingRef.playing) break
const noteSet = tune[index]!
const sleepTime = noteSet[0]
for (let j = 1; j < noteSet.length; j += 3) {
const instrument = noteSet[j] as InstrumentType
const note = noteSet[j+1]!
const duration = noteSet[j+2] as number
const frequency = typeof note === 'string'
? tones[note.toUpperCase()]
: 2**((note-69)/12)*440
if | (instruments.includes(instrument) && frequency !== undefined) playFrequency(frequency, duration, instrument, ctx, dest)
} |
await sleep(sleepTime)
}
}
let audioCtx: AudioContext | null = null
export function playTune(tune: Tune, number = 1): PlayTuneRes {
const playingRef = { playing: true }
if (audioCtx === null) audioCtx = new AudioContext()
playTuneHelper(tune, number, playingRef, audioCtx, audioCtx.destination)
return {
end() { playingRef.playing = false },
isPlaying() { return playingRef.playing }
}
} | src/web/tune.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/base/tune.ts",
"retrieved_chunk": "\t\t}\n\t\treturn groups\n\t}\n\tconst notesToString = ([duration, ...notes]: Tune[number]) => (\n\t\tnotes.length === 0 \n\t\t\t? duration \n\t\t\t: `${duration}: ${groupNotes(notes).map(notesToStringHelper).join(' + ')}`\n\t)\n\tconst notesToStringHelper = ([instrument, duration, note]: (number | string)[]) => (\n\t\t`${duration}${reverseInstrumentKey[instrument as InstrumentType]}${note}`",
"score": 81.48226213822878
},
{
"filename": "src/api.ts",
"retrieved_chunk": "export const VALID_INPUTS = [ 'w', 's', 'a', 'd', 'i', 'j', 'k', 'l' ] as const\nexport type InputKey = typeof VALID_INPUTS[number]\nexport interface AddTextOptions {\n\tx?: number\n\ty?: number\n\tcolor?: string\n}\nexport declare class SpriteType {\n\ttype: string\n\tx: number",
"score": 43.20899752784201
},
{
"filename": "src/image-data/index.ts",
"retrieved_chunk": "\t\td: [],\n\t\ti: [],\n\t\tj: [],\n\t\tk: [],\n\t\tl: []\n\t}\n\tconst afterInputs: (() => void)[] = []\n\tconst cleanup = () => {\n\t\ttimeouts.forEach(clearTimeout)\n\t\tintervals.forEach(clearInterval)",
"score": 36.64715891214083
},
{
"filename": "src/web/index.ts",
"retrieved_chunk": "\t}\n\tlet tileInputs: Record<InputKey, (() => void)[]> = {\n\t\tw: [],\n\t\ts: [],\n\t\ta: [],\n\t\td: [],\n\t\ti: [],\n\t\tj: [],\n\t\tk: [],\n\t\tl: []",
"score": 33.6505861107366
},
{
"filename": "src/api.ts",
"retrieved_chunk": "export type InstrumentType = typeof instruments[number]\nexport const instrumentKey: Record<string, InstrumentType> = {\n\t'~': 'sine',\n\t'-': 'square',\n\t'^': 'triangle',\n\t'/': 'sawtooth'\n}\nexport const reverseInstrumentKey = Object.fromEntries(\n\tObject.entries(instrumentKey).map(([ k, v ]) => [ v, k ])\n) as Record<InstrumentType, string>",
"score": 29.31059474055168
}
] | typescript | (instruments.includes(instrument) && frequency !== undefined) playFrequency(frequency, duration, instrument, ctx, dest)
} |
import { executePrompt, executePromptStream } from "./executePrompt.js";
import { loadConfig } from "./config.js";
import { loadPromptConfig, listPrompts } from "./loadPromptConfig.js";
import { APPNAME } from "./types.js";
import FileSystemKVS from "./kvs/kvs-filesystem.js";
import { AppError } from "./errors.js";
import { readFileSync } from "node:fs";
function parseArgs(argv: string[]) {
const [_nodeBin, _jsFile, promptId, ...rest] = argv;
const input = rest.join(" ");
return { promptId, input };
}
function printUsageAndExit() {
console.log("Usage:");
console.log(`$ ${APPNAME} <promptType> <input>`);
console.log(`$ ${APPNAME} --list`);
console.log("");
console.log("Example: ");
console.log("");
console.log(`$ ${APPNAME} eli5 "what are large language models?"`);
process.exit(1);
}
function getInput(argvInput: string) {
try {
const stdinInput = readFileSync(process.stdin.fd, "utf-8");
// console.log({ stdinInput });
return `${argvInput} ${stdinInput}`;
} catch (err) {
return argvInput;
}
}
export async function cli() {
try {
const config = loadConfig();
const { promptId, input: argvInput } = parseArgs(process.argv);
if (promptId === "--list") {
const prompts = await listPrompts(config);
console.log(
prompts
.map((p) => {
const description = p.description ? `: ${p.description}` : "";
return `${p.name}${description}`;
})
.join("\n")
);
return;
} else if (promptId && promptId.startsWith("--")) {
printUsageAndExit();
}
const input = getInput(argvInput);
if (!promptId || !input) {
printUsageAndExit();
}
const promptConfig = await loadPromptConfig(promptId, config);
const cache = config.useCache
| ? new FileSystemKVS({ baseDir: config.paths.cache })
: undefined; |
const stream = executePromptStream(promptConfig, input, config, cache);
for await (const chunk of stream) {
process.stdout.write(chunk);
}
process.stdout.write("\n");
} catch (err) {
if (err instanceof AppError) {
console.error(err.toString());
process.exit(err.exitCode);
}
console.error(err);
process.exit(1);
}
}
export default cli;
| src/index.ts | clevercli-clevercli-c660fae | [
{
"filename": "src/loadPromptConfig.ts",
"retrieved_chunk": "export async function loadFromPath(path: string) {\n const promptConfig = await import(path);\n // TODO: validate promptConfig?\n return promptConfig.default;\n}\nexport async function loadPromptConfig(promptId: string, config: Config) {\n try {\n const promptConfig = await Promise.any([\n loadFromPath(sourceRelativePath(import.meta, `./prompts/${promptId}.js`)),\n loadFromPath(pathJoin(config.paths.data, `${promptId}.mjs`)),",
"score": 27.24368845756548
},
{
"filename": "src/config.ts",
"retrieved_chunk": " apiKey: getEnvOrThrow(\"OPENAI_API_KEY\"),\n },\n paths: {\n data: pathJoin(homedir(), `.${APPNAME}`),\n cache: paths.cache,\n },\n useCache: true,\n };\n debug(config);\n return config;",
"score": 21.876415717747566
},
{
"filename": "src/loadPromptConfig.ts",
"retrieved_chunk": " ]);\n return promptConfig;\n } catch (err) {\n throw new AppError({\n message: `Could not find prompt ${promptId}. Are you sure it is a builtin prompt or that ${config.paths.data}/${promptId}.mjs exists?`,\n });\n }\n}\nexport async function listPrompts(config: Config) {\n const [localFiles, builtinFiles] = await Promise.all(",
"score": 21.551173551481508
},
{
"filename": "src/executePrompt.ts",
"retrieved_chunk": " const response = (\n await asyncIterableToArray(\n executePromptStream(promptConfig, input, config, cache)\n )\n ).join(\"\");\n return parseResponse(response, input);\n}\nexport default executePrompt;",
"score": 20.658324077636312
},
{
"filename": "src/executePrompt.ts",
"retrieved_chunk": " }\n}\nexport async function executePrompt(\n promptConfig: PromptConfiguration,\n input: string,\n config: Config,\n cache?: KeyValueStore<string, string>\n): Promise<ParsedResponse> {\n const model = toModel(promptConfig);\n const parseResponse = promptConfig.parseResponse ?? defaultParseResponse;",
"score": 18.70475749622126
}
] | typescript | ? new FileSystemKVS({ baseDir: config.paths.cache })
: undefined; |
/*
song form
[
[duration, instrument, pitch, duration, ...],
]
Syntax:
500: 64.4~500 + c5~1000
[500, 'sine', 64.4, 500, 'sine', 'c5', 1000]
Comma between each tune element. Whitespace ignored.
*/
import { type Tune, instrumentKey, InstrumentType, reverseInstrumentKey } from '../api.js'
export const textToTune = (text: string): Tune => {
const elements = text.replace(/\s/g, '').split(',')
const tune = []
for (const element of elements) {
if (!element) continue
const [durationRaw, notesRaw] = element.split(':')
const duration = Math.round(parseInt(durationRaw ?? '0', 10))
const notes = (notesRaw || '').split('+').map((noteRaw) => {
if (!noteRaw) return []
const [, pitchRaw, instrumentRaw, durationRaw] = noteRaw.match(/^(.+)([~\-^\/])(.+)$/)!
return [
instrumentKey[instrumentRaw!] ?? 'sine',
isNaN(parseInt(pitchRaw ?? '', 10)) ? pitchRaw! : parseInt(pitchRaw!, 10),
parseInt(durationRaw ?? '0', 10)
]
})
tune.push([duration, ...notes].flat())
}
return tune as Tune
}
export const tuneToText = (tune: Tune): string => {
const groupNotes = (notes: (number | string)[]) => {
const groups = []
for (let i = 0; i < notes.length; i++) {
if (i % 3 === 0) {
groups.push([notes[i]!])
} else {
groups[groups.length-1]!.push(notes[i]!)
}
}
return groups
}
const notesToString = ([duration, ...notes]: Tune[number]) => (
notes.length === 0
? duration
: `${duration}: ${groupNotes(notes).map(notesToStringHelper).join(' + ')}`
)
const notesToStringHelper = ([instrument, duration, note]: (number | string)[]) => (
`${duration}${reverseInstrumentKey[instrument as InstrumentType]}${note}`
)
return tune. | map(notesToString).join(',\n')
} | src/base/tune.ts | hackclub-sprig-engine-e5e3c0c | [
{
"filename": "src/web/tune.ts",
"retrieved_chunk": "\t\t\tconst duration = noteSet[j+2] as number\n\t\t\tconst frequency = typeof note === 'string' \n\t\t\t\t? tones[note.toUpperCase()]\n\t\t\t\t: 2**((note-69)/12)*440\n\t\t\tif (instruments.includes(instrument) && frequency !== undefined) playFrequency(frequency, duration, instrument, ctx, dest)\n\t\t}\n\t\tawait sleep(sleepTime)\n\t}\n}\nlet audioCtx: AudioContext | null = null",
"score": 49.96241468711131
},
{
"filename": "src/web/tune.ts",
"retrieved_chunk": "const sleep = async (duration: number) => new Promise(resolve => setTimeout(resolve, duration))\nexport async function playTuneHelper(tune: Tune, number: number, playingRef: { playing: boolean }, ctx: AudioContext, dest: AudioNode) {\n\tfor (let i = 0; i < tune.length*number; i++) {\n\t\tconst index = i%tune.length\n\t\tif (!playingRef.playing) break\n\t\tconst noteSet = tune[index]!\n\t\tconst sleepTime = noteSet[0]\n\t\tfor (let j = 1; j < noteSet.length; j += 3) {\n\t\t\tconst instrument = noteSet[j] as InstrumentType\n\t\t\tconst note = noteSet[j+1]!",
"score": 45.06148962360298
},
{
"filename": "src/web/tune.ts",
"retrieved_chunk": "import { type InstrumentType, type PlayTuneRes, type Tune, instruments, tones } from '../api.js'\nexport function playFrequency(frequency: number, duration: number, instrument: InstrumentType, ctx: AudioContext, dest: AudioNode) {\n\tconst osc = ctx.createOscillator()\n\tconst rampGain = ctx.createGain()\n\tosc.connect(rampGain)\n\trampGain.connect(dest)\n\tosc.frequency.value = frequency\n\tosc.type = instrument ?? 'sine'\n\tosc.start()\n\tconst endTime = ctx.currentTime + duration*2/1000",
"score": 34.74546714235583
},
{
"filename": "src/base/palette.ts",
"retrieved_chunk": "\tconst [ r, g, b, a ] = hex.match(/\\w\\w/g)?.map((x) => parseInt(x, 16)) ?? []\n\treturn [ r!, g!, b!, a ?? 255 ]\n}\nexport const rgbaToHex = (rgba: Rgba): string => {\n\treturn '#' + rgba.map(n => n.toString(16).padStart(2, '0')).join('')\n}",
"score": 23.494943106585467
},
{
"filename": "src/api.ts",
"retrieved_chunk": "export type InstrumentType = typeof instruments[number]\nexport const instrumentKey: Record<string, InstrumentType> = {\n\t'~': 'sine',\n\t'-': 'square',\n\t'^': 'triangle',\n\t'/': 'sawtooth'\n}\nexport const reverseInstrumentKey = Object.fromEntries(\n\tObject.entries(instrumentKey).map(([ k, v ]) => [ v, k ])\n) as Record<InstrumentType, string>",
"score": 23.156040094548196
}
] | typescript | map(notesToString).join(',\n')
} |
|
import {
ChatCompletionRequestMessageRoleEnum,
Configuration as OpenAIConfiguration,
OpenAIApi,
} from "openai";
import models, { defaultModel } from "./openaiModels.js";
import { ApiError, AppError } from "./errors.js";
import { Config, Model, ParsedResponse, PromptConfiguration } from "./types.js";
import KeyValueStore from "./kvs/abstract.js";
import { openAIQuery } from "./openai.js";
import { asyncIterableToArray } from "./utils.js";
function defaultParseResponse(content: string, _input: string): ParsedResponse {
return { message: content };
}
function toModel(promptConfig: PromptConfiguration): Model {
const model = promptConfig.model
? models.get(promptConfig.model)
: defaultModel;
if (!model) {
throw new AppError({
message: `Could not find model "${promptConfig.model}"`,
});
}
return model;
}
export async function* executePromptStream(
promptConfig: PromptConfiguration,
input: string,
config: Config,
cache?: KeyValueStore<string, string>
): AsyncGenerator<string> {
const model = toModel(promptConfig);
const formattedPrompt = promptConfig.createPrompt(input);
const cacheKey = `${model.id}-${formattedPrompt}`;
if (cache) {
const cachedResponse = await cache.get(cacheKey);
if (cachedResponse) {
yield cachedResponse;
return;
}
}
const stream = openAIQuery(model, formattedPrompt, config);
const chunks = [];
for await (const chunk of stream) {
chunks.push(chunk);
yield chunk;
}
if (cache) {
const response = chunks.join("");
await cache.set(cacheKey, response);
}
}
export async function executePrompt(
promptConfig: PromptConfiguration,
input: string,
config: Config,
cache?: KeyValueStore<string, string>
): Promise< | ParsedResponse> { |
const model = toModel(promptConfig);
const parseResponse = promptConfig.parseResponse ?? defaultParseResponse;
const response = (
await asyncIterableToArray(
executePromptStream(promptConfig, input, config, cache)
)
).join("");
return parseResponse(response, input);
}
export default executePrompt;
| src/executePrompt.ts | clevercli-clevercli-c660fae | [
{
"filename": "src/index.ts",
"retrieved_chunk": " if (!promptId || !input) {\n printUsageAndExit();\n }\n const promptConfig = await loadPromptConfig(promptId, config);\n const cache = config.useCache\n ? new FileSystemKVS({ baseDir: config.paths.cache })\n : undefined;\n const stream = executePromptStream(promptConfig, input, config, cache);\n for await (const chunk of stream) {\n process.stdout.write(chunk);",
"score": 18.1773018348824
},
{
"filename": "src/loadPromptConfig.ts",
"retrieved_chunk": "export async function loadFromPath(path: string) {\n const promptConfig = await import(path);\n // TODO: validate promptConfig?\n return promptConfig.default;\n}\nexport async function loadPromptConfig(promptId: string, config: Config) {\n try {\n const promptConfig = await Promise.any([\n loadFromPath(sourceRelativePath(import.meta, `./prompts/${promptId}.js`)),\n loadFromPath(pathJoin(config.paths.data, `${promptId}.mjs`)),",
"score": 17.237124561073525
},
{
"filename": "src/prompts/ask.ts",
"retrieved_chunk": "import { ParsedResponse, PromptConfiguration } from \"../types.js\";\nconst promptConfiguration: PromptConfiguration = {\n description: \"Just passes through the input directly to ChatGPT.\",\n createPrompt(input: string) {\n return input;\n },\n parseResponse(response: string, _input: string): ParsedResponse {\n return { message: response };\n },\n};",
"score": 15.49061313887772
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export interface Config {\n openai: {\n apiKey: string;\n };\n useCache: boolean;\n paths: {\n data: string;\n cache: string;\n };\n}",
"score": 15.320117707546295
},
{
"filename": "src/types.ts",
"retrieved_chunk": " id: string;\n type: ModelType;\n maxTokens: number;\n}\nexport interface PromptConfiguration {\n createPrompt(input: string): string;\n parseResponse?(response: string, input: string): ParsedResponse;\n model?: string;\n description?: string;\n}",
"score": 14.686849531934834
}
] | typescript | ParsedResponse> { |
import {
ChatCompletionRequestMessageRoleEnum,
Configuration as OpenAIConfiguration,
OpenAIApi,
} from "openai";
import models, { defaultModel } from "./openaiModels.js";
import { ApiError, AppError } from "./errors.js";
import { Config, Model, ParsedResponse, PromptConfiguration } from "./types.js";
import KeyValueStore from "./kvs/abstract.js";
import { openAIQuery } from "./openai.js";
import { asyncIterableToArray } from "./utils.js";
function defaultParseResponse(content: string, _input: string): ParsedResponse {
return { message: content };
}
function toModel(promptConfig: PromptConfiguration): Model {
const model = promptConfig.model
? models.get(promptConfig.model)
: defaultModel;
if (!model) {
throw new AppError({
message: `Could not find model "${promptConfig.model}"`,
});
}
return model;
}
export async function* executePromptStream(
promptConfig: PromptConfiguration,
input: string,
config: Config,
cache?: KeyValueStore<string, string>
): AsyncGenerator<string> {
const model = toModel(promptConfig);
const formattedPrompt = promptConfig.createPrompt(input);
const cacheKey = `${model.id}-${formattedPrompt}`;
if (cache) {
const cachedResponse = await cache.get(cacheKey);
if (cachedResponse) {
yield cachedResponse;
return;
}
}
const stream = openAIQuery(model, formattedPrompt, config);
const chunks = [];
for await (const chunk of stream) {
chunks.push(chunk);
yield chunk;
}
if (cache) {
const response = chunks.join("");
await cache.set(cacheKey, response);
}
}
export async function executePrompt(
promptConfig: PromptConfiguration,
input: string,
config: Config,
cache?: KeyValueStore<string, string>
): Promise<ParsedResponse> {
const model = toModel(promptConfig);
const parseResponse = promptConfig.parseResponse ?? defaultParseResponse;
const response = (
await | asyncIterableToArray(
executePromptStream(promptConfig, input, config, cache)
)
).join(""); |
return parseResponse(response, input);
}
export default executePrompt;
| src/executePrompt.ts | clevercli-clevercli-c660fae | [
{
"filename": "src/index.ts",
"retrieved_chunk": " if (!promptId || !input) {\n printUsageAndExit();\n }\n const promptConfig = await loadPromptConfig(promptId, config);\n const cache = config.useCache\n ? new FileSystemKVS({ baseDir: config.paths.cache })\n : undefined;\n const stream = executePromptStream(promptConfig, input, config, cache);\n for await (const chunk of stream) {\n process.stdout.write(chunk);",
"score": 32.90648943301486
},
{
"filename": "src/loadPromptConfig.ts",
"retrieved_chunk": "export async function loadFromPath(path: string) {\n const promptConfig = await import(path);\n // TODO: validate promptConfig?\n return promptConfig.default;\n}\nexport async function loadPromptConfig(promptId: string, config: Config) {\n try {\n const promptConfig = await Promise.any([\n loadFromPath(sourceRelativePath(import.meta, `./prompts/${promptId}.js`)),\n loadFromPath(pathJoin(config.paths.data, `${promptId}.mjs`)),",
"score": 24.09620358849833
},
{
"filename": "src/types.ts",
"retrieved_chunk": " id: string;\n type: ModelType;\n maxTokens: number;\n}\nexport interface PromptConfiguration {\n createPrompt(input: string): string;\n parseResponse?(response: string, input: string): ParsedResponse;\n model?: string;\n description?: string;\n}",
"score": 20.26148281963682
},
{
"filename": "src/prompts/ask.ts",
"retrieved_chunk": "import { ParsedResponse, PromptConfiguration } from \"../types.js\";\nconst promptConfiguration: PromptConfiguration = {\n description: \"Just passes through the input directly to ChatGPT.\",\n createPrompt(input: string) {\n return input;\n },\n parseResponse(response: string, _input: string): ParsedResponse {\n return { message: response };\n },\n};",
"score": 19.570018840440518
},
{
"filename": "src/prompts/eli5.ts",
"retrieved_chunk": "import { ParsedResponse, PromptConfiguration } from \"../types.js\";\nconst promptConfiguration: PromptConfiguration = {\n description: \"Explain Me Like I'm 5\",\n createPrompt(input: string) {\n return `Provide a very detailed explanation but like I am 5 years old (ELI5) on this topic: ${input}.\\n###\\n`;\n },\n parseResponse(response: string, _input: string): ParsedResponse {\n return { message: response };\n },\n};",
"score": 16.218032993217435
}
] | typescript | asyncIterableToArray(
executePromptStream(promptConfig, input, config, cache)
)
).join(""); |
import { executePrompt, executePromptStream } from "./executePrompt.js";
import { loadConfig } from "./config.js";
import { loadPromptConfig, listPrompts } from "./loadPromptConfig.js";
import { APPNAME } from "./types.js";
import FileSystemKVS from "./kvs/kvs-filesystem.js";
import { AppError } from "./errors.js";
import { readFileSync } from "node:fs";
function parseArgs(argv: string[]) {
const [_nodeBin, _jsFile, promptId, ...rest] = argv;
const input = rest.join(" ");
return { promptId, input };
}
function printUsageAndExit() {
console.log("Usage:");
console.log(`$ ${APPNAME} <promptType> <input>`);
console.log(`$ ${APPNAME} --list`);
console.log("");
console.log("Example: ");
console.log("");
console.log(`$ ${APPNAME} eli5 "what are large language models?"`);
process.exit(1);
}
function getInput(argvInput: string) {
try {
const stdinInput = readFileSync(process.stdin.fd, "utf-8");
// console.log({ stdinInput });
return `${argvInput} ${stdinInput}`;
} catch (err) {
return argvInput;
}
}
export async function cli() {
try {
const config = loadConfig();
const { promptId, input: argvInput } = parseArgs(process.argv);
if (promptId === "--list") {
const prompts = await listPrompts(config);
console.log(
prompts
.map(( | p) => { |
const description = p.description ? `: ${p.description}` : "";
return `${p.name}${description}`;
})
.join("\n")
);
return;
} else if (promptId && promptId.startsWith("--")) {
printUsageAndExit();
}
const input = getInput(argvInput);
if (!promptId || !input) {
printUsageAndExit();
}
const promptConfig = await loadPromptConfig(promptId, config);
const cache = config.useCache
? new FileSystemKVS({ baseDir: config.paths.cache })
: undefined;
const stream = executePromptStream(promptConfig, input, config, cache);
for await (const chunk of stream) {
process.stdout.write(chunk);
}
process.stdout.write("\n");
} catch (err) {
if (err instanceof AppError) {
console.error(err.toString());
process.exit(err.exitCode);
}
console.error(err);
process.exit(1);
}
}
export default cli;
| src/index.ts | clevercli-clevercli-c660fae | [
{
"filename": "src/loadPromptConfig.ts",
"retrieved_chunk": "export async function loadFromPath(path: string) {\n const promptConfig = await import(path);\n // TODO: validate promptConfig?\n return promptConfig.default;\n}\nexport async function loadPromptConfig(promptId: string, config: Config) {\n try {\n const promptConfig = await Promise.any([\n loadFromPath(sourceRelativePath(import.meta, `./prompts/${promptId}.js`)),\n loadFromPath(pathJoin(config.paths.data, `${promptId}.mjs`)),",
"score": 27.460908835890084
},
{
"filename": "src/loadPromptConfig.ts",
"retrieved_chunk": " ]);\n return promptConfig;\n } catch (err) {\n throw new AppError({\n message: `Could not find prompt ${promptId}. Are you sure it is a builtin prompt or that ${config.paths.data}/${promptId}.mjs exists?`,\n });\n }\n}\nexport async function listPrompts(config: Config) {\n const [localFiles, builtinFiles] = await Promise.all(",
"score": 20.12889335872816
},
{
"filename": "src/loadPromptConfig.ts",
"retrieved_chunk": " [\n sourceRelativePath(import.meta, `./prompts`),\n pathJoin(config.paths.data),\n ].map(readFilesInDirectory)\n );\n const allFiles = [...localFiles, ...builtinFiles];\n const allPromptConfigs = await Promise.all(allFiles.map(loadFromPath));\n return allPromptConfigs.map((config, i) => {\n const name = parse(allFiles[i]).name;\n return {",
"score": 18.749804239174928
},
{
"filename": "src/config.ts",
"retrieved_chunk": " throw new ConfigError({\n message: `Please set the ${key} environment variable.`,\n });\n }\n return val;\n}\nconst paths = envPaths(APPNAME, { suffix: \"\" });\nexport function loadConfig(): Config {\n const config = {\n openai: {",
"score": 12.408056737006168
},
{
"filename": "src/openai.ts",
"retrieved_chunk": " // console.log({ json });\n if (content) {\n yield content;\n }\n }\n}",
"score": 12.104347450684369
}
] | typescript | p) => { |
import { executePrompt, executePromptStream } from "./executePrompt.js";
import { loadConfig } from "./config.js";
import { loadPromptConfig, listPrompts } from "./loadPromptConfig.js";
import { APPNAME } from "./types.js";
import FileSystemKVS from "./kvs/kvs-filesystem.js";
import { AppError } from "./errors.js";
import { readFileSync } from "node:fs";
function parseArgs(argv: string[]) {
const [_nodeBin, _jsFile, promptId, ...rest] = argv;
const input = rest.join(" ");
return { promptId, input };
}
function printUsageAndExit() {
console.log("Usage:");
console.log(`$ ${APPNAME} <promptType> <input>`);
console.log(`$ ${APPNAME} --list`);
console.log("");
console.log("Example: ");
console.log("");
console.log(`$ ${APPNAME} eli5 "what are large language models?"`);
process.exit(1);
}
function getInput(argvInput: string) {
try {
const stdinInput = readFileSync(process.stdin.fd, "utf-8");
// console.log({ stdinInput });
return `${argvInput} ${stdinInput}`;
} catch (err) {
return argvInput;
}
}
export async function cli() {
try {
const config = loadConfig();
const { promptId, input: argvInput } = parseArgs(process.argv);
if (promptId === "--list") {
const prompts = await listPrompts(config);
console.log(
prompts
.map((p) => {
const description = p.description ? `: ${p.description}` : "";
return `${p.name}${description}`;
})
.join("\n")
);
return;
} else if (promptId && promptId.startsWith("--")) {
printUsageAndExit();
}
const input = getInput(argvInput);
if (!promptId || !input) {
printUsageAndExit();
}
const promptConfig = await loadPromptConfig(promptId, config);
const cache = config.useCache
? new FileSystemKVS({ baseDir: config.paths.cache })
: undefined;
const stream = executePromptStream(promptConfig, input, config, cache);
for await (const chunk of stream) {
process.stdout.write(chunk);
}
process.stdout.write("\n");
} catch (err) {
if (err instanceof AppError) {
console | .error(err.toString()); |
process.exit(err.exitCode);
}
console.error(err);
process.exit(1);
}
}
export default cli;
| src/index.ts | clevercli-clevercli-c660fae | [
{
"filename": "src/openai.ts",
"retrieved_chunk": " return await openai.createChatCompletion(opts, {\n responseType: \"stream\",\n });\n } catch (err) {\n if (err instanceof Error) {\n if (\"isAxiosError\" in err) {\n /* @ts-ignore */\n const data = await asyncIterableToArray(err.response.data);\n const error = JSON.parse(data.toString()).error;\n throw new ApiError(error);",
"score": 32.71227375458592
},
{
"filename": "src/executePrompt.ts",
"retrieved_chunk": " }\n const stream = openAIQuery(model, formattedPrompt, config);\n const chunks = [];\n for await (const chunk of stream) {\n chunks.push(chunk);\n yield chunk;\n }\n if (cache) {\n const response = chunks.join(\"\");\n await cache.set(cacheKey, response);",
"score": 30.831528535464344
},
{
"filename": "src/openai.ts",
"retrieved_chunk": " }\n }\n throw err;\n }\n })();\n /* @ts-ignore */\n const stream = res.data as IncomingMessage;\n for await (const chunk of chunksToLines(stream)) {\n const data = JSON.parse(chunk);\n const content = data.choices[0].delta.content;",
"score": 29.785438346244806
},
{
"filename": "src/errors.ts",
"retrieved_chunk": "}\nexport class AppError extends Error {\n cause?: Error;\n exitCode = 1;\n private static wrap(err: unknown) {\n // We don't wrap errors that indicate unexpected/programming errors\n if (isProgrammingError(err)) {\n return err;\n }\n const cause = err instanceof Error ? err : undefined;",
"score": 21.778149767458377
},
{
"filename": "src/loadPromptConfig.ts",
"retrieved_chunk": " .filter((f) => f.endsWith(\".js\") || f.endsWith(\".mjs\"))\n .map((filename) => pathJoin(path, filename));\n } catch (err) {\n if (err instanceof Error && \"code\" in err) {\n if (err.code == \"ENOENT\") {\n // ignore error: ENOENT: no such file or directory\n return [];\n }\n }\n throw err;",
"score": 20.886783590642608
}
] | typescript | .error(err.toString()); |
import { executePrompt, executePromptStream } from "./executePrompt.js";
import { loadConfig } from "./config.js";
import { loadPromptConfig, listPrompts } from "./loadPromptConfig.js";
import { APPNAME } from "./types.js";
import FileSystemKVS from "./kvs/kvs-filesystem.js";
import { AppError } from "./errors.js";
import { readFileSync } from "node:fs";
function parseArgs(argv: string[]) {
const [_nodeBin, _jsFile, promptId, ...rest] = argv;
const input = rest.join(" ");
return { promptId, input };
}
function printUsageAndExit() {
console.log("Usage:");
console.log(`$ ${APPNAME} <promptType> <input>`);
console.log(`$ ${APPNAME} --list`);
console.log("");
console.log("Example: ");
console.log("");
console.log(`$ ${APPNAME} eli5 "what are large language models?"`);
process.exit(1);
}
function getInput(argvInput: string) {
try {
const stdinInput = readFileSync(process.stdin.fd, "utf-8");
// console.log({ stdinInput });
return `${argvInput} ${stdinInput}`;
} catch (err) {
return argvInput;
}
}
export async function cli() {
try {
const config = loadConfig();
const { promptId, input: argvInput } = parseArgs(process.argv);
if (promptId === "--list") {
const prompts = await listPrompts(config);
console.log(
prompts
.map((p) => {
const description = p.description ? `: ${p.description}` : "";
return `${p.name}${description}`;
})
.join("\n")
);
return;
} else if (promptId && promptId.startsWith("--")) {
printUsageAndExit();
}
const input = getInput(argvInput);
if (!promptId || !input) {
printUsageAndExit();
}
| const promptConfig = await loadPromptConfig(promptId, config); |
const cache = config.useCache
? new FileSystemKVS({ baseDir: config.paths.cache })
: undefined;
const stream = executePromptStream(promptConfig, input, config, cache);
for await (const chunk of stream) {
process.stdout.write(chunk);
}
process.stdout.write("\n");
} catch (err) {
if (err instanceof AppError) {
console.error(err.toString());
process.exit(err.exitCode);
}
console.error(err);
process.exit(1);
}
}
export default cli;
| src/index.ts | clevercli-clevercli-c660fae | [
{
"filename": "src/loadPromptConfig.ts",
"retrieved_chunk": "export async function loadFromPath(path: string) {\n const promptConfig = await import(path);\n // TODO: validate promptConfig?\n return promptConfig.default;\n}\nexport async function loadPromptConfig(promptId: string, config: Config) {\n try {\n const promptConfig = await Promise.any([\n loadFromPath(sourceRelativePath(import.meta, `./prompts/${promptId}.js`)),\n loadFromPath(pathJoin(config.paths.data, `${promptId}.mjs`)),",
"score": 31.171826785745974
},
{
"filename": "src/loadPromptConfig.ts",
"retrieved_chunk": " ]);\n return promptConfig;\n } catch (err) {\n throw new AppError({\n message: `Could not find prompt ${promptId}. Are you sure it is a builtin prompt or that ${config.paths.data}/${promptId}.mjs exists?`,\n });\n }\n}\nexport async function listPrompts(config: Config) {\n const [localFiles, builtinFiles] = await Promise.all(",
"score": 22.974751539472024
},
{
"filename": "src/executePrompt.ts",
"retrieved_chunk": "): AsyncGenerator<string> {\n const model = toModel(promptConfig);\n const formattedPrompt = promptConfig.createPrompt(input);\n const cacheKey = `${model.id}-${formattedPrompt}`;\n if (cache) {\n const cachedResponse = await cache.get(cacheKey);\n if (cachedResponse) {\n yield cachedResponse;\n return;\n }",
"score": 13.662491307816126
},
{
"filename": "src/executePrompt.ts",
"retrieved_chunk": " const response = (\n await asyncIterableToArray(\n executePromptStream(promptConfig, input, config, cache)\n )\n ).join(\"\");\n return parseResponse(response, input);\n}\nexport default executePrompt;",
"score": 11.787096621138799
},
{
"filename": "src/executePrompt.ts",
"retrieved_chunk": " }\n}\nexport async function executePrompt(\n promptConfig: PromptConfiguration,\n input: string,\n config: Config,\n cache?: KeyValueStore<string, string>\n): Promise<ParsedResponse> {\n const model = toModel(promptConfig);\n const parseResponse = promptConfig.parseResponse ?? defaultParseResponse;",
"score": 9.798205241426924
}
] | typescript | const promptConfig = await loadPromptConfig(promptId, config); |
import {
ChatCompletionRequestMessageRoleEnum,
Configuration as OpenAIConfiguration,
OpenAIApi,
} from "openai";
import models, { defaultModel } from "./openaiModels.js";
import { ApiError, AppError } from "./errors.js";
import { Config, Model, ParsedResponse, PromptConfiguration } from "./types.js";
import KeyValueStore from "./kvs/abstract.js";
import { openAIQuery } from "./openai.js";
import { asyncIterableToArray } from "./utils.js";
function defaultParseResponse(content: string, _input: string): ParsedResponse {
return { message: content };
}
function toModel(promptConfig: PromptConfiguration): Model {
const model = promptConfig.model
? models.get(promptConfig.model)
: defaultModel;
if (!model) {
throw new AppError({
message: `Could not find model "${promptConfig.model}"`,
});
}
return model;
}
export async function* executePromptStream(
promptConfig: PromptConfiguration,
input: string,
config: Config,
cache?: KeyValueStore<string, string>
): AsyncGenerator<string> {
const model = toModel(promptConfig);
const formattedPrompt = promptConfig.createPrompt(input);
const cacheKey = `${model.id}-${formattedPrompt}`;
if (cache) {
const cachedResponse = await cache.get(cacheKey);
if (cachedResponse) {
yield cachedResponse;
return;
}
}
const stream = openAIQuery(model, formattedPrompt, config);
const chunks = [];
for await (const chunk of stream) {
chunks.push(chunk);
yield chunk;
}
if (cache) {
const response = chunks.join("");
await cache.set(cacheKey, response);
}
}
export async function executePrompt(
promptConfig: PromptConfiguration,
input: string,
config: Config,
cache?: KeyValueStore<string, string>
): Promise<ParsedResponse> {
const model = toModel(promptConfig);
const parseResponse = promptConfig.parseResponse ?? defaultParseResponse;
const response = (
| await asyncIterableToArray(
executePromptStream(promptConfig, input, config, cache)
)
).join(""); |
return parseResponse(response, input);
}
export default executePrompt;
| src/executePrompt.ts | clevercli-clevercli-c660fae | [
{
"filename": "src/index.ts",
"retrieved_chunk": " if (!promptId || !input) {\n printUsageAndExit();\n }\n const promptConfig = await loadPromptConfig(promptId, config);\n const cache = config.useCache\n ? new FileSystemKVS({ baseDir: config.paths.cache })\n : undefined;\n const stream = executePromptStream(promptConfig, input, config, cache);\n for await (const chunk of stream) {\n process.stdout.write(chunk);",
"score": 35.6864963428596
},
{
"filename": "src/loadPromptConfig.ts",
"retrieved_chunk": "export async function loadFromPath(path: string) {\n const promptConfig = await import(path);\n // TODO: validate promptConfig?\n return promptConfig.default;\n}\nexport async function loadPromptConfig(promptId: string, config: Config) {\n try {\n const promptConfig = await Promise.any([\n loadFromPath(sourceRelativePath(import.meta, `./prompts/${promptId}.js`)),\n loadFromPath(pathJoin(config.paths.data, `${promptId}.mjs`)),",
"score": 27.652777380441062
},
{
"filename": "src/types.ts",
"retrieved_chunk": " id: string;\n type: ModelType;\n maxTokens: number;\n}\nexport interface PromptConfiguration {\n createPrompt(input: string): string;\n parseResponse?(response: string, input: string): ParsedResponse;\n model?: string;\n description?: string;\n}",
"score": 20.26148281963682
},
{
"filename": "src/prompts/ask.ts",
"retrieved_chunk": "import { ParsedResponse, PromptConfiguration } from \"../types.js\";\nconst promptConfiguration: PromptConfiguration = {\n description: \"Just passes through the input directly to ChatGPT.\",\n createPrompt(input: string) {\n return input;\n },\n parseResponse(response: string, _input: string): ParsedResponse {\n return { message: response };\n },\n};",
"score": 19.570018840440518
},
{
"filename": "src/loadPromptConfig.ts",
"retrieved_chunk": " ]);\n return promptConfig;\n } catch (err) {\n throw new AppError({\n message: `Could not find prompt ${promptId}. Are you sure it is a builtin prompt or that ${config.paths.data}/${promptId}.mjs exists?`,\n });\n }\n}\nexport async function listPrompts(config: Config) {\n const [localFiles, builtinFiles] = await Promise.all(",
"score": 17.743077339207094
}
] | typescript | await asyncIterableToArray(
executePromptStream(promptConfig, input, config, cache)
)
).join(""); |
import { Config } from "./types.js";
import { join as pathJoin } from "node:path";
import { AppError } from "./errors.js";
import { fileURLToPath } from "node:url";
import { dirname, parse } from "node:path";
import { readdir } from "node:fs/promises";
async function readFilesInDirectory(path: string) {
try {
const files = await readdir(path);
return files
.filter((f) => f.endsWith(".js") || f.endsWith(".mjs"))
.map((filename) => pathJoin(path, filename));
} catch (err) {
if (err instanceof Error && "code" in err) {
if (err.code == "ENOENT") {
// ignore error: ENOENT: no such file or directory
return [];
}
}
throw err;
}
}
// Returns a path relative to import.meta.filename
export function sourceRelativePath(
meta: { url: string },
...relPaths: string[]
) {
const __dirname = dirname(fileURLToPath(meta.url));
return pathJoin(__dirname, ...relPaths);
}
export async function loadFromPath(path: string) {
const promptConfig = await import(path);
// TODO: validate promptConfig?
return promptConfig.default;
}
export async function loadPromptConfig(promptId | : string, config: Config) { |
try {
const promptConfig = await Promise.any([
loadFromPath(sourceRelativePath(import.meta, `./prompts/${promptId}.js`)),
loadFromPath(pathJoin(config.paths.data, `${promptId}.mjs`)),
]);
return promptConfig;
} catch (err) {
throw new AppError({
message: `Could not find prompt ${promptId}. Are you sure it is a builtin prompt or that ${config.paths.data}/${promptId}.mjs exists?`,
});
}
}
export async function listPrompts(config: Config) {
const [localFiles, builtinFiles] = await Promise.all(
[
sourceRelativePath(import.meta, `./prompts`),
pathJoin(config.paths.data),
].map(readFilesInDirectory)
);
const allFiles = [...localFiles, ...builtinFiles];
const allPromptConfigs = await Promise.all(allFiles.map(loadFromPath));
return allPromptConfigs.map((config, i) => {
const name = parse(allFiles[i]).name;
return {
name,
description: config.description,
};
});
}
| src/loadPromptConfig.ts | clevercli-clevercli-c660fae | [
{
"filename": "src/executePrompt.ts",
"retrieved_chunk": " }\n}\nexport async function executePrompt(\n promptConfig: PromptConfiguration,\n input: string,\n config: Config,\n cache?: KeyValueStore<string, string>\n): Promise<ParsedResponse> {\n const model = toModel(promptConfig);\n const parseResponse = promptConfig.parseResponse ?? defaultParseResponse;",
"score": 26.62961515787965
},
{
"filename": "src/executePrompt.ts",
"retrieved_chunk": " message: `Could not find model \"${promptConfig.model}\"`,\n });\n }\n return model;\n}\nexport async function* executePromptStream(\n promptConfig: PromptConfiguration,\n input: string,\n config: Config,\n cache?: KeyValueStore<string, string>",
"score": 25.03631715354707
},
{
"filename": "src/index.ts",
"retrieved_chunk": " if (!promptId || !input) {\n printUsageAndExit();\n }\n const promptConfig = await loadPromptConfig(promptId, config);\n const cache = config.useCache\n ? new FileSystemKVS({ baseDir: config.paths.cache })\n : undefined;\n const stream = executePromptStream(promptConfig, input, config, cache);\n for await (const chunk of stream) {\n process.stdout.write(chunk);",
"score": 21.695262534519085
},
{
"filename": "src/executePrompt.ts",
"retrieved_chunk": "import { asyncIterableToArray } from \"./utils.js\";\nfunction defaultParseResponse(content: string, _input: string): ParsedResponse {\n return { message: content };\n}\nfunction toModel(promptConfig: PromptConfiguration): Model {\n const model = promptConfig.model\n ? models.get(promptConfig.model)\n : defaultModel;\n if (!model) {\n throw new AppError({",
"score": 20.346312191284724
},
{
"filename": "src/executePrompt.ts",
"retrieved_chunk": "): AsyncGenerator<string> {\n const model = toModel(promptConfig);\n const formattedPrompt = promptConfig.createPrompt(input);\n const cacheKey = `${model.id}-${formattedPrompt}`;\n if (cache) {\n const cachedResponse = await cache.get(cacheKey);\n if (cachedResponse) {\n yield cachedResponse;\n return;\n }",
"score": 16.874091568401532
}
] | typescript | : string, config: Config) { |
import { ext, generateMessageId, handleCrxRpcRequest, wait } from '../lib/messaging';
import { getJoyconDevice, getNextStrain, getStrain, setupJoycon } from '../lib/ring-con';
injectResourceScript('js/nip07-provider.js');
// 'nip07-provider' -> ...
window.addEventListener('message', async ({ data }: MessageEvent<CrxRpcRequestMessage>) => {
const { next, shouldBeHandled } = handleCrxRpcRequest(data, 'content');
if (!shouldBeHandled) {
return;
}
if (next === 'background') {
// ... -> HERE -> 'background'
const response: CrxRpcResponseMessage = await chrome.runtime.sendMessage(data);
window.postMessage(response);
return;
} else if (!!next) {
console.warn('Unexpected message', data);
return;
}
//... -> HERE
switch (data.payload.kind) {
case 'enterChargeMode':
{
try {
const response = await enterChargeMode(data);
window.postMessage(response);
} catch (err) {
console.error(err);
window.postMessage({
ext,
messageId: data.messageId,
payload: {
kind: 'enterChargeMode',
response: false,
},
});
throw err;
}
}
break;
default:
break;
}
});
async function enterChargeMode({
messageId,
payload,
}: CrxRpcRequestMessage): Promise<CrxRpcResponseMessage> {
if (payload.kind !== 'enterChargeMode') {
throw 'Unexpected message';
}
const openChargeWindowReq: CrxRpcMessage = {
ext,
messageId: generateMessageId(),
src: 'content',
path: ['background'],
payload: {
kind: 'openChargeWindow',
request: {},
},
};
const { payload: result }: CrxRpcResponseMessage = await chrome.runtime.sendMessage(
openChargeWindowReq,
);
if (result.kind !== 'openChargeWindow') {
throw 'Unexpected message';
}
// Keep sending strain signals.
| const joycon = await getJoyconDevice(); |
await setupJoycon(joycon);
const neutral = await getNextStrain(joycon);
const sendStrain = (value: number) => {
const req: CrxRpcMessage = {
ext,
messageId: generateMessageId(),
src: 'content',
path: ['charge'],
payload: {
kind: 'sendStrain',
request: {
value,
neutral,
},
},
};
chrome.runtime.sendMessage(req);
};
const reportListener = (ev: HIDInputReportEvent) => {
const value = getStrain(ev);
if (value) {
sendStrain(value);
}
};
joycon.addEventListener('inputreport', reportListener);
// Wait for `leaveChargeMode` signal.
await wait<CrxRpcRequestMessage, void>(
(resolve) => (msg) => {
const { next, shouldBeHandled } = handleCrxRpcRequest(msg, 'content');
if (!shouldBeHandled) {
return;
}
if (!!next) {
console.warn('Unexpected message', msg);
return;
}
if (msg.payload.kind === 'leaveChargeMode') {
resolve();
}
},
{
addEventListener: (listener) => {
chrome.runtime.onMessage.addListener(listener);
},
removeEventListener: (listener) => {
chrome.runtime.onMessage.removeListener(listener);
},
},
);
// Stop sending strain signals.
joycon.removeEventListener('inputreport', reportListener);
return {
ext,
messageId,
payload: {
kind: 'enterChargeMode',
response: true,
},
};
}
function injectResourceScript(path: string) {
const script = document.createElement('script');
script.setAttribute('async', 'false');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', chrome.runtime.getURL(path));
document.head.appendChild(script);
}
| src/content/index.ts | penpenpng-nostronger-851a990 | [
{
"filename": "src/background/index.ts",
"retrieved_chunk": " if (next === 'content' && payload.kind === 'leaveChargeMode') {\n chrome.tabs.sendMessage(payload.request.senderTabId, msg);\n return;\n } else if (!!next) {\n console.warn('Unexpected message', msg);\n return;\n }\n const sendResponse = (val: any) => {\n const res: CrxRpcResponseMessage = {\n ...msg,",
"score": 19.210732427088956
},
{
"filename": "src/lib/ring-con.ts",
"retrieved_chunk": " return wait<HIDInputReportEvent, number>(\n (resolve) => (event) => {\n const strain = getStrain(event);\n if (strain) {\n resolve(strain);\n }\n },\n {\n addEventListener: (listener) => joycon.addEventListener('inputreport', listener),\n removeEventListener: (listener) => joycon.removeEventListener('inputreport', listener),",
"score": 10.620354804500328
},
{
"filename": "src/background/index.ts",
"retrieved_chunk": " case 'openChargeWindow':\n chrome.windows\n .create({\n url: chrome.runtime.getURL('charge.html'),\n type: 'popup',\n })\n .then((res) => {\n const tabId = res.tabs?.[0].id;\n sendResponse(tabId);\n });",
"score": 10.582412007677071
},
{
"filename": "src/lib/ring-con.ts",
"retrieved_chunk": " if (!device) {\n throw new Error('device not found.');\n }\n if (!device.opened) {\n await device.open();\n }\n await setupJoycon(device);\n return device;\n}\nexport async function setupJoycon(joycon: HIDDevice) {",
"score": 10.498411892563515
},
{
"filename": "src/lib/nostr.ts",
"retrieved_chunk": " result.push((value << (outBits - bits)) & maxV);\n }\n } else {\n if (bits >= inBits) return 'Excess padding';\n if ((value << (outBits - bits)) & maxV) return 'Non-zero padding';\n }\n return result;\n}\nexport function isValidHex(hex: string): boolean {\n return /^[a-f0-9]{64}$/.test(hex);",
"score": 8.483615692354299
}
] | typescript | const joycon = await getJoyconDevice(); |
import { handleCrxRpcRequest } from '../lib/messaging';
import { signEvent } from '../lib/nostr';
import { getKeyPair, getSignPower, setSignPower } from '../lib/store';
// * -> ...
chrome.runtime.onMessage.addListener((msg: CrxRpcRequestMessage, sender, _sendResponse) => {
const { next, shouldBeHandled } = handleCrxRpcRequest(msg, 'background');
if (!shouldBeHandled) {
return;
}
const payload = msg.payload;
if (next === 'content' && payload.kind === 'leaveChargeMode') {
chrome.tabs.sendMessage(payload.request.senderTabId, msg);
return;
} else if (!!next) {
console.warn('Unexpected message', msg);
return;
}
const sendResponse = (val: any) => {
const res: CrxRpcResponseMessage = {
...msg,
payload: {
kind: payload.kind,
response: val,
},
};
_sendResponse(res);
};
// ... -> HERE
switch (payload.kind) {
case 'getPubkey':
getKeyPair().then(({ pubkey }) => {
sendResponse(pubkey);
});
return true; // For async response
case 'signEvent':
| getKeyPair().then(async (keypair) => { |
const signed = await signEvent(keypair, payload.request);
sendResponse(signed);
});
return true;
case 'getSignPower':
getSignPower().then((power) => {
sendResponse(power);
});
return true;
case 'setSignPower':
setSignPower(payload.request.value).then(() => {
sendResponse(void 0);
});
return true;
case 'openChargeWindow':
chrome.windows
.create({
url: chrome.runtime.getURL('charge.html'),
type: 'popup',
})
.then((res) => {
const tabId = res.tabs?.[0].id;
sendResponse(tabId);
});
return true;
default:
break;
}
});
| src/background/index.ts | penpenpng-nostronger-851a990 | [
{
"filename": "src/lib/store.ts",
"retrieved_chunk": " await chrome.storage.local.set({ [key]: val });\n}\nexport async function getKeyPair(): Promise<KeyPair> {\n const { seckey, pubkey } = await get(LOCAL_STORAGE_KEY.KEY_PAIR);\n return { seckey, pubkey };\n}\nexport async function setKeyPair(seckey: string) {\n const pubkey = await calcPubkey(seckey);\n await set(LOCAL_STORAGE_KEY.KEY_PAIR, { seckey, pubkey });\n}",
"score": 17.818132494497227
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " // ... -> HERE -> 'background'\n const response: CrxRpcResponseMessage = await chrome.runtime.sendMessage(data);\n window.postMessage(response);\n return;\n } else if (!!next) {\n console.warn('Unexpected message', data);\n return;\n }\n //... -> HERE\n switch (data.payload.kind) {",
"score": 13.60204165480462
},
{
"filename": "src/@types/common/index.d.ts",
"retrieved_chunk": " kind: 'getPubkey';\n request: {};\n response: string;\n }\n | {\n // possible paths:\n // - 'nip07-provider' -> 'content' -> 'background'\n kind: 'signEvent';\n request: UnsignedEvent;\n response: SignedEvent;",
"score": 10.285854730424855
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " case 'enterChargeMode':\n {\n try {\n const response = await enterChargeMode(data);\n window.postMessage(response);\n } catch (err) {\n console.error(err);\n window.postMessage({\n ext,\n messageId: data.messageId,",
"score": 10.195406925186745
},
{
"filename": "src/lib/nostr.ts",
"retrieved_chunk": "import * as secp256k1 from '@noble/secp256k1';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { bech32 } from 'bech32';\nconst utf8Encoder = new TextEncoder();\nsecp256k1.utils.sha256Sync = (...msgs) => sha256(secp256k1.utils.concatBytes(...msgs));\nexport async function calcPubkey(seckey: string): Promise<string> {\n return secp256k1.utils.bytesToHex(secp256k1.schnorr.getPublicKey(seckey));\n}\nexport async function signEvent(\n { seckey, pubkey }: KeyPair,",
"score": 8.485508228138956
}
] | typescript | getKeyPair().then(async (keypair) => { |
import { handleCrxRpcRequest } from '../lib/messaging';
import { signEvent } from '../lib/nostr';
import { getKeyPair, getSignPower, setSignPower } from '../lib/store';
// * -> ...
chrome.runtime.onMessage.addListener((msg: CrxRpcRequestMessage, sender, _sendResponse) => {
const { next, shouldBeHandled } = handleCrxRpcRequest(msg, 'background');
if (!shouldBeHandled) {
return;
}
const payload = msg.payload;
if (next === 'content' && payload.kind === 'leaveChargeMode') {
chrome.tabs.sendMessage(payload.request.senderTabId, msg);
return;
} else if (!!next) {
console.warn('Unexpected message', msg);
return;
}
const sendResponse = (val: any) => {
const res: CrxRpcResponseMessage = {
...msg,
payload: {
kind: payload.kind,
response: val,
},
};
_sendResponse(res);
};
// ... -> HERE
switch (payload.kind) {
case 'getPubkey':
getKeyPair().then(({ pubkey }) => {
sendResponse(pubkey);
});
return true; // For async response
case 'signEvent':
getKeyPair().then(async (keypair) => {
const signed = await | signEvent(keypair, payload.request); |
sendResponse(signed);
});
return true;
case 'getSignPower':
getSignPower().then((power) => {
sendResponse(power);
});
return true;
case 'setSignPower':
setSignPower(payload.request.value).then(() => {
sendResponse(void 0);
});
return true;
case 'openChargeWindow':
chrome.windows
.create({
url: chrome.runtime.getURL('charge.html'),
type: 'popup',
})
.then((res) => {
const tabId = res.tabs?.[0].id;
sendResponse(tabId);
});
return true;
default:
break;
}
});
| src/background/index.ts | penpenpng-nostronger-851a990 | [
{
"filename": "src/lib/store.ts",
"retrieved_chunk": " await chrome.storage.local.set({ [key]: val });\n}\nexport async function getKeyPair(): Promise<KeyPair> {\n const { seckey, pubkey } = await get(LOCAL_STORAGE_KEY.KEY_PAIR);\n return { seckey, pubkey };\n}\nexport async function setKeyPair(seckey: string) {\n const pubkey = await calcPubkey(seckey);\n await set(LOCAL_STORAGE_KEY.KEY_PAIR, { seckey, pubkey });\n}",
"score": 20.01271745177093
},
{
"filename": "src/@types/common/index.d.ts",
"retrieved_chunk": " kind: 'getPubkey';\n request: {};\n response: string;\n }\n | {\n // possible paths:\n // - 'nip07-provider' -> 'content' -> 'background'\n kind: 'signEvent';\n request: UnsignedEvent;\n response: SignedEvent;",
"score": 15.43600516029743
},
{
"filename": "src/resource/nip07-provider.ts",
"retrieved_chunk": " },\n async signEvent(event: UnsignedEvent): Promise<SignedEvent | undefined> {\n let signPower = await rpc(\n {\n kind: 'getSignPower',\n request: {},\n },\n ['content', 'background'],\n );\n if (signPower <= 0) {",
"score": 12.693331142311196
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " case 'enterChargeMode':\n {\n try {\n const response = await enterChargeMode(data);\n window.postMessage(response);\n } catch (err) {\n console.error(err);\n window.postMessage({\n ext,\n messageId: data.messageId,",
"score": 11.68716081009935
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " // ... -> HERE -> 'background'\n const response: CrxRpcResponseMessage = await chrome.runtime.sendMessage(data);\n window.postMessage(response);\n return;\n } else if (!!next) {\n console.warn('Unexpected message', data);\n return;\n }\n //... -> HERE\n switch (data.payload.kind) {",
"score": 11.146483968071767
}
] | typescript | signEvent(keypair, payload.request); |
import { executePrompt, executePromptStream } from "./executePrompt.js";
import { loadConfig } from "./config.js";
import { loadPromptConfig, listPrompts } from "./loadPromptConfig.js";
import { APPNAME } from "./types.js";
import FileSystemKVS from "./kvs/kvs-filesystem.js";
import { AppError } from "./errors.js";
import { readFileSync } from "node:fs";
function parseArgs(argv: string[]) {
const [_nodeBin, _jsFile, promptId, ...rest] = argv;
const input = rest.join(" ");
return { promptId, input };
}
function printUsageAndExit() {
console.log("Usage:");
console.log(`$ ${APPNAME} <promptType> <input>`);
console.log(`$ ${APPNAME} --list`);
console.log("");
console.log("Example: ");
console.log("");
console.log(`$ ${APPNAME} eli5 "what are large language models?"`);
process.exit(1);
}
function getInput(argvInput: string) {
try {
const stdinInput = readFileSync(process.stdin.fd, "utf-8");
// console.log({ stdinInput });
return `${argvInput} ${stdinInput}`;
} catch (err) {
return argvInput;
}
}
export async function cli() {
try {
const config = loadConfig();
const { promptId, input: argvInput } = parseArgs(process.argv);
if (promptId === "--list") {
const prompts = await listPrompts(config);
console.log(
prompts
.map((p) => {
const description = p.description ? `: ${p.description}` : "";
return `${p.name}${description}`;
})
.join("\n")
);
return;
} else if (promptId && promptId.startsWith("--")) {
printUsageAndExit();
}
const input = getInput(argvInput);
if (!promptId || !input) {
printUsageAndExit();
}
const promptConfig = await loadPromptConfig(promptId, config);
const cache = config.useCache
? new FileSystemKVS({ baseDir: config.paths.cache })
: undefined;
| const stream = executePromptStream(promptConfig, input, config, cache); |
for await (const chunk of stream) {
process.stdout.write(chunk);
}
process.stdout.write("\n");
} catch (err) {
if (err instanceof AppError) {
console.error(err.toString());
process.exit(err.exitCode);
}
console.error(err);
process.exit(1);
}
}
export default cli;
| src/index.ts | clevercli-clevercli-c660fae | [
{
"filename": "src/executePrompt.ts",
"retrieved_chunk": " const response = (\n await asyncIterableToArray(\n executePromptStream(promptConfig, input, config, cache)\n )\n ).join(\"\");\n return parseResponse(response, input);\n}\nexport default executePrompt;",
"score": 34.355011078073446
},
{
"filename": "src/loadPromptConfig.ts",
"retrieved_chunk": "export async function loadFromPath(path: string) {\n const promptConfig = await import(path);\n // TODO: validate promptConfig?\n return promptConfig.default;\n}\nexport async function loadPromptConfig(promptId: string, config: Config) {\n try {\n const promptConfig = await Promise.any([\n loadFromPath(sourceRelativePath(import.meta, `./prompts/${promptId}.js`)),\n loadFromPath(pathJoin(config.paths.data, `${promptId}.mjs`)),",
"score": 33.49020232534479
},
{
"filename": "src/executePrompt.ts",
"retrieved_chunk": " }\n}\nexport async function executePrompt(\n promptConfig: PromptConfiguration,\n input: string,\n config: Config,\n cache?: KeyValueStore<string, string>\n): Promise<ParsedResponse> {\n const model = toModel(promptConfig);\n const parseResponse = promptConfig.parseResponse ?? defaultParseResponse;",
"score": 28.463246070841922
},
{
"filename": "src/config.ts",
"retrieved_chunk": " apiKey: getEnvOrThrow(\"OPENAI_API_KEY\"),\n },\n paths: {\n data: pathJoin(homedir(), `.${APPNAME}`),\n cache: paths.cache,\n },\n useCache: true,\n };\n debug(config);\n return config;",
"score": 27.82578463864333
},
{
"filename": "src/executePrompt.ts",
"retrieved_chunk": " }\n const stream = openAIQuery(model, formattedPrompt, config);\n const chunks = [];\n for await (const chunk of stream) {\n chunks.push(chunk);\n yield chunk;\n }\n if (cache) {\n const response = chunks.join(\"\");\n await cache.set(cacheKey, response);",
"score": 27.06405007241286
}
] | typescript | const stream = executePromptStream(promptConfig, input, config, cache); |
import { executePrompt, executePromptStream } from "./executePrompt.js";
import { loadConfig } from "./config.js";
import { loadPromptConfig, listPrompts } from "./loadPromptConfig.js";
import { APPNAME } from "./types.js";
import FileSystemKVS from "./kvs/kvs-filesystem.js";
import { AppError } from "./errors.js";
import { readFileSync } from "node:fs";
function parseArgs(argv: string[]) {
const [_nodeBin, _jsFile, promptId, ...rest] = argv;
const input = rest.join(" ");
return { promptId, input };
}
function printUsageAndExit() {
console.log("Usage:");
console.log(`$ ${APPNAME} <promptType> <input>`);
console.log(`$ ${APPNAME} --list`);
console.log("");
console.log("Example: ");
console.log("");
console.log(`$ ${APPNAME} eli5 "what are large language models?"`);
process.exit(1);
}
function getInput(argvInput: string) {
try {
const stdinInput = readFileSync(process.stdin.fd, "utf-8");
// console.log({ stdinInput });
return `${argvInput} ${stdinInput}`;
} catch (err) {
return argvInput;
}
}
export async function cli() {
try {
const config = loadConfig();
const { promptId, input: argvInput } = parseArgs(process.argv);
if (promptId === "--list") {
const prompts = await listPrompts(config);
console.log(
prompts
.map((p) => {
const description = p.description ? `: ${p.description}` : "";
return `${p.name}${description}`;
})
.join("\n")
);
return;
} else if (promptId && promptId.startsWith("--")) {
printUsageAndExit();
}
const input = getInput(argvInput);
if (!promptId || !input) {
printUsageAndExit();
}
const promptConfig = await loadPromptConfig(promptId, config);
const cache = config.useCache
? new FileSystemKVS({ baseDir: config.paths.cache })
: undefined;
const stream = executePromptStream(promptConfig, input, config, cache);
for await (const chunk of stream) {
process.stdout.write(chunk);
}
process.stdout.write("\n");
} catch (err) {
if (err instanceof AppError) {
| console.error(err.toString()); |
process.exit(err.exitCode);
}
console.error(err);
process.exit(1);
}
}
export default cli;
| src/index.ts | clevercli-clevercli-c660fae | [
{
"filename": "src/executePrompt.ts",
"retrieved_chunk": " }\n const stream = openAIQuery(model, formattedPrompt, config);\n const chunks = [];\n for await (const chunk of stream) {\n chunks.push(chunk);\n yield chunk;\n }\n if (cache) {\n const response = chunks.join(\"\");\n await cache.set(cacheKey, response);",
"score": 35.28573263078114
},
{
"filename": "src/openai.ts",
"retrieved_chunk": " return await openai.createChatCompletion(opts, {\n responseType: \"stream\",\n });\n } catch (err) {\n if (err instanceof Error) {\n if (\"isAxiosError\" in err) {\n /* @ts-ignore */\n const data = await asyncIterableToArray(err.response.data);\n const error = JSON.parse(data.toString()).error;\n throw new ApiError(error);",
"score": 34.05246168705873
},
{
"filename": "src/openai.ts",
"retrieved_chunk": " }\n }\n throw err;\n }\n })();\n /* @ts-ignore */\n const stream = res.data as IncomingMessage;\n for await (const chunk of chunksToLines(stream)) {\n const data = JSON.parse(chunk);\n const content = data.choices[0].delta.content;",
"score": 29.785438346244806
},
{
"filename": "src/errors.ts",
"retrieved_chunk": "}\nexport class AppError extends Error {\n cause?: Error;\n exitCode = 1;\n private static wrap(err: unknown) {\n // We don't wrap errors that indicate unexpected/programming errors\n if (isProgrammingError(err)) {\n return err;\n }\n const cause = err instanceof Error ? err : undefined;",
"score": 21.778149767458377
},
{
"filename": "src/loadPromptConfig.ts",
"retrieved_chunk": " .filter((f) => f.endsWith(\".js\") || f.endsWith(\".mjs\"))\n .map((filename) => pathJoin(path, filename));\n } catch (err) {\n if (err instanceof Error && \"code\" in err) {\n if (err.code == \"ENOENT\") {\n // ignore error: ENOENT: no such file or directory\n return [];\n }\n }\n throw err;",
"score": 20.886783590642608
}
] | typescript | console.error(err.toString()); |
import { executePrompt, executePromptStream } from "./executePrompt.js";
import { loadConfig } from "./config.js";
import { loadPromptConfig, listPrompts } from "./loadPromptConfig.js";
import { APPNAME } from "./types.js";
import FileSystemKVS from "./kvs/kvs-filesystem.js";
import { AppError } from "./errors.js";
import { readFileSync } from "node:fs";
function parseArgs(argv: string[]) {
const [_nodeBin, _jsFile, promptId, ...rest] = argv;
const input = rest.join(" ");
return { promptId, input };
}
function printUsageAndExit() {
console.log("Usage:");
console.log(`$ ${APPNAME} <promptType> <input>`);
console.log(`$ ${APPNAME} --list`);
console.log("");
console.log("Example: ");
console.log("");
console.log(`$ ${APPNAME} eli5 "what are large language models?"`);
process.exit(1);
}
function getInput(argvInput: string) {
try {
const stdinInput = readFileSync(process.stdin.fd, "utf-8");
// console.log({ stdinInput });
return `${argvInput} ${stdinInput}`;
} catch (err) {
return argvInput;
}
}
export async function cli() {
try {
const config = loadConfig();
const { promptId, input: argvInput } = parseArgs(process.argv);
if (promptId === "--list") {
const prompts = await listPrompts(config);
console.log(
prompts
.map((p) => {
const description = p.description ? `: ${p.description}` : "";
return `${p.name}${description}`;
})
.join("\n")
);
return;
} else if (promptId && promptId.startsWith("--")) {
printUsageAndExit();
}
const input = getInput(argvInput);
if (!promptId || !input) {
printUsageAndExit();
}
const promptConfig = await | loadPromptConfig(promptId, config); |
const cache = config.useCache
? new FileSystemKVS({ baseDir: config.paths.cache })
: undefined;
const stream = executePromptStream(promptConfig, input, config, cache);
for await (const chunk of stream) {
process.stdout.write(chunk);
}
process.stdout.write("\n");
} catch (err) {
if (err instanceof AppError) {
console.error(err.toString());
process.exit(err.exitCode);
}
console.error(err);
process.exit(1);
}
}
export default cli;
| src/index.ts | clevercli-clevercli-c660fae | [
{
"filename": "src/loadPromptConfig.ts",
"retrieved_chunk": "export async function loadFromPath(path: string) {\n const promptConfig = await import(path);\n // TODO: validate promptConfig?\n return promptConfig.default;\n}\nexport async function loadPromptConfig(promptId: string, config: Config) {\n try {\n const promptConfig = await Promise.any([\n loadFromPath(sourceRelativePath(import.meta, `./prompts/${promptId}.js`)),\n loadFromPath(pathJoin(config.paths.data, `${promptId}.mjs`)),",
"score": 31.171826785745974
},
{
"filename": "src/loadPromptConfig.ts",
"retrieved_chunk": " ]);\n return promptConfig;\n } catch (err) {\n throw new AppError({\n message: `Could not find prompt ${promptId}. Are you sure it is a builtin prompt or that ${config.paths.data}/${promptId}.mjs exists?`,\n });\n }\n}\nexport async function listPrompts(config: Config) {\n const [localFiles, builtinFiles] = await Promise.all(",
"score": 22.974751539472024
},
{
"filename": "src/executePrompt.ts",
"retrieved_chunk": "): AsyncGenerator<string> {\n const model = toModel(promptConfig);\n const formattedPrompt = promptConfig.createPrompt(input);\n const cacheKey = `${model.id}-${formattedPrompt}`;\n if (cache) {\n const cachedResponse = await cache.get(cacheKey);\n if (cachedResponse) {\n yield cachedResponse;\n return;\n }",
"score": 13.662491307816126
},
{
"filename": "src/executePrompt.ts",
"retrieved_chunk": " const response = (\n await asyncIterableToArray(\n executePromptStream(promptConfig, input, config, cache)\n )\n ).join(\"\");\n return parseResponse(response, input);\n}\nexport default executePrompt;",
"score": 11.787096621138799
},
{
"filename": "src/executePrompt.ts",
"retrieved_chunk": " }\n}\nexport async function executePrompt(\n promptConfig: PromptConfiguration,\n input: string,\n config: Config,\n cache?: KeyValueStore<string, string>\n): Promise<ParsedResponse> {\n const model = toModel(promptConfig);\n const parseResponse = promptConfig.parseResponse ?? defaultParseResponse;",
"score": 9.798205241426924
}
] | typescript | loadPromptConfig(promptId, config); |
import { ext, generateMessageId, handleCrxRpcRequest, wait } from '../lib/messaging';
import { getJoyconDevice, getNextStrain, getStrain, setupJoycon } from '../lib/ring-con';
injectResourceScript('js/nip07-provider.js');
// 'nip07-provider' -> ...
window.addEventListener('message', async ({ data }: MessageEvent<CrxRpcRequestMessage>) => {
const { next, shouldBeHandled } = handleCrxRpcRequest(data, 'content');
if (!shouldBeHandled) {
return;
}
if (next === 'background') {
// ... -> HERE -> 'background'
const response: CrxRpcResponseMessage = await chrome.runtime.sendMessage(data);
window.postMessage(response);
return;
} else if (!!next) {
console.warn('Unexpected message', data);
return;
}
//... -> HERE
switch (data.payload.kind) {
case 'enterChargeMode':
{
try {
const response = await enterChargeMode(data);
window.postMessage(response);
} catch (err) {
console.error(err);
window.postMessage({
ext,
messageId: data.messageId,
payload: {
kind: 'enterChargeMode',
response: false,
},
});
throw err;
}
}
break;
default:
break;
}
});
async function enterChargeMode({
messageId,
payload,
}: CrxRpcRequestMessage): Promise<CrxRpcResponseMessage> {
if (payload.kind !== 'enterChargeMode') {
throw 'Unexpected message';
}
const openChargeWindowReq: CrxRpcMessage = {
ext,
messageId: generateMessageId(),
src: 'content',
path: ['background'],
payload: {
kind: 'openChargeWindow',
request: {},
},
};
const { payload: result }: CrxRpcResponseMessage = await chrome.runtime.sendMessage(
openChargeWindowReq,
);
if (result.kind !== 'openChargeWindow') {
throw 'Unexpected message';
}
// Keep sending strain signals.
const joycon = await getJoyconDevice();
await setupJoycon(joycon);
const neutral = await getNextStrain(joycon);
const sendStrain = (value: number) => {
const req: CrxRpcMessage = {
ext,
messageId: generateMessageId(),
src: 'content',
path: ['charge'],
payload: {
kind: 'sendStrain',
request: {
value,
neutral,
},
},
};
chrome.runtime.sendMessage(req);
};
const reportListener = (ev: HIDInputReportEvent) => {
const value | = getStrain(ev); |
if (value) {
sendStrain(value);
}
};
joycon.addEventListener('inputreport', reportListener);
// Wait for `leaveChargeMode` signal.
await wait<CrxRpcRequestMessage, void>(
(resolve) => (msg) => {
const { next, shouldBeHandled } = handleCrxRpcRequest(msg, 'content');
if (!shouldBeHandled) {
return;
}
if (!!next) {
console.warn('Unexpected message', msg);
return;
}
if (msg.payload.kind === 'leaveChargeMode') {
resolve();
}
},
{
addEventListener: (listener) => {
chrome.runtime.onMessage.addListener(listener);
},
removeEventListener: (listener) => {
chrome.runtime.onMessage.removeListener(listener);
},
},
);
// Stop sending strain signals.
joycon.removeEventListener('inputreport', reportListener);
return {
ext,
messageId,
payload: {
kind: 'enterChargeMode',
response: true,
},
};
}
function injectResourceScript(path: string) {
const script = document.createElement('script');
script.setAttribute('async', 'false');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', chrome.runtime.getURL(path));
document.head.appendChild(script);
}
| src/content/index.ts | penpenpng-nostronger-851a990 | [
{
"filename": "src/resource/nip07-provider.ts",
"retrieved_chunk": " const timeoutId = timeout\n ? setTimeout(() => {\n window.removeEventListener('message', listener);\n reject(`Request \\`${req.kind}\\` timed out`);\n }, timeout)\n : -1;\n function listener(ev: MessageEvent<CrxRpcResponseMessage>) {\n const data = ev.data;\n if (\n data.ext !== 'nostronger' ||",
"score": 13.512845465030061
},
{
"filename": "src/@types/common/index.d.ts",
"retrieved_chunk": " }\n | {\n // possible paths:\n // - 'content' -> 'charge'\n kind: 'sendStrain';\n request: {\n value: number;\n neutral: number;\n };\n response: void;",
"score": 9.92361224220594
},
{
"filename": "src/background/index.ts",
"retrieved_chunk": " case 'openChargeWindow':\n chrome.windows\n .create({\n url: chrome.runtime.getURL('charge.html'),\n type: 'popup',\n })\n .then((res) => {\n const tabId = res.tabs?.[0].id;\n sendResponse(tabId);\n });",
"score": 7.252834533997848
},
{
"filename": "src/lib/ring-con.ts",
"retrieved_chunk": " return wait<HIDInputReportEvent, number>(\n (resolve) => (event) => {\n const strain = getStrain(event);\n if (strain) {\n resolve(strain);\n }\n },\n {\n addEventListener: (listener) => joycon.addEventListener('inputreport', listener),\n removeEventListener: (listener) => joycon.removeEventListener('inputreport', listener),",
"score": 6.643154380996037
},
{
"filename": "src/lib/nostr.ts",
"retrieved_chunk": " for (let i = 0; i < data.length; ++i) {\n value = (value << inBits) | data[i];\n bits += inBits;\n while (bits >= outBits) {\n bits -= outBits;\n result.push((value >> bits) & maxV);\n }\n }\n if (pad) {\n if (bits > 0) {",
"score": 6.419865338508484
}
] | typescript | = getStrain(ev); |
import { handleCrxRpcRequest } from '../lib/messaging';
import { signEvent } from '../lib/nostr';
import { getKeyPair, getSignPower, setSignPower } from '../lib/store';
// * -> ...
chrome.runtime.onMessage.addListener((msg: CrxRpcRequestMessage, sender, _sendResponse) => {
const { next, shouldBeHandled } = handleCrxRpcRequest(msg, 'background');
if (!shouldBeHandled) {
return;
}
const payload = msg.payload;
if (next === 'content' && payload.kind === 'leaveChargeMode') {
chrome.tabs.sendMessage(payload.request.senderTabId, msg);
return;
} else if (!!next) {
console.warn('Unexpected message', msg);
return;
}
const sendResponse = (val: any) => {
const res: CrxRpcResponseMessage = {
...msg,
payload: {
kind: payload.kind,
response: val,
},
};
_sendResponse(res);
};
// ... -> HERE
switch (payload.kind) {
case 'getPubkey':
getKeyPair().then(({ pubkey }) => {
sendResponse(pubkey);
});
return true; // For async response
case 'signEvent':
getKeyPair().then(async (keypair) => {
const signed = await signEvent(keypair, payload.request);
sendResponse(signed);
});
return true;
case 'getSignPower':
getSignPower().then( | (power) => { |
sendResponse(power);
});
return true;
case 'setSignPower':
setSignPower(payload.request.value).then(() => {
sendResponse(void 0);
});
return true;
case 'openChargeWindow':
chrome.windows
.create({
url: chrome.runtime.getURL('charge.html'),
type: 'popup',
})
.then((res) => {
const tabId = res.tabs?.[0].id;
sendResponse(tabId);
});
return true;
default:
break;
}
});
| src/background/index.ts | penpenpng-nostronger-851a990 | [
{
"filename": "src/resource/nip07-provider.ts",
"retrieved_chunk": " },\n async signEvent(event: UnsignedEvent): Promise<SignedEvent | undefined> {\n let signPower = await rpc(\n {\n kind: 'getSignPower',\n request: {},\n },\n ['content', 'background'],\n );\n if (signPower <= 0) {",
"score": 17.97921425902564
},
{
"filename": "src/lib/store.ts",
"retrieved_chunk": "export async function getSignPower(): Promise<number> {\n const signPower = (await get(LOCAL_STORAGE_KEY.SIGN_POWER)) ?? 0;\n return Number(signPower) || 0;\n}\nexport async function setSignPower(signPower: number) {\n await set(LOCAL_STORAGE_KEY.SIGN_POWER, signPower);\n}",
"score": 11.855496437987671
},
{
"filename": "src/content/index.ts",
"retrieved_chunk": " case 'enterChargeMode':\n {\n try {\n const response = await enterChargeMode(data);\n window.postMessage(response);\n } catch (err) {\n console.error(err);\n window.postMessage({\n ext,\n messageId: data.messageId,",
"score": 11.68716081009935
},
{
"filename": "src/lib/messaging.ts",
"retrieved_chunk": " return {\n next,\n shouldBeHandled: true,\n };\n}",
"score": 11.160574959217106
},
{
"filename": "src/resource/nip07-provider.ts",
"retrieved_chunk": " await rpc(\n {\n kind: 'enterChargeMode',\n request: {},\n },\n ['content'],\n );\n signPower = await rpc(\n {\n kind: 'getSignPower',",
"score": 10.942161115807782
}
] | typescript | (power) => { |
import { ext, generateMessageId, handleCrxRpcRequest, wait } from '../lib/messaging';
import { getJoyconDevice, getNextStrain, getStrain, setupJoycon } from '../lib/ring-con';
injectResourceScript('js/nip07-provider.js');
// 'nip07-provider' -> ...
window.addEventListener('message', async ({ data }: MessageEvent<CrxRpcRequestMessage>) => {
const { next, shouldBeHandled } = handleCrxRpcRequest(data, 'content');
if (!shouldBeHandled) {
return;
}
if (next === 'background') {
// ... -> HERE -> 'background'
const response: CrxRpcResponseMessage = await chrome.runtime.sendMessage(data);
window.postMessage(response);
return;
} else if (!!next) {
console.warn('Unexpected message', data);
return;
}
//... -> HERE
switch (data.payload.kind) {
case 'enterChargeMode':
{
try {
const response = await enterChargeMode(data);
window.postMessage(response);
} catch (err) {
console.error(err);
window.postMessage({
ext,
messageId: data.messageId,
payload: {
kind: 'enterChargeMode',
response: false,
},
});
throw err;
}
}
break;
default:
break;
}
});
async function enterChargeMode({
messageId,
payload,
}: CrxRpcRequestMessage): Promise<CrxRpcResponseMessage> {
if (payload.kind !== 'enterChargeMode') {
throw 'Unexpected message';
}
const openChargeWindowReq: CrxRpcMessage = {
ext,
messageId: generateMessageId(),
src: 'content',
path: ['background'],
payload: {
kind: 'openChargeWindow',
request: {},
},
};
const { payload: result }: CrxRpcResponseMessage = await chrome.runtime.sendMessage(
openChargeWindowReq,
);
if (result.kind !== 'openChargeWindow') {
throw 'Unexpected message';
}
// Keep sending strain signals.
const joycon = await getJoyconDevice();
await | setupJoycon(joycon); |
const neutral = await getNextStrain(joycon);
const sendStrain = (value: number) => {
const req: CrxRpcMessage = {
ext,
messageId: generateMessageId(),
src: 'content',
path: ['charge'],
payload: {
kind: 'sendStrain',
request: {
value,
neutral,
},
},
};
chrome.runtime.sendMessage(req);
};
const reportListener = (ev: HIDInputReportEvent) => {
const value = getStrain(ev);
if (value) {
sendStrain(value);
}
};
joycon.addEventListener('inputreport', reportListener);
// Wait for `leaveChargeMode` signal.
await wait<CrxRpcRequestMessage, void>(
(resolve) => (msg) => {
const { next, shouldBeHandled } = handleCrxRpcRequest(msg, 'content');
if (!shouldBeHandled) {
return;
}
if (!!next) {
console.warn('Unexpected message', msg);
return;
}
if (msg.payload.kind === 'leaveChargeMode') {
resolve();
}
},
{
addEventListener: (listener) => {
chrome.runtime.onMessage.addListener(listener);
},
removeEventListener: (listener) => {
chrome.runtime.onMessage.removeListener(listener);
},
},
);
// Stop sending strain signals.
joycon.removeEventListener('inputreport', reportListener);
return {
ext,
messageId,
payload: {
kind: 'enterChargeMode',
response: true,
},
};
}
function injectResourceScript(path: string) {
const script = document.createElement('script');
script.setAttribute('async', 'false');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', chrome.runtime.getURL(path));
document.head.appendChild(script);
}
| src/content/index.ts | penpenpng-nostronger-851a990 | [
{
"filename": "src/lib/ring-con.ts",
"retrieved_chunk": " if (!device) {\n throw new Error('device not found.');\n }\n if (!device.opened) {\n await device.open();\n }\n await setupJoycon(device);\n return device;\n}\nexport async function setupJoycon(joycon: HIDDevice) {",
"score": 19.603576991907765
},
{
"filename": "src/background/index.ts",
"retrieved_chunk": " if (next === 'content' && payload.kind === 'leaveChargeMode') {\n chrome.tabs.sendMessage(payload.request.senderTabId, msg);\n return;\n } else if (!!next) {\n console.warn('Unexpected message', msg);\n return;\n }\n const sendResponse = (val: any) => {\n const res: CrxRpcResponseMessage = {\n ...msg,",
"score": 19.210732427088956
},
{
"filename": "src/lib/ring-con.ts",
"retrieved_chunk": " return wait<HIDInputReportEvent, number>(\n (resolve) => (event) => {\n const strain = getStrain(event);\n if (strain) {\n resolve(strain);\n }\n },\n {\n addEventListener: (listener) => joycon.addEventListener('inputreport', listener),\n removeEventListener: (listener) => joycon.removeEventListener('inputreport', listener),",
"score": 13.271203404456985
},
{
"filename": "src/lib/ring-con.ts",
"retrieved_chunk": " // set_input_report_mode_to_0x30\n await communicate(joycon, [0x03, 0x30], [[14, 0x03]]);\n // enabling_MCU_data_22_1\n await communicate(\n joycon,\n [0x22, 0x01],\n [\n [13, 0x80],\n [14, 0x22],\n ],",
"score": 12.1199485916118
},
{
"filename": "src/lib/ring-con.ts",
"retrieved_chunk": " // start_external_polling_5A\n await communicate(joycon, [0x5a, 0x04, 0x01, 0x01, 0x02], [[14, 0x5a]]);\n // blink LED\n await communicate(joycon, [0x30, 0x90], [[14, 0x30]]);\n}\nasync function communicate(device: HIDDevice, subcommand: number[], expected: [number, number][]) {\n await wait<HIDInputReportEvent, void>(\n (resolve) => (event) => {\n if (event.reportId !== 0x21) {\n return;",
"score": 11.04106441046685
}
] | typescript | setupJoycon(joycon); |
import { executePrompt, executePromptStream } from "./executePrompt.js";
import { loadConfig } from "./config.js";
import { loadPromptConfig, listPrompts } from "./loadPromptConfig.js";
import { APPNAME } from "./types.js";
import FileSystemKVS from "./kvs/kvs-filesystem.js";
import { AppError } from "./errors.js";
import { readFileSync } from "node:fs";
function parseArgs(argv: string[]) {
const [_nodeBin, _jsFile, promptId, ...rest] = argv;
const input = rest.join(" ");
return { promptId, input };
}
function printUsageAndExit() {
console.log("Usage:");
console.log(`$ ${APPNAME} <promptType> <input>`);
console.log(`$ ${APPNAME} --list`);
console.log("");
console.log("Example: ");
console.log("");
console.log(`$ ${APPNAME} eli5 "what are large language models?"`);
process.exit(1);
}
function getInput(argvInput: string) {
try {
const stdinInput = readFileSync(process.stdin.fd, "utf-8");
// console.log({ stdinInput });
return `${argvInput} ${stdinInput}`;
} catch (err) {
return argvInput;
}
}
export async function cli() {
try {
const config = loadConfig();
const { promptId, input: argvInput } = parseArgs(process.argv);
if (promptId === "--list") {
const prompts = await listPrompts(config);
console.log(
prompts
| .map((p) => { |
const description = p.description ? `: ${p.description}` : "";
return `${p.name}${description}`;
})
.join("\n")
);
return;
} else if (promptId && promptId.startsWith("--")) {
printUsageAndExit();
}
const input = getInput(argvInput);
if (!promptId || !input) {
printUsageAndExit();
}
const promptConfig = await loadPromptConfig(promptId, config);
const cache = config.useCache
? new FileSystemKVS({ baseDir: config.paths.cache })
: undefined;
const stream = executePromptStream(promptConfig, input, config, cache);
for await (const chunk of stream) {
process.stdout.write(chunk);
}
process.stdout.write("\n");
} catch (err) {
if (err instanceof AppError) {
console.error(err.toString());
process.exit(err.exitCode);
}
console.error(err);
process.exit(1);
}
}
export default cli;
| src/index.ts | clevercli-clevercli-c660fae | [
{
"filename": "src/loadPromptConfig.ts",
"retrieved_chunk": "export async function loadFromPath(path: string) {\n const promptConfig = await import(path);\n // TODO: validate promptConfig?\n return promptConfig.default;\n}\nexport async function loadPromptConfig(promptId: string, config: Config) {\n try {\n const promptConfig = await Promise.any([\n loadFromPath(sourceRelativePath(import.meta, `./prompts/${promptId}.js`)),\n loadFromPath(pathJoin(config.paths.data, `${promptId}.mjs`)),",
"score": 27.460908835890084
},
{
"filename": "src/loadPromptConfig.ts",
"retrieved_chunk": " ]);\n return promptConfig;\n } catch (err) {\n throw new AppError({\n message: `Could not find prompt ${promptId}. Are you sure it is a builtin prompt or that ${config.paths.data}/${promptId}.mjs exists?`,\n });\n }\n}\nexport async function listPrompts(config: Config) {\n const [localFiles, builtinFiles] = await Promise.all(",
"score": 20.12889335872816
},
{
"filename": "src/loadPromptConfig.ts",
"retrieved_chunk": " [\n sourceRelativePath(import.meta, `./prompts`),\n pathJoin(config.paths.data),\n ].map(readFilesInDirectory)\n );\n const allFiles = [...localFiles, ...builtinFiles];\n const allPromptConfigs = await Promise.all(allFiles.map(loadFromPath));\n return allPromptConfigs.map((config, i) => {\n const name = parse(allFiles[i]).name;\n return {",
"score": 18.749804239174928
},
{
"filename": "src/config.ts",
"retrieved_chunk": " throw new ConfigError({\n message: `Please set the ${key} environment variable.`,\n });\n }\n return val;\n}\nconst paths = envPaths(APPNAME, { suffix: \"\" });\nexport function loadConfig(): Config {\n const config = {\n openai: {",
"score": 12.408056737006168
},
{
"filename": "src/openai.ts",
"retrieved_chunk": " // console.log({ json });\n if (content) {\n yield content;\n }\n }\n}",
"score": 12.104347450684369
}
] | typescript | .map((p) => { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.