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/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": 0.8451051712036133 }, { "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": 0.8396981954574585 }, { "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": 0.8357936143875122 }, { "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": 0.82941734790802 }, { "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": 0.8215386271476746 } ]
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": 0.8934849500656128 }, { "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": 0.859308123588562 }, { "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": 0.8584834337234497 }, { "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": 0.8235952854156494 }, { "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": 0.8226037621498108 } ]
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": 0.8957299590110779 }, { "filename": "src/helpers/snapshot.ts", "retrieved_chunk": " orderBy,\n orderDirection,\n first,\n skip,\n created_gte\n }\n });\n return votes;\n}\nexport async function fetchSpace(id: string) {", "score": 0.8553829789161682 }, { "filename": "src/api.ts", "retrieved_chunk": "router.post('/votes/:id', async (req, res) => {\n const { id } = req.params;\n const votesReport = new VotesReport(id, storageEngine(process.env.VOTE_REPORT_SUBDIR));\n try {\n const file = await votesReport.getCache();\n if (file) {\n res.header('Content-Type', 'text/csv');\n res.attachment(votesReport.filename);\n return res.end(file);\n }", "score": 0.8130518198013306 }, { "filename": "src/api.ts", "retrieved_chunk": " try {\n await votesReport.isCacheable();\n queue(votesReport);\n return rpcSuccess(res.status(202), getProgress(id).toString(), id);\n } catch (e: any) {\n capture(e);\n rpcError(res, e, id);\n }\n } catch (e) {\n capture(e);", "score": 0.8070147037506104 }, { "filename": "src/helpers/snapshot.ts", "retrieved_chunk": " $skip: Int\n $orderBy: String\n $orderDirection: OrderDirection\n $created_gte: Int\n ) {\n votes(\n first: $first\n skip: $skip\n where: { proposal: $id, created_gte: $created_gte }\n orderBy: $orderBy", "score": 0.8042243123054504 } ]
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": 0.9338904023170471 }, { "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": 0.929557204246521 }, { "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": 0.9248620867729187 }, { "filename": "src/exceptions/internal-server-error.exception.ts", "retrieved_chunk": " })\n timestamp: string; // Timestamp of the exception\n @ApiProperty({\n description: 'Trace ID of the request',\n example: '65b5f773-df95-4ce5-a917-62ee832fcdd0',\n })\n traceId: string; // Trace ID of the request\n /**\n * Constructs a new InternalServerErrorException object.\n * @param exception An object containing the exception details.", "score": 0.8585684299468994 }, { "filename": "src/exceptions/exceptions.interface.ts", "retrieved_chunk": "export interface IException {\n message: string;\n code?: number;\n cause?: Error;\n description?: string;\n}\nexport interface IHttpBadRequestExceptionResponse {\n code: number;\n message: string;\n description: string;", "score": 0.8424656391143799 } ]
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": 0.9446876645088196 }, { "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": 0.922133207321167 }, { "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": 0.9080532789230347 }, { "filename": "src/exceptions/exceptions.interface.ts", "retrieved_chunk": "export interface IException {\n message: string;\n code?: number;\n cause?: Error;\n description?: string;\n}\nexport interface IHttpBadRequestExceptionResponse {\n code: number;\n message: string;\n description: string;", "score": 0.8164711594581604 }, { "filename": "src/exceptions/bad-request.exception.ts", "retrieved_chunk": " @ApiProperty({\n enum: ExceptionConstants.BadRequestCodes,\n description: 'A unique code identifying the error.',\n example: ExceptionConstants.BadRequestCodes.VALIDATION_ERROR,\n })\n code: number; // Internal status code\n @ApiHideProperty()\n cause: Error; // Error object causing the exception\n @ApiProperty({\n description: 'Message for the exception',", "score": 0.814764142036438 } ]
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": 0.9737163782119751 }, { "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": 0.9376154541969299 }, { "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": 0.9350349307060242 }, { "filename": "src/exceptions/bad-request.exception.ts", "retrieved_chunk": " generateHttpResponseBody = (message?: string): IHttpBadRequestExceptionResponse => {\n return {\n code: this.code,\n message: message || this.message,\n description: this.description,\n timestamp: this.timestamp,\n traceId: this.traceId,\n };\n };\n /**", "score": 0.9128544330596924 }, { "filename": "src/exceptions/exceptions.interface.ts", "retrieved_chunk": " timestamp: string;\n traceId: string;\n}\nexport interface IHttpInternalServerErrorExceptionResponse {\n code: number;\n message: string;\n description: string;\n timestamp: string;\n traceId: string;\n}", "score": 0.8757935166358948 } ]
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": 0.9599713683128357 }, { "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": 0.9416981935501099 }, { "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": 0.9403434991836548 }, { "filename": "src/exceptions/bad-request.exception.ts", "retrieved_chunk": " generateHttpResponseBody = (message?: string): IHttpBadRequestExceptionResponse => {\n return {\n code: this.code,\n message: message || this.message,\n description: this.description,\n timestamp: this.timestamp,\n traceId: this.traceId,\n };\n };\n /**", "score": 0.9102122187614441 }, { "filename": "src/exceptions/exceptions.interface.ts", "retrieved_chunk": "export interface IHttpUnauthorizedExceptionResponse {\n code: number;\n message: string;\n description: string;\n timestamp: string;\n traceId: string;\n}\nexport interface IHttpForbiddenExceptionResponse {\n code: number;\n message: string;", "score": 0.8536126613616943 } ]
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": 0.9874809384346008 }, { "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": 0.9652629494667053 }, { "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": 0.9311695098876953 }, { "filename": "src/exceptions/exceptions.interface.ts", "retrieved_chunk": " timestamp: string;\n traceId: string;\n}\nexport interface IHttpInternalServerErrorExceptionResponse {\n code: number;\n message: string;\n description: string;\n timestamp: string;\n traceId: string;\n}", "score": 0.8480513691902161 }, { "filename": "src/exceptions/exceptions.interface.ts", "retrieved_chunk": "export interface IException {\n message: string;\n code?: number;\n cause?: Error;\n description?: string;\n}\nexport interface IHttpBadRequestExceptionResponse {\n code: number;\n message: string;\n description: string;", "score": 0.8344045877456665 } ]
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": 0.984531819820404 }, { "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": 0.9419252872467041 }, { "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": 0.931390106678009 }, { "filename": "src/exceptions/bad-request.exception.ts", "retrieved_chunk": " generateHttpResponseBody = (message?: string): IHttpBadRequestExceptionResponse => {\n return {\n code: this.code,\n message: message || this.message,\n description: this.description,\n timestamp: this.timestamp,\n traceId: this.traceId,\n };\n };\n /**", "score": 0.9115154147148132 }, { "filename": "src/exceptions/exceptions.interface.ts", "retrieved_chunk": " timestamp: string;\n traceId: string;\n}\nexport interface IHttpInternalServerErrorExceptionResponse {\n code: number;\n message: string;\n description: string;\n timestamp: string;\n traceId: string;\n}", "score": 0.8658140301704407 } ]
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": 0.9696172475814819 }, { "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": 0.9340378046035767 }, { "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": 0.9121399521827698 }, { "filename": "src/exceptions/bad-request.exception.ts", "retrieved_chunk": " generateHttpResponseBody = (message?: string): IHttpBadRequestExceptionResponse => {\n return {\n code: this.code,\n message: message || this.message,\n description: this.description,\n timestamp: this.timestamp,\n traceId: this.traceId,\n };\n };\n /**", "score": 0.8834491968154907 }, { "filename": "src/exceptions/exceptions.interface.ts", "retrieved_chunk": "export interface IHttpUnauthorizedExceptionResponse {\n code: number;\n message: string;\n description: string;\n timestamp: string;\n traceId: string;\n}\nexport interface IHttpForbiddenExceptionResponse {\n code: number;\n message: string;", "score": 0.8555321097373962 } ]
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": 0.883019208908081 }, { "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": 0.8455255627632141 }, { "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": 0.8409487009048462 }, { "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": 0.8180996775627136 }, { "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": 0.8106698989868164 } ]
typescript
= new Item() itemInstance.renderList({
/** * 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": 0.9425487518310547 }, { "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": 0.9400701522827148 }, { "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": 0.9111735820770264 }, { "filename": "src/exceptions/internal-server-error.exception.ts", "retrieved_chunk": " })\n timestamp: string; // Timestamp of the exception\n @ApiProperty({\n description: 'Trace ID of the request',\n example: '65b5f773-df95-4ce5-a917-62ee832fcdd0',\n })\n traceId: string; // Trace ID of the request\n /**\n * Constructs a new InternalServerErrorException object.\n * @param exception An object containing the exception details.", "score": 0.8435873985290527 }, { "filename": "src/exceptions/unauthorized.exception.ts", "retrieved_chunk": " /**\n * A static method to generate an exception for unauthorized access to a resource.\n * @param description - An optional detailed description of the error.\n * @returns An instance of the UnauthorizedException class.\n */\n static UNAUTHORIZED_ACCESS = (description?: string) => {\n return new UnauthorizedException({\n message: 'Access to the requested resource is unauthorized.',\n code: ExceptionConstants.UnauthorizedCodes.UNAUTHORIZED_ACCESS,\n description,", "score": 0.831186056137085 } ]
typescript
message, HttpStatus.FORBIDDEN, {
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/types/index.ts", "retrieved_chunk": "export enum SearchJSTheme {\n ThemeGithubLight = 'github-light',\n ThemeGithubDark = 'github-dark',\n ThemeLight = 'light-theme',\n ThemeDark = 'dark-theme',\n}\nexport interface SearchJSItem {\n title: string\n description?: string\n [propName: string]: any", "score": 0.8489915132522583 }, { "filename": "src/themes/index.ts", "retrieved_chunk": "import {\n DEFAULT_HEIGHT,\n DEFAULT_POSITION_TOP,\n DEFAULT_THEME_COLOR,\n DEFAULT_WIDTH,\n} from '../constant'\nimport { SearchJSConfig, SearchJSTheme } from '../types'\nimport {\n AvailableThemes,\n CssFontFamily,", "score": 0.8405966758728027 }, { "filename": "src/constant/index.ts", "retrieved_chunk": "export const DEFAULT_THEME_COLOR = '#FF2E1F'\nexport const DEFAULT_WIDTH = '400px'\nexport const DEFAULT_HEIGHT = '450px'\nexport const DEFAULT_POSITION_TOP = '85px'\nexport const ID = 'search-js'\nexport const ID_HISTORIES = 'search-js-histories'\nexport const ID_RESULTS = 'search-js-result'\nexport const ID_LOADING = 'search-js-loading'\nexport const CLASS_CONTAINER = 'container'\nexport const CLASS_CLEAR_ICON = 'clear-icon'", "score": 0.8388746380805969 }, { "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": 0.8206782937049866 }, { "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": 0.8025793433189392 } ]
typescript
[SearchJSTheme.ThemeGithubLight]: {
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": 0.8561864495277405 }, { "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": 0.8131563663482666 }, { "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": 0.8048356771469116 }, { "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": 0.8000666499137878 }, { "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": 0.7965927720069885 } ]
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": 0.8840146064758301 }, { "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": 0.809907078742981 }, { "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": 0.8097392320632935 }, { "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": 0.8025072813034058 }, { "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": 0.7995763421058655 } ]
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/utils/SearchComponent.ts", "retrieved_chunk": " * @var {number} searchTimer\n */\n private searchTimer?: number\n /**\n * class constructor\n *\n * @param {SearchJSApp} app\n * @param {DomListener} domListener\n * @param {SearchHistory} searchHistory\n * @param {Theme} theme", "score": 0.8098991513252258 }, { "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": 0.8053346872329712 }, { "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": 0.8041490316390991 }, { "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": 0.8018727898597717 }, { "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": 0.7977118492126465 } ]
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": 0.8594657778739929 }, { "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": 0.8377203941345215 }, { "filename": "src/index.ts", "retrieved_chunk": " */\nconst SearchJS = (config: SearchJSConfig): SearchJSApp => {\n return SearchJSApp.getInstance(config)\n}\ndeclare global {\n interface Window {\n SearchJS: (config: SearchJSConfig) => SearchJSApp\n }\n}\nwindow.SearchJS = SearchJS", "score": 0.8088997006416321 }, { "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": 0.8044644594192505 }, { "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": 0.7930938005447388 } ]
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/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": 0.8193771243095398 }, { "filename": "src/utils/DomListener.ts", "retrieved_chunk": "import {\n CLASS_CLEAR_ICON,\n CLASS_CONTAINER,\n ATTR_DATA_PAYLOAD,\n ID,\n CLASS_INPUT,\n CLASS_ITEM,\n CLASS_ITEM_CLOSE,\n} from '../constant'\nimport { SearchJSItem } from '../types'", "score": 0.8119322657585144 }, { "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": 0.8040780425071716 }, { "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": 0.8040473461151123 }, { "filename": "src/components/Header.ts", "retrieved_chunk": "<div class=\"search-icon\">${icon}</div>\n<input placeholder=\"${placeholder}\" class=\"${CLASS_INPUT}\" type=\"text\"/>\n<div class=\"${CLASS_CLEAR_ICON}\">${clearIcon()}</div>\n</div>`\n }\n}", "score": 0.8001066446304321 } ]
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": 0.84677654504776 }, { "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": 0.840950608253479 }, { "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": 0.8191883563995361 }, { "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": 0.817813515663147 }, { "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": 0.8105108141899109 } ]
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": 0.8907791376113892 }, { "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": 0.8451113104820251 }, { "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": 0.8411588668823242 }, { "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": 0.8294864892959595 }, { "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": 0.8237704634666443 } ]
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/constant/index.ts", "retrieved_chunk": "export const DEFAULT_THEME_COLOR = '#FF2E1F'\nexport const DEFAULT_WIDTH = '400px'\nexport const DEFAULT_HEIGHT = '450px'\nexport const DEFAULT_POSITION_TOP = '85px'\nexport const ID = 'search-js'\nexport const ID_HISTORIES = 'search-js-histories'\nexport const ID_RESULTS = 'search-js-result'\nexport const ID_LOADING = 'search-js-loading'\nexport const CLASS_CONTAINER = 'container'\nexport const CLASS_CLEAR_ICON = 'clear-icon'", "score": 0.8355027437210083 }, { "filename": "src/themes/index.ts", "retrieved_chunk": "import {\n DEFAULT_HEIGHT,\n DEFAULT_POSITION_TOP,\n DEFAULT_THEME_COLOR,\n DEFAULT_WIDTH,\n} from '../constant'\nimport { SearchJSConfig, SearchJSTheme } from '../types'\nimport {\n AvailableThemes,\n CssFontFamily,", "score": 0.8316904306411743 }, { "filename": "src/types/index.ts", "retrieved_chunk": "export enum SearchJSTheme {\n ThemeGithubLight = 'github-light',\n ThemeGithubDark = 'github-dark',\n ThemeLight = 'light-theme',\n ThemeDark = 'dark-theme',\n}\nexport interface SearchJSItem {\n title: string\n description?: string\n [propName: string]: any", "score": 0.8303455114364624 }, { "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": 0.8094170093536377 }, { "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": 0.8001083135604858 } ]
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": 0.8576235175132751 }, { "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": 0.8415433168411255 }, { "filename": "src/index.ts", "retrieved_chunk": " */\nconst SearchJS = (config: SearchJSConfig): SearchJSApp => {\n return SearchJSApp.getInstance(config)\n}\ndeclare global {\n interface Window {\n SearchJS: (config: SearchJSConfig) => SearchJSApp\n }\n}\nwindow.SearchJS = SearchJS", "score": 0.8096343278884888 }, { "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": 0.8061143755912781 }, { "filename": "src/themes/index.ts", "retrieved_chunk": "import {\n DEFAULT_HEIGHT,\n DEFAULT_POSITION_TOP,\n DEFAULT_THEME_COLOR,\n DEFAULT_WIDTH,\n} from '../constant'\nimport { SearchJSConfig, SearchJSTheme } from '../types'\nimport {\n AvailableThemes,\n CssFontFamily,", "score": 0.8026838302612305 } ]
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": 0.8594657778739929 }, { "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": 0.8377203941345215 }, { "filename": "src/index.ts", "retrieved_chunk": " */\nconst SearchJS = (config: SearchJSConfig): SearchJSApp => {\n return SearchJSApp.getInstance(config)\n}\ndeclare global {\n interface Window {\n SearchJS: (config: SearchJSConfig) => SearchJSApp\n }\n}\nwindow.SearchJS = SearchJS", "score": 0.8088997006416321 }, { "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": 0.8044644594192505 }, { "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": 0.7930938005447388 } ]
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": 0.8539757132530212 }, { "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": 0.8379600048065186 }, { "filename": "src/index.ts", "retrieved_chunk": " */\nconst SearchJS = (config: SearchJSConfig): SearchJSApp => {\n return SearchJSApp.getInstance(config)\n}\ndeclare global {\n interface Window {\n SearchJS: (config: SearchJSConfig) => SearchJSApp\n }\n}\nwindow.SearchJS = SearchJS", "score": 0.8057671189308167 }, { "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": 0.8028325438499451 }, { "filename": "src/themes/index.ts", "retrieved_chunk": "import {\n DEFAULT_HEIGHT,\n DEFAULT_POSITION_TOP,\n DEFAULT_THEME_COLOR,\n DEFAULT_WIDTH,\n} from '../constant'\nimport { SearchJSConfig, SearchJSTheme } from '../types'\nimport {\n AvailableThemes,\n CssFontFamily,", "score": 0.7992133498191833 } ]
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": 0.8787208795547485 }, { "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": 0.8525744676589966 }, { "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": 0.8499789237976074 }, { "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": 0.8421151638031006 }, { "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": 0.8266716003417969 } ]
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/themes/AvailableThemes.ts", "retrieved_chunk": "export const CssItemBoxShadow = '--search-js-item-box-shadow'\nexport const CssTextColor = '--search-js-text-color'\nexport const CssTheme = '--search-js-theme'\nexport const CssWidth = '--search-js-width'\nexport const CssHeight = '--search-js-height'\nexport const CssFontFamily = '--search-js-font-family'\nexport const CssPositionTop = '--search-js-top'\nexport const AvailableThemes: any = {\n [SearchJSTheme.ThemeDark]: {\n [CssBackdropBackground]: 'rgba(47, 55, 69, 0.7)',", "score": 0.815680742263794 }, { "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": 0.8156208992004395 }, { "filename": "src/themes/AvailableThemes.ts", "retrieved_chunk": "import { SearchJSTheme } from '../types'\nexport const CssBackdropBackground = '--search-js-backdrop-bg'\nexport const CssModalBackground = '--search-js-modal-bg'\nexport const CssModalBoxShadow = '--search-js-modal-box-shadow'\nexport const CssModalFooterBoxShadow = '--search-js-modal-footer-box-shadow'\nexport const CssKeyboardButtonBoxShadow = '--search-js-keyboard-button-box-shadow'\nexport const CssKeyboardButtonBackground = '--search-js-keyboard-button-bg'\nexport const CssInputBackground = '--search-js-search-input-bg'\nexport const CssInputPlaceholderColor = '--search-js-input-placeholder-color'\nexport const CssItemBackground = '--search-js-item-bg'", "score": 0.8070240020751953 }, { "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": 0.8069969415664673 }, { "filename": "src/utils/SearchComponent.ts", "retrieved_chunk": "import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'\nimport { Footer } from '../components/Footer'\nimport { Header } from '../components/Header'\nimport { Item } from '../components/Item'\nimport { DomListener } from './DomListener'\nimport { SearchHistory } from './SearchHistory'\nimport { SearchJSApp } from '..'\nimport { SearchJSItem, SearchJSTheme } from '../types'\nimport { Theme } from '../themes'\nimport {", "score": 0.7931687831878662 } ]
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": 0.9324812293052673 }, { "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": 0.9211768507957458 }, { "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": 0.9047093391418457 }, { "filename": "src/exceptions/internal-server-error.exception.ts", "retrieved_chunk": " })\n timestamp: string; // Timestamp of the exception\n @ApiProperty({\n description: 'Trace ID of the request',\n example: '65b5f773-df95-4ce5-a917-62ee832fcdd0',\n })\n traceId: string; // Trace ID of the request\n /**\n * Constructs a new InternalServerErrorException object.\n * @param exception An object containing the exception details.", "score": 0.8396974802017212 }, { "filename": "src/exceptions/forbidden.exception.ts", "retrieved_chunk": " timestamp: string;\n /** Trace ID of the request */\n @ApiProperty({\n description: 'Trace ID of the request',\n example: '65b5f773-df95-4ce5-a917-62ee832fcdd0',\n })\n traceId: string; // Trace ID of the request\n /**\n * Constructs a new ForbiddenException object.\n * @param exception An object containing the exception details.", "score": 0.8393998146057129 } ]
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/themes/AvailableThemes.ts", "retrieved_chunk": "export const CssItemBoxShadow = '--search-js-item-box-shadow'\nexport const CssTextColor = '--search-js-text-color'\nexport const CssTheme = '--search-js-theme'\nexport const CssWidth = '--search-js-width'\nexport const CssHeight = '--search-js-height'\nexport const CssFontFamily = '--search-js-font-family'\nexport const CssPositionTop = '--search-js-top'\nexport const AvailableThemes: any = {\n [SearchJSTheme.ThemeDark]: {\n [CssBackdropBackground]: 'rgba(47, 55, 69, 0.7)',", "score": 0.8141394257545471 }, { "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": 0.812286913394928 }, { "filename": "src/themes/AvailableThemes.ts", "retrieved_chunk": "import { SearchJSTheme } from '../types'\nexport const CssBackdropBackground = '--search-js-backdrop-bg'\nexport const CssModalBackground = '--search-js-modal-bg'\nexport const CssModalBoxShadow = '--search-js-modal-box-shadow'\nexport const CssModalFooterBoxShadow = '--search-js-modal-footer-box-shadow'\nexport const CssKeyboardButtonBoxShadow = '--search-js-keyboard-button-box-shadow'\nexport const CssKeyboardButtonBackground = '--search-js-keyboard-button-bg'\nexport const CssInputBackground = '--search-js-search-input-bg'\nexport const CssInputPlaceholderColor = '--search-js-input-placeholder-color'\nexport const CssItemBackground = '--search-js-item-bg'", "score": 0.806063175201416 }, { "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": 0.8017978668212891 }, { "filename": "src/utils/SearchComponent.ts", "retrieved_chunk": "import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon'\nimport { Footer } from '../components/Footer'\nimport { Header } from '../components/Header'\nimport { Item } from '../components/Item'\nimport { DomListener } from './DomListener'\nimport { SearchHistory } from './SearchHistory'\nimport { SearchJSApp } from '..'\nimport { SearchJSItem, SearchJSTheme } from '../types'\nimport { Theme } from '../themes'\nimport {", "score": 0.7923433780670166 } ]
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": 0.8594657778739929 }, { "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": 0.8377203941345215 }, { "filename": "src/index.ts", "retrieved_chunk": " */\nconst SearchJS = (config: SearchJSConfig): SearchJSApp => {\n return SearchJSApp.getInstance(config)\n}\ndeclare global {\n interface Window {\n SearchJS: (config: SearchJSConfig) => SearchJSApp\n }\n}\nwindow.SearchJS = SearchJS", "score": 0.8088997006416321 }, { "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": 0.8044644594192505 }, { "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": 0.7930938005447388 } ]
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": 0.8171645998954773 }, { "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": 0.8131709098815918 }, { "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": 0.8081734776496887 }, { "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": 0.8080068826675415 }, { "filename": "src/index.ts", "retrieved_chunk": " */\nconst SearchJS = (config: SearchJSConfig): SearchJSApp => {\n return SearchJSApp.getInstance(config)\n}\ndeclare global {\n interface Window {\n SearchJS: (config: SearchJSConfig) => SearchJSApp\n }\n}\nwindow.SearchJS = SearchJS", "score": 0.8058880567550659 } ]
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/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": 0.8192354440689087 }, { "filename": "src/utils/DomListener.ts", "retrieved_chunk": "import {\n CLASS_CLEAR_ICON,\n CLASS_CONTAINER,\n ATTR_DATA_PAYLOAD,\n ID,\n CLASS_INPUT,\n CLASS_ITEM,\n CLASS_ITEM_CLOSE,\n} from '../constant'\nimport { SearchJSItem } from '../types'", "score": 0.8113837242126465 }, { "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": 0.8033221960067749 }, { "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": 0.8030340671539307 }, { "filename": "src/components/Header.ts", "retrieved_chunk": "<div class=\"search-icon\">${icon}</div>\n<input placeholder=\"${placeholder}\" class=\"${CLASS_INPUT}\" type=\"text\"/>\n<div class=\"${CLASS_CLEAR_ICON}\">${clearIcon()}</div>\n</div>`\n }\n}", "score": 0.8002129793167114 } ]
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": 0.8305752873420715 }, { "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": 0.8250048756599426 }, { "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": 0.7941677570343018 }, { "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": 0.7919397354125977 }, { "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": 0.7917616367340088 } ]
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": 0.8543210625648499 }, { "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": 0.8383908867835999 }, { "filename": "src/index.ts", "retrieved_chunk": " */\nconst SearchJS = (config: SearchJSConfig): SearchJSApp => {\n return SearchJSApp.getInstance(config)\n}\ndeclare global {\n interface Window {\n SearchJS: (config: SearchJSConfig) => SearchJSApp\n }\n}\nwindow.SearchJS = SearchJS", "score": 0.8077675104141235 }, { "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": 0.8022847771644592 }, { "filename": "src/themes/index.ts", "retrieved_chunk": "import {\n DEFAULT_HEIGHT,\n DEFAULT_POSITION_TOP,\n DEFAULT_THEME_COLOR,\n DEFAULT_WIDTH,\n} from '../constant'\nimport { SearchJSConfig, SearchJSTheme } from '../types'\nimport {\n AvailableThemes,\n CssFontFamily,", "score": 0.7996788024902344 } ]
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": 0.8368484973907471 }, { "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": 0.8174612522125244 }, { "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": 0.8112936019897461 }, { "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": 0.8020284175872803 }, { "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": 0.801970362663269 } ]
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": " }\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": 0.8374160528182983 }, { "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": 0.819441020488739 }, { "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": 0.8167134523391724 }, { "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": 0.8153284788131714 }, { "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": 0.806641697883606 } ]
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/constant/index.ts", "retrieved_chunk": "export const DEFAULT_THEME_COLOR = '#FF2E1F'\nexport const DEFAULT_WIDTH = '400px'\nexport const DEFAULT_HEIGHT = '450px'\nexport const DEFAULT_POSITION_TOP = '85px'\nexport const ID = 'search-js'\nexport const ID_HISTORIES = 'search-js-histories'\nexport const ID_RESULTS = 'search-js-result'\nexport const ID_LOADING = 'search-js-loading'\nexport const CLASS_CONTAINER = 'container'\nexport const CLASS_CLEAR_ICON = 'clear-icon'", "score": 0.8336706161499023 }, { "filename": "src/types/index.ts", "retrieved_chunk": "export enum SearchJSTheme {\n ThemeGithubLight = 'github-light',\n ThemeGithubDark = 'github-dark',\n ThemeLight = 'light-theme',\n ThemeDark = 'dark-theme',\n}\nexport interface SearchJSItem {\n title: string\n description?: string\n [propName: string]: any", "score": 0.8316137194633484 }, { "filename": "src/themes/index.ts", "retrieved_chunk": "import {\n DEFAULT_HEIGHT,\n DEFAULT_POSITION_TOP,\n DEFAULT_THEME_COLOR,\n DEFAULT_WIDTH,\n} from '../constant'\nimport { SearchJSConfig, SearchJSTheme } from '../types'\nimport {\n AvailableThemes,\n CssFontFamily,", "score": 0.8290977478027344 }, { "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": 0.8057242035865784 }, { "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": 0.8028919696807861 } ]
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": " }\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": 0.8344194889068604 }, { "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": 0.8213258981704712 }, { "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": 0.8179425597190857 }, { "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": 0.8157327175140381 }, { "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": 0.8083404898643494 } ]
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": " * @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": 0.8462799191474915 }, { "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": 0.8454720973968506 }, { "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": 0.8269054889678955 }, { "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": 0.8249955177307129 }, { "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": 0.8216991424560547 } ]
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": 0.8713712692260742 }, { "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": 0.8454045057296753 }, { "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": 0.8383298516273499 }, { "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": 0.8271157741546631 }, { "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": 0.8245525360107422 } ]
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/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": 0.8215316534042358 }, { "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": 0.8175344467163086 }, { "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": 0.8169312477111816 }, { "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": 0.8138600587844849 }, { "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": 0.8074487447738647 } ]
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": " }\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": 0.8362728953361511 }, { "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": 0.8236592411994934 }, { "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": 0.8210505247116089 }, { "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": 0.818284273147583 }, { "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": 0.8123080134391785 } ]
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": " 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": 0.870080828666687 }, { "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": 0.8196644186973572 }, { "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": 0.8144252300262451 }, { "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": 0.8136830925941467 }, { "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": 0.8060019016265869 } ]
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": " 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": 0.8689429759979248 }, { "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": 0.8192301988601685 }, { "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": 0.8174535036087036 }, { "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": 0.8167068958282471 }, { "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": 0.8097819089889526 } ]
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": 0.869229793548584 }, { "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": 0.8443565368652344 }, { "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": 0.8305878639221191 }, { "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": 0.8171404004096985 }, { "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": 0.799130916595459 } ]
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/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": 0.848084568977356 }, { "filename": "src/scorer/FeedScorer.ts", "retrieved_chunk": "import { mastodon } from \"masto\"\nimport { StatusType } from \"../types\";\nexport default class FeedScorer {\n private _verboseName: string = \"BaseScorer\";\n private _isReady: boolean = false;\n private _description: string = \"\";\n private _defaultWeight: number = 1;\n features: any = {};\n constructor(verboseName: string, description?: string, defaultWeight?: number) {\n this._verboseName = verboseName;", "score": 0.8432760238647461 }, { "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": 0.8432672619819641 }, { "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": 0.8357237577438354 }, { "filename": "src/scorer/FeatureScorer.ts", "retrieved_chunk": "import { mastodon } from \"masto\"\nimport { StatusType, accFeatureType } from \"../types\";\ninterface RankParams {\n featureGetter: (api: mastodon.Client) => Promise<accFeatureType>,\n verboseName: string,\n description?: string,\n defaultWeight?: number,\n}\nexport default class FeatureScorer {\n featureGetter: (api: mastodon.Client) => Promise<accFeatureType>;", "score": 0.8321839570999146 } ]
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/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": 0.8753098249435425 }, { "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": 0.8659792542457581 }, { "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": 0.8421185612678528 }, { "filename": "src/weights/weightsStore.ts", "retrieved_chunk": " await this.setWeights({ [verboseName]: defaultWeight }, verboseName);\n return true;\n }\n return false;\n }\n}", "score": 0.8398444652557373 }, { "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": 0.834908127784729 } ]
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/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": 0.889319896697998 }, { "filename": "src/features/interactsFeature.ts", "retrieved_chunk": "import { mastodon } from \"masto\";\nimport { accFeatureType } from \"../types\";\nexport default async function interactFeature(api: mastodon.Client): Promise<accFeatureType> {\n let results: any[] = [];\n let pages = 3;\n for await (const page of api.v1.notifications.list({ limit: 80 })) {\n results = results.concat(page)\n pages--;\n if (pages === 0 || results.length < 80) {\n break;", "score": 0.8799444437026978 }, { "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": 0.8754351139068604 }, { "filename": "src/scorer/FeatureScorer.ts", "retrieved_chunk": " }\n async getFeature(api: mastodon.Client) {\n this._isReady = true;\n this.feature = await this.featureGetter(api);\n }\n async score(api: mastodon.Client, status: StatusType): Promise<number> {\n if (!this._isReady) {\n await this.getFeature(api);\n this._isReady = true;\n }", "score": 0.8599071502685547 }, { "filename": "src/features/favsFeature.ts", "retrieved_chunk": "import { login, mastodon } from \"masto\";\nimport { accFeatureType } from \"../types\";\nexport default async function favFeature(api: mastodon.Client): Promise<accFeatureType> {\n let results: mastodon.v1.Status[] = [];\n let pages = 3;\n for await (const page of api.v1.favourites.list({ limit: 80 })) {\n results = results.concat(page)\n pages--;\n if (pages === 0 || results.length < 80) {\n break;", "score": 0.8535404205322266 } ]
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/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": 0.850596010684967 }, { "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": 0.8432353734970093 }, { "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": 0.8195987343788147 }, { "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": 0.8020409941673279 }, { "filename": "src/scorer/feed/diversityFeedScorer.ts", "retrieved_chunk": " }, {});\n }\n async score(status: StatusType) {\n super.score(status);\n const frequ = this.features[status.account.acct]\n this.features[status.account.acct] = frequ + 1\n return frequ + 1\n }\n}", "score": 0.7985841631889343 } ]
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/scorer/feed/reblogsFeedScorer.ts", "retrieved_chunk": "import FeedScorer from \"../FeedScorer\";\nimport { StatusType } from \"../../types\";\nimport { mastodon } from \"masto\";\nexport default class reblogsFeedScorer extends FeedScorer {\n constructor() {\n super(\"reblogsFeed\", \"More Weight to posts that are reblogged a lot\", 6);\n }\n feedExtractor(feed: StatusType[]) {\n return feed.reduce((obj: any, status) => {\n if (status.reblog) {", "score": 0.842732846736908 }, { "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": 0.8274264931678772 }, { "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": 0.8234190940856934 }, { "filename": "src/features/reblogsFeature.ts", "retrieved_chunk": " }\n const reblogFrequ = results.reduce((accumulator: any, status: mastodon.v1.Status) => {\n if (status.reblog) {\n if (status.reblog.account.acct in accumulator) {\n accumulator[status.reblog.account.acct] += 1;\n } else {\n accumulator[status.reblog.account.acct] = 1;\n }\n }\n return accumulator", "score": 0.8226478695869446 }, { "filename": "src/scorer/feature/reblogsFeatureScorer.ts", "retrieved_chunk": " defaultWeight: 3,\n })\n }\n async score(api: mastodon.Client, status: StatusType) {\n const authorScore = (status.account.acct in this.feature) ? this.feature[status.account.acct] : 0\n const reblogScore = (status.reblog && status.reblog.account.acct in this.feature) ? this.feature[status.reblog.account.acct] : 0\n return authorScore + reblogScore\n }\n}", "score": 0.8183825016021729 } ]
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/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": 0.8685197234153748 }, { "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": 0.8405500650405884 }, { "filename": "src/scorer/FeatureScorer.ts", "retrieved_chunk": " }\n async getFeature(api: mastodon.Client) {\n this._isReady = true;\n this.feature = await this.featureGetter(api);\n }\n async score(api: mastodon.Client, status: StatusType): Promise<number> {\n if (!this._isReady) {\n await this.getFeature(api);\n this._isReady = true;\n }", "score": 0.8192038536071777 }, { "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": 0.8173933029174805 }, { "filename": "src/scorer/FeatureScorer.ts", "retrieved_chunk": "import { mastodon } from \"masto\"\nimport { StatusType, accFeatureType } from \"../types\";\ninterface RankParams {\n featureGetter: (api: mastodon.Client) => Promise<accFeatureType>,\n verboseName: string,\n description?: string,\n defaultWeight?: number,\n}\nexport default class FeatureScorer {\n featureGetter: (api: mastodon.Client) => Promise<accFeatureType>;", "score": 0.816702663898468 } ]
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/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": 0.9027138352394104 }, { "filename": "src/features/interactsFeature.ts", "retrieved_chunk": "import { mastodon } from \"masto\";\nimport { accFeatureType } from \"../types\";\nexport default async function interactFeature(api: mastodon.Client): Promise<accFeatureType> {\n let results: any[] = [];\n let pages = 3;\n for await (const page of api.v1.notifications.list({ limit: 80 })) {\n results = results.concat(page)\n pages--;\n if (pages === 0 || results.length < 80) {\n break;", "score": 0.866772472858429 }, { "filename": "src/scorer/FeatureScorer.ts", "retrieved_chunk": " }\n async getFeature(api: mastodon.Client) {\n this._isReady = true;\n this.feature = await this.featureGetter(api);\n }\n async score(api: mastodon.Client, status: StatusType): Promise<number> {\n if (!this._isReady) {\n await this.getFeature(api);\n this._isReady = true;\n }", "score": 0.8635902404785156 }, { "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": 0.859795331954956 }, { "filename": "src/features/favsFeature.ts", "retrieved_chunk": "import { login, mastodon } from \"masto\";\nimport { accFeatureType } from \"../types\";\nexport default async function favFeature(api: mastodon.Client): Promise<accFeatureType> {\n let results: mastodon.v1.Status[] = [];\n let pages = 3;\n for await (const page of api.v1.favourites.list({ limit: 80 })) {\n results = results.concat(page)\n pages--;\n if (pages === 0 || results.length < 80) {\n break;", "score": 0.8514896631240845 } ]
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/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": 0.8660422563552856 }, { "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": 0.8507499694824219 }, { "filename": "src/weights/weightsStore.ts", "retrieved_chunk": " await this.setWeights({ [verboseName]: defaultWeight }, verboseName);\n return true;\n }\n return false;\n }\n}", "score": 0.8493695259094238 }, { "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": 0.8218010663986206 }, { "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": 0.8212395906448364 } ]
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/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": 0.8349789977073669 }, { "filename": "src/scorer/feed/reblogsFeedScorer.ts", "retrieved_chunk": "import FeedScorer from \"../FeedScorer\";\nimport { StatusType } from \"../../types\";\nimport { mastodon } from \"masto\";\nexport default class reblogsFeedScorer extends FeedScorer {\n constructor() {\n super(\"reblogsFeed\", \"More Weight to posts that are reblogged a lot\", 6);\n }\n feedExtractor(feed: StatusType[]) {\n return feed.reduce((obj: any, status) => {\n if (status.reblog) {", "score": 0.8184522986412048 }, { "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": 0.817823588848114 }, { "filename": "src/features/favsFeature.ts", "retrieved_chunk": " }\n }\n const favFrequ = results.reduce((accumulator: accFeatureType, status: mastodon.v1.Status,) => {\n if (!status.account) return accumulator;\n if (status.account.acct in accumulator) {\n accumulator[status.account.acct] += 1;\n } else {\n accumulator[status.account.acct] = 1;\n }\n return accumulator", "score": 0.8095220923423767 }, { "filename": "src/features/interactsFeature.ts", "retrieved_chunk": " }\n }\n const interactFrequ = results.reduce((accumulator: any, status: mastodon.v1.Status,) => {\n if (!status.account) return accumulator;\n if (status.account.acct in accumulator) {\n accumulator[status.account.acct] += 1;\n } else {\n accumulator[status.account.acct] = 1;\n }\n return accumulator", "score": 0.8032060861587524 } ]
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/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": 0.9127753973007202 }, { "filename": "src/scorer/FeatureScorer.ts", "retrieved_chunk": " }\n async getFeature(api: mastodon.Client) {\n this._isReady = true;\n this.feature = await this.featureGetter(api);\n }\n async score(api: mastodon.Client, status: StatusType): Promise<number> {\n if (!this._isReady) {\n await this.getFeature(api);\n this._isReady = true;\n }", "score": 0.8758872747421265 }, { "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": 0.8637441992759705 }, { "filename": "src/features/favsFeature.ts", "retrieved_chunk": "import { login, mastodon } from \"masto\";\nimport { accFeatureType } from \"../types\";\nexport default async function favFeature(api: mastodon.Client): Promise<accFeatureType> {\n let results: mastodon.v1.Status[] = [];\n let pages = 3;\n for await (const page of api.v1.favourites.list({ limit: 80 })) {\n results = results.concat(page)\n pages--;\n if (pages === 0 || results.length < 80) {\n break;", "score": 0.8495036363601685 }, { "filename": "src/features/interactsFeature.ts", "retrieved_chunk": "import { mastodon } from \"masto\";\nimport { accFeatureType } from \"../types\";\nexport default async function interactFeature(api: mastodon.Client): Promise<accFeatureType> {\n let results: any[] = [];\n let pages = 3;\n for await (const page of api.v1.notifications.list({ limit: 80 })) {\n results = results.concat(page)\n pages--;\n if (pages === 0 || results.length < 80) {\n break;", "score": 0.8418898582458496 } ]
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/scorer/FeatureScorer.ts", "retrieved_chunk": " }\n async getFeature(api: mastodon.Client) {\n this._isReady = true;\n this.feature = await this.featureGetter(api);\n }\n async score(api: mastodon.Client, status: StatusType): Promise<number> {\n if (!this._isReady) {\n await this.getFeature(api);\n this._isReady = true;\n }", "score": 0.8519713878631592 }, { "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": 0.8477433919906616 }, { "filename": "src/scorer/FeatureScorer.ts", "retrieved_chunk": "import { mastodon } from \"masto\"\nimport { StatusType, accFeatureType } from \"../types\";\ninterface RankParams {\n featureGetter: (api: mastodon.Client) => Promise<accFeatureType>,\n verboseName: string,\n description?: string,\n defaultWeight?: number,\n}\nexport default class FeatureScorer {\n featureGetter: (api: mastodon.Client) => Promise<accFeatureType>;", "score": 0.8447080254554749 }, { "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": 0.8362196087837219 }, { "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": 0.8294936418533325 } ]
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": 0.8917946815490723 }, { "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": 0.8626022338867188 }, { "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": 0.8537129163742065 }, { "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": 0.8474435806274414 }, { "filename": "src/weights/weightsStore.ts", "retrieved_chunk": " await this.setWeights({ [verboseName]: defaultWeight }, verboseName);\n return true;\n }\n return false;\n }\n}", "score": 0.8316787481307983 } ]
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": "\t| 'setTimeout'\n\t| 'setInterval'\n\t| 'playTune'\n>\nexport const imageDataEngine = (): {\n\tapi: ImageDataEngineAPI,\n\trender(): ImageData,\n\tbutton(key: InputKey): void,\n\tcleanup(): void,\n\tstate: GameState", "score": 0.8531284928321838 }, { "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": 0.8518000841140747 }, { "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": 0.8509616851806641 }, { "filename": "src/image-data/index.ts", "retrieved_chunk": "} => {\n\tconst game = baseEngine()\n\tlet legendImages: Record<string, ImageData> = {}\n\tlet background: string = '.'\n\tconst timeouts: number[] = []\n\tconst intervals: number[] = []\n\tconst keyHandlers: Record<InputKey, (() => void)[]> = {\n\t\tw: [],\n\t\ts: [],\n\t\ta: [],", "score": 0.8396528959274292 }, { "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": 0.8391439318656921 } ]
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": 0.8647588491439819 }, { "filename": "src/image-data/index.ts", "retrieved_chunk": "\t\t\tconst out = new ImageData(sw, sh)\n\t\t\tout.data.fill(255)\n\t\t\tfor (const t of game.api.getGrid().flat()) {\n\t\t\t\tconst img = legendImages[t.type ?? background]\n\t\t\t\tif (!img) continue\n\t\t\t\tfor (let x = 0; x < tSize(); x++)\n\t\t\t\t\tfor (let y = 0; y < tSize(); y++) {\n\t\t\t\t\t\tconst tx = t.x * tSize() + x\n\t\t\t\t\t\tconst ty = t.y * tSize() + y\n\t\t\t\t\t\tconst src_alpha = img.data[(y * 16 + x) * 4 + 3]", "score": 0.836401104927063 }, { "filename": "src/base/index.ts", "retrieved_chunk": "\t\tif (y < 0) return []\n\t\tif (x < 0) return []\n\t\tif (y >= gameState.dimensions.height) return []\n\t\tif (x >= gameState.dimensions.width) return []\n\t\treturn getGrid()[gameState.dimensions.width*y+x] ?? []\n\t}\n\tconst _hasDuplicates = <T>(array: T[]): boolean => (new Set(array)).size !== array.length\n\tconst tilesWith = (...matchingTypes: string[]): SpriteType[][] => {\n\t\tconst { width, height } = gameState.dimensions\n\t\tconst tiles: SpriteType[][] = []", "score": 0.8362153768539429 }, { "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": 0.8355581760406494 }, { "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": 0.8331689834594727 } ]
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": 0.8396469950675964 }, { "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": 0.8303849101066589 }, { "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": 0.8198524713516235 }, { "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": 0.8111871480941772 }, { "filename": "src/web/text.ts", "retrieved_chunk": "import type { TextElement } from '../api.js'\nimport { font, composeText } from '../base/index.js'\nimport { makeCanvas } from './util.js'\nexport const getTextImg = (texts: TextElement[]): CanvasImageSource => {\n\tconst charGrid = composeText(texts)\n\tconst img = new ImageData(160, 128)\n\timg.data.fill(0)\n\tfor (const [i, row] of Object.entries(charGrid)) {\n\t\tlet xt = 0\n\t\tfor (const { char, color } of row) {", "score": 0.8055598139762878 } ]
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\tconst [, pitchRaw, instrumentRaw, durationRaw] = noteRaw.match(/^(.+)([~\\-^\\/])(.+)$/)!\n\t\t\treturn [\n\t\t\t\tinstrumentKey[instrumentRaw!] ?? 'sine',\n\t\t\t\tisNaN(parseInt(pitchRaw ?? '', 10)) ? pitchRaw! : parseInt(pitchRaw!, 10),\n\t\t\t\tparseInt(durationRaw ?? '0', 10)\n\t\t\t]\n\t\t})\n\t\ttune.push([duration, ...notes].flat())\n\t}\n\treturn tune as Tune", "score": 0.8474364876747131 }, { "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": 0.8285739421844482 }, { "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": 0.820509672164917 }, { "filename": "src/base/tune.ts", "retrieved_chunk": "import { type Tune, instrumentKey, InstrumentType, reverseInstrumentKey } from '../api.js'\nexport const textToTune = (text: string): Tune => {\n\tconst elements = text.replace(/\\s/g, '').split(',')\n\tconst tune = []\n\tfor (const element of elements) {\n\t\tif (!element) continue\n\t\tconst [durationRaw, notesRaw] = element.split(':')\n\t\tconst duration = Math.round(parseInt(durationRaw ?? '0', 10))\n\t\tconst notes = (notesRaw || '').split('+').map((noteRaw) => {\n\t\t\tif (!noteRaw) return []", "score": 0.7986050844192505 }, { "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": 0.7970795035362244 } ]
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": "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": 0.823823094367981 }, { "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": 0.8120917677879333 }, { "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": 0.8041962385177612 }, { "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": 0.7895416617393494 }, { "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": 0.7894464731216431 } ]
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": 0.8454703092575073 }, { "filename": "src/web/text.ts", "retrieved_chunk": "import type { TextElement } from '../api.js'\nimport { font, composeText } from '../base/index.js'\nimport { makeCanvas } from './util.js'\nexport const getTextImg = (texts: TextElement[]): CanvasImageSource => {\n\tconst charGrid = composeText(texts)\n\tconst img = new ImageData(160, 128)\n\timg.data.fill(0)\n\tfor (const [i, row] of Object.entries(charGrid)) {\n\t\tlet xt = 0\n\t\tfor (const { char, color } of row) {", "score": 0.8264901638031006 }, { "filename": "src/image-data/index.ts", "retrieved_chunk": "} => {\n\tconst game = baseEngine()\n\tlet legendImages: Record<string, ImageData> = {}\n\tlet background: string = '.'\n\tconst timeouts: number[] = []\n\tconst intervals: number[] = []\n\tconst keyHandlers: Record<InputKey, (() => void)[]> = {\n\t\tw: [],\n\t\ts: [],\n\t\ta: [],", "score": 0.8191822171211243 }, { "filename": "src/image-data/bitmap.ts", "retrieved_chunk": "import { palette } from '../base/index.js'\n// At odds with in-game behavior... doesn't enforce a size with stretching.\nexport const bitmapTextToImageData = (text: string): ImageData => {\n const rows = text.trim().split(\"\\n\").map(x => x.trim())\n const rowLengths = rows.map(x => x.length)\n const isRect = rowLengths.every(val => val === rowLengths[0])\n if (!isRect) throw new Error(\"Level must be rect.\")\n const width = rows[0]!.length || 1\n const height = rows.length || 1\n const data = new Uint8ClampedArray(width*height*4)", "score": 0.8183023929595947 }, { "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": 0.7999820709228516 } ]
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": 0.8631100654602051 }, { "filename": "src/base/index.ts", "retrieved_chunk": "\t\tif (y < 0) return []\n\t\tif (x < 0) return []\n\t\tif (y >= gameState.dimensions.height) return []\n\t\tif (x >= gameState.dimensions.width) return []\n\t\treturn getGrid()[gameState.dimensions.width*y+x] ?? []\n\t}\n\tconst _hasDuplicates = <T>(array: T[]): boolean => (new Set(array)).size !== array.length\n\tconst tilesWith = (...matchingTypes: string[]): SpriteType[][] => {\n\t\tconst { width, height } = gameState.dimensions\n\t\tconst tiles: SpriteType[][] = []", "score": 0.8367967009544373 }, { "filename": "src/image-data/index.ts", "retrieved_chunk": "\t\t\tconst out = new ImageData(sw, sh)\n\t\t\tout.data.fill(255)\n\t\t\tfor (const t of game.api.getGrid().flat()) {\n\t\t\t\tconst img = legendImages[t.type ?? background]\n\t\t\t\tif (!img) continue\n\t\t\t\tfor (let x = 0; x < tSize(); x++)\n\t\t\t\t\tfor (let y = 0; y < tSize(); y++) {\n\t\t\t\t\t\tconst tx = t.x * tSize() + x\n\t\t\t\t\t\tconst ty = t.y * tSize() + y\n\t\t\t\t\t\tconst src_alpha = img.data[(y * 16 + x) * 4 + 3]", "score": 0.8357490301132202 }, { "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": 0.830807089805603 }, { "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": 0.8277037143707275 } ]
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": 0.839011549949646 }, { "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": 0.8343543410301208 }, { "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": 0.8339536190032959 }, { "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": 0.8307528495788574 }, { "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": 0.8205151557922363 } ]
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": "\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": 0.8527982234954834 }, { "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": 0.8144745230674744 }, { "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": 0.8094831705093384 }, { "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": 0.8080407381057739 }, { "filename": "src/image-data/index.ts", "retrieved_chunk": "} => {\n\tconst game = baseEngine()\n\tlet legendImages: Record<string, ImageData> = {}\n\tlet background: string = '.'\n\tconst timeouts: number[] = []\n\tconst intervals: number[] = []\n\tconst keyHandlers: Record<InputKey, (() => void)[]> = {\n\t\tw: [],\n\t\ts: [],\n\t\ta: [],", "score": 0.7960735559463501 } ]
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": 0.839011549949646 }, { "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": 0.8343543410301208 }, { "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": 0.8339536190032959 }, { "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": 0.8307528495788574 }, { "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": 0.8205151557922363 } ]
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/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": 0.8024713397026062 }, { "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": 0.7863765954971313 }, { "filename": "src/web/index.ts", "retrieved_chunk": "\tcleanup(): void\n} {\n\tconst { api, state } = baseEngine()\n\tconst ctx = canvas.getContext('2d')!\n\tconst offscreenCanvas = makeCanvas(1, 1)\n\tconst offscreenCtx = offscreenCanvas.getContext('2d')!\n\tconst _bitmaps: Record<string, CanvasImageSource> = {}\n\tlet _zOrder: string[] = []\n\tctx.imageSmoothingEnabled = false\n\tconst _gameloop = (): void => {", "score": 0.7810414433479309 }, { "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": 0.7789319157600403 }, { "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": 0.7604936957359314 } ]
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": 0.8621301651000977 }, { "filename": "src/image-data/index.ts", "retrieved_chunk": "\t| 'setTimeout'\n\t| 'setInterval'\n\t| 'playTune'\n>\nexport const imageDataEngine = (): {\n\tapi: ImageDataEngineAPI,\n\trender(): ImageData,\n\tbutton(key: InputKey): void,\n\tcleanup(): void,\n\tstate: GameState", "score": 0.8595179319381714 }, { "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": 0.8582544326782227 }, { "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": 0.8458268046379089 }, { "filename": "src/image-data/index.ts", "retrieved_chunk": "} => {\n\tconst game = baseEngine()\n\tlet legendImages: Record<string, ImageData> = {}\n\tlet background: string = '.'\n\tconst timeouts: number[] = []\n\tconst intervals: number[] = []\n\tconst keyHandlers: Record<InputKey, (() => void)[]> = {\n\t\tw: [],\n\t\ts: [],\n\t\ta: [],", "score": 0.841688871383667 } ]
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\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": 0.883132815361023 }, { "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": 0.8534677028656006 }, { "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": 0.8318328261375427 }, { "filename": "src/image-data/index.ts", "retrieved_chunk": "} => {\n\tconst game = baseEngine()\n\tlet legendImages: Record<string, ImageData> = {}\n\tlet background: string = '.'\n\tconst timeouts: number[] = []\n\tconst intervals: number[] = []\n\tconst keyHandlers: Record<InputKey, (() => void)[]> = {\n\t\tw: [],\n\t\ts: [],\n\t\ta: [],", "score": 0.8154132962226868 }, { "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": 0.8023934364318848 } ]
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\tconst [, pitchRaw, instrumentRaw, durationRaw] = noteRaw.match(/^(.+)([~\\-^\\/])(.+)$/)!\n\t\t\treturn [\n\t\t\t\tinstrumentKey[instrumentRaw!] ?? 'sine',\n\t\t\t\tisNaN(parseInt(pitchRaw ?? '', 10)) ? pitchRaw! : parseInt(pitchRaw!, 10),\n\t\t\t\tparseInt(durationRaw ?? '0', 10)\n\t\t\t]\n\t\t})\n\t\ttune.push([duration, ...notes].flat())\n\t}\n\treturn tune as Tune", "score": 0.8238589763641357 }, { "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": 0.822955846786499 }, { "filename": "src/web/index.ts", "retrieved_chunk": "\t\t\t\tconst tune = textToTune(text)\n\t\t\t\tconst playTuneRes = playTune(tune, n)\n\t\t\t\ttunes.push(playTuneRes)\n\t\t\t\treturn playTuneRes\n\t\t\t}\n\t\t},\n\t\tstate,\n\t\tcleanup: () => {\n\t\t\tctx.clearRect(0, 0, canvas.width, canvas.height)\n\t\t\twindow.cancelAnimationFrame(animationId)", "score": 0.8106647729873657 }, { "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": 0.8063323497772217 }, { "filename": "src/web/index.ts", "retrieved_chunk": "\tconst afterInput = (fn: () => void): void => { afterInputs.push(fn) }\n\tconst tunes: PlayTuneRes[] = []\n\treturn {\n\t\tapi: {\n\t\t\t...api,\n\t\t\tsetLegend,\n\t\t\tonInput, \n\t\t\tafterInput,\n\t\t\tgetState: () => state,\n\t\t\tplayTune: (text: string, n: number) => {", "score": 0.8042342662811279 } ]
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\tconst [, pitchRaw, instrumentRaw, durationRaw] = noteRaw.match(/^(.+)([~\\-^\\/])(.+)$/)!\n\t\t\treturn [\n\t\t\t\tinstrumentKey[instrumentRaw!] ?? 'sine',\n\t\t\t\tisNaN(parseInt(pitchRaw ?? '', 10)) ? pitchRaw! : parseInt(pitchRaw!, 10),\n\t\t\t\tparseInt(durationRaw ?? '0', 10)\n\t\t\t]\n\t\t})\n\t\ttune.push([duration, ...notes].flat())\n\t}\n\treturn tune as Tune", "score": 0.8263978958129883 }, { "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": 0.8157949447631836 }, { "filename": "src/web/index.ts", "retrieved_chunk": "\t\t\t\tconst tune = textToTune(text)\n\t\t\t\tconst playTuneRes = playTune(tune, n)\n\t\t\t\ttunes.push(playTuneRes)\n\t\t\t\treturn playTuneRes\n\t\t\t}\n\t\t},\n\t\tstate,\n\t\tcleanup: () => {\n\t\t\tctx.clearRect(0, 0, canvas.width, canvas.height)\n\t\t\twindow.cancelAnimationFrame(animationId)", "score": 0.8146383762359619 }, { "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": 0.8100428581237793 }, { "filename": "src/web/index.ts", "retrieved_chunk": "\tconst afterInput = (fn: () => void): void => { afterInputs.push(fn) }\n\tconst tunes: PlayTuneRes[] = []\n\treturn {\n\t\tapi: {\n\t\t\t...api,\n\t\t\tsetLegend,\n\t\t\tonInput, \n\t\t\tafterInput,\n\t\t\tgetState: () => state,\n\t\t\tplayTune: (text: string, n: number) => {", "score": 0.8090213537216187 } ]
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": "\t| 'setTimeout'\n\t| 'setInterval'\n\t| 'playTune'\n>\nexport const imageDataEngine = (): {\n\tapi: ImageDataEngineAPI,\n\trender(): ImageData,\n\tbutton(key: InputKey): void,\n\tcleanup(): void,\n\tstate: GameState", "score": 0.8561234474182129 }, { "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": 0.8546847105026245 }, { "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": 0.8506119251251221 }, { "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": 0.8391174674034119 }, { "filename": "src/image-data/index.ts", "retrieved_chunk": "} => {\n\tconst game = baseEngine()\n\tlet legendImages: Record<string, ImageData> = {}\n\tlet background: string = '.'\n\tconst timeouts: number[] = []\n\tconst intervals: number[] = []\n\tconst keyHandlers: Record<InputKey, (() => void)[]> = {\n\t\tw: [],\n\t\ts: [],\n\t\ta: [],", "score": 0.8386354446411133 } ]
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": "\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": 0.8452147245407104 }, { "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": 0.8142219185829163 }, { "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": 0.8141339421272278 }, { "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": 0.8057945370674133 }, { "filename": "src/image-data/index.ts", "retrieved_chunk": "} => {\n\tconst game = baseEngine()\n\tlet legendImages: Record<string, ImageData> = {}\n\tlet background: string = '.'\n\tconst timeouts: number[] = []\n\tconst intervals: number[] = []\n\tconst keyHandlers: Record<InputKey, (() => void)[]> = {\n\t\tw: [],\n\t\ts: [],\n\t\ta: [],", "score": 0.7835466861724854 } ]
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/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": 0.8349252939224243 }, { "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": 0.8028289079666138 }, { "filename": "src/image-data/bitmap.ts", "retrieved_chunk": "import { palette } from '../base/index.js'\n// At odds with in-game behavior... doesn't enforce a size with stretching.\nexport const bitmapTextToImageData = (text: string): ImageData => {\n const rows = text.trim().split(\"\\n\").map(x => x.trim())\n const rowLengths = rows.map(x => x.length)\n const isRect = rowLengths.every(val => val === rowLengths[0])\n if (!isRect) throw new Error(\"Level must be rect.\")\n const width = rows[0]!.length || 1\n const height = rows.length || 1\n const data = new Uint8ClampedArray(width*height*4)", "score": 0.7986098527908325 }, { "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": 0.7968100905418396 }, { "filename": "src/web/text.ts", "retrieved_chunk": "import type { TextElement } from '../api.js'\nimport { font, composeText } from '../base/index.js'\nimport { makeCanvas } from './util.js'\nexport const getTextImg = (texts: TextElement[]): CanvasImageSource => {\n\tconst charGrid = composeText(texts)\n\tconst img = new ImageData(160, 128)\n\timg.data.fill(0)\n\tfor (const [i, row] of Object.entries(charGrid)) {\n\t\tlet xt = 0\n\t\tfor (const { char, color } of row) {", "score": 0.7889372110366821 } ]
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/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": 0.8628924489021301 }, { "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": 0.8499507904052734 }, { "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": 0.8297483921051025 }, { "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": 0.8094044923782349 }, { "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": 0.8057191371917725 } ]
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": 0.8548176288604736 }, { "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": 0.8435636162757874 }, { "filename": "src/image-data/index.ts", "retrieved_chunk": "} => {\n\tconst game = baseEngine()\n\tlet legendImages: Record<string, ImageData> = {}\n\tlet background: string = '.'\n\tconst timeouts: number[] = []\n\tconst intervals: number[] = []\n\tconst keyHandlers: Record<InputKey, (() => void)[]> = {\n\t\tw: [],\n\t\ts: [],\n\t\ta: [],", "score": 0.8059271574020386 }, { "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": 0.8058174848556519 }, { "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": 0.8025856614112854 } ]
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": "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": 0.8269287347793579 }, { "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": 0.8152977228164673 }, { "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": 0.807289719581604 }, { "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": 0.7921711206436157 }, { "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": 0.7900639772415161 } ]
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/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": 0.8229917883872986 }, { "filename": "src/base/tune.ts", "retrieved_chunk": "\t\t\tconst [, pitchRaw, instrumentRaw, durationRaw] = noteRaw.match(/^(.+)([~\\-^\\/])(.+)$/)!\n\t\t\treturn [\n\t\t\t\tinstrumentKey[instrumentRaw!] ?? 'sine',\n\t\t\t\tisNaN(parseInt(pitchRaw ?? '', 10)) ? pitchRaw! : parseInt(pitchRaw!, 10),\n\t\t\t\tparseInt(durationRaw ?? '0', 10)\n\t\t\t]\n\t\t})\n\t\ttune.push([duration, ...notes].flat())\n\t}\n\treturn tune as Tune", "score": 0.8213107585906982 }, { "filename": "src/web/index.ts", "retrieved_chunk": "\t\t\t\tconst tune = textToTune(text)\n\t\t\t\tconst playTuneRes = playTune(tune, n)\n\t\t\t\ttunes.push(playTuneRes)\n\t\t\t\treturn playTuneRes\n\t\t\t}\n\t\t},\n\t\tstate,\n\t\tcleanup: () => {\n\t\t\tctx.clearRect(0, 0, canvas.width, canvas.height)\n\t\t\twindow.cancelAnimationFrame(animationId)", "score": 0.8102827072143555 }, { "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": 0.8062925338745117 }, { "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": 0.8043270111083984 } ]
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": 0.8010631799697876 }, { "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": 0.7872775793075562 }, { "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": 0.7817812561988831 }, { "filename": "src/web/index.ts", "retrieved_chunk": "\tcleanup(): void\n} {\n\tconst { api, state } = baseEngine()\n\tconst ctx = canvas.getContext('2d')!\n\tconst offscreenCanvas = makeCanvas(1, 1)\n\tconst offscreenCtx = offscreenCanvas.getContext('2d')!\n\tconst _bitmaps: Record<string, CanvasImageSource> = {}\n\tlet _zOrder: string[] = []\n\tctx.imageSmoothingEnabled = false\n\tconst _gameloop = (): void => {", "score": 0.7809685468673706 }, { "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": 0.7651774883270264 } ]
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": 0.8631604313850403 }, { "filename": "src/base/index.ts", "retrieved_chunk": "\t\tif (y < 0) return []\n\t\tif (x < 0) return []\n\t\tif (y >= gameState.dimensions.height) return []\n\t\tif (x >= gameState.dimensions.width) return []\n\t\treturn getGrid()[gameState.dimensions.width*y+x] ?? []\n\t}\n\tconst _hasDuplicates = <T>(array: T[]): boolean => (new Set(array)).size !== array.length\n\tconst tilesWith = (...matchingTypes: string[]): SpriteType[][] => {\n\t\tconst { width, height } = gameState.dimensions\n\t\tconst tiles: SpriteType[][] = []", "score": 0.8359565734863281 }, { "filename": "src/image-data/index.ts", "retrieved_chunk": "\t\t\tconst out = new ImageData(sw, sh)\n\t\t\tout.data.fill(255)\n\t\t\tfor (const t of game.api.getGrid().flat()) {\n\t\t\t\tconst img = legendImages[t.type ?? background]\n\t\t\t\tif (!img) continue\n\t\t\t\tfor (let x = 0; x < tSize(); x++)\n\t\t\t\t\tfor (let y = 0; y < tSize(); y++) {\n\t\t\t\t\t\tconst tx = t.x * tSize() + x\n\t\t\t\t\t\tconst ty = t.y * tSize() + y\n\t\t\t\t\t\tconst src_alpha = img.data[(y * 16 + x) * 4 + 3]", "score": 0.8350563049316406 }, { "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": 0.8297154903411865 }, { "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": 0.8281192183494568 } ]
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\tconst [, pitchRaw, instrumentRaw, durationRaw] = noteRaw.match(/^(.+)([~\\-^\\/])(.+)$/)!\n\t\t\treturn [\n\t\t\t\tinstrumentKey[instrumentRaw!] ?? 'sine',\n\t\t\t\tisNaN(parseInt(pitchRaw ?? '', 10)) ? pitchRaw! : parseInt(pitchRaw!, 10),\n\t\t\t\tparseInt(durationRaw ?? '0', 10)\n\t\t\t]\n\t\t})\n\t\ttune.push([duration, ...notes].flat())\n\t}\n\treturn tune as Tune", "score": 0.8396328687667847 }, { "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": 0.8262019157409668 }, { "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": 0.8174009323120117 }, { "filename": "src/base/tune.ts", "retrieved_chunk": "import { type Tune, instrumentKey, InstrumentType, reverseInstrumentKey } from '../api.js'\nexport const textToTune = (text: string): Tune => {\n\tconst elements = text.replace(/\\s/g, '').split(',')\n\tconst tune = []\n\tfor (const element of elements) {\n\t\tif (!element) continue\n\t\tconst [durationRaw, notesRaw] = element.split(':')\n\t\tconst duration = Math.round(parseInt(durationRaw ?? '0', 10))\n\t\tconst notes = (notesRaw || '').split('+').map((noteRaw) => {\n\t\t\tif (!noteRaw) return []", "score": 0.8011761903762817 }, { "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": 0.7934941649436951 } ]
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/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": 0.8636369109153748 }, { "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": 0.8406389355659485 }, { "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": 0.8382630348205566 }, { "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": 0.8323642015457153 }, { "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": 0.8286311626434326 } ]
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": "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": 0.8230551481246948 }, { "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": 0.8124996423721313 }, { "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": 0.8020948171615601 }, { "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": 0.790128231048584 }, { "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": 0.7875863313674927 } ]
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": 0.8750437498092651 }, { "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": 0.8311779499053955 }, { "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": 0.8269773721694946 }, { "filename": "src/index.ts", "retrieved_chunk": "import { executePrompt, executePromptStream } from \"./executePrompt.js\";\nimport { loadConfig } from \"./config.js\";\nimport { loadPromptConfig, listPrompts } from \"./loadPromptConfig.js\";\nimport { APPNAME } from \"./types.js\";\nimport FileSystemKVS from \"./kvs/kvs-filesystem.js\";\nimport { AppError } from \"./errors.js\";\nimport { readFileSync } from \"node:fs\";\nfunction parseArgs(argv: string[]) {\n const [_nodeBin, _jsFile, promptId, ...rest] = argv;\n const input = rest.join(\" \");", "score": 0.8246215581893921 }, { "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": 0.8230517506599426 } ]
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": 0.8916809558868408 }, { "filename": "src/index.ts", "retrieved_chunk": "import { executePrompt, executePromptStream } from \"./executePrompt.js\";\nimport { loadConfig } from \"./config.js\";\nimport { loadPromptConfig, listPrompts } from \"./loadPromptConfig.js\";\nimport { APPNAME } from \"./types.js\";\nimport FileSystemKVS from \"./kvs/kvs-filesystem.js\";\nimport { AppError } from \"./errors.js\";\nimport { readFileSync } from \"node:fs\";\nfunction parseArgs(argv: string[]) {\n const [_nodeBin, _jsFile, promptId, ...rest] = argv;\n const input = rest.join(\" \");", "score": 0.8470360040664673 }, { "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": 0.8467581272125244 }, { "filename": "src/index.ts", "retrieved_chunk": "}\nexport async function cli() {\n try {\n const config = loadConfig();\n const { promptId, input: argvInput } = parseArgs(process.argv);\n if (promptId === \"--list\") {\n const prompts = await listPrompts(config);\n console.log(\n prompts\n .map((p) => {", "score": 0.8368813991546631 }, { "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": 0.8297359347343445 } ]
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": " ]);\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": 0.8761653900146484 }, { "filename": "src/bin/cli.ts", "retrieved_chunk": "#!/usr/bin/env node\nimport { cli } from \"../index.js\";\nawait cli();", "score": 0.8663622140884399 }, { "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": 0.8461982607841492 }, { "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": 0.8442634344100952 }, { "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": 0.8412438631057739 } ]
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/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": 0.8850665092468262 }, { "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": 0.8626149892807007 }, { "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": 0.8612134456634521 }, { "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": 0.8486589789390564 }, { "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": 0.8485251665115356 } ]
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": 0.8534845113754272 }, { "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": 0.8505395650863647 }, { "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": 0.8471535444259644 }, { "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": 0.8388116359710693 }, { "filename": "src/prompts/eli5.ts", "retrieved_chunk": "export default promptConfiguration;", "score": 0.8275977373123169 } ]
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": 0.8931363821029663 }, { "filename": "src/index.ts", "retrieved_chunk": "import { executePrompt, executePromptStream } from \"./executePrompt.js\";\nimport { loadConfig } from \"./config.js\";\nimport { loadPromptConfig, listPrompts } from \"./loadPromptConfig.js\";\nimport { APPNAME } from \"./types.js\";\nimport FileSystemKVS from \"./kvs/kvs-filesystem.js\";\nimport { AppError } from \"./errors.js\";\nimport { readFileSync } from \"node:fs\";\nfunction parseArgs(argv: string[]) {\n const [_nodeBin, _jsFile, promptId, ...rest] = argv;\n const input = rest.join(\" \");", "score": 0.852083683013916 }, { "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": 0.8511885404586792 }, { "filename": "src/index.ts", "retrieved_chunk": "}\nexport async function cli() {\n try {\n const config = loadConfig();\n const { promptId, input: argvInput } = parseArgs(process.argv);\n if (promptId === \"--list\") {\n const prompts = await listPrompts(config);\n console.log(\n prompts\n .map((p) => {", "score": 0.8440853357315063 }, { "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": 0.8345014452934265 } ]
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/index.ts", "retrieved_chunk": "import { executePrompt, executePromptStream } from \"./executePrompt.js\";\nimport { loadConfig } from \"./config.js\";\nimport { loadPromptConfig, listPrompts } from \"./loadPromptConfig.js\";\nimport { APPNAME } from \"./types.js\";\nimport FileSystemKVS from \"./kvs/kvs-filesystem.js\";\nimport { AppError } from \"./errors.js\";\nimport { readFileSync } from \"node:fs\";\nfunction parseArgs(argv: string[]) {\n const [_nodeBin, _jsFile, promptId, ...rest] = argv;\n const input = rest.join(\" \");", "score": 0.8188029527664185 }, { "filename": "src/index.ts", "retrieved_chunk": "}\nexport async function cli() {\n try {\n const config = loadConfig();\n const { promptId, input: argvInput } = parseArgs(process.argv);\n if (promptId === \"--list\") {\n const prompts = await listPrompts(config);\n console.log(\n prompts\n .map((p) => {", "score": 0.8085567951202393 }, { "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": 0.8084807395935059 }, { "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": 0.8079374432563782 }, { "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": 0.8007886409759521 } ]
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": " 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": 0.8645392060279846 }, { "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": 0.8504729270935059 }, { "filename": "src/resource/nip07-provider.ts", "retrieved_chunk": " const messageId = Math.floor(Math.random() * 1000000);\n const message: CrxRpcRequestMessage = {\n ext,\n messageId,\n src: 'nip07-provider',\n path,\n payload: req,\n };\n window.addEventListener('message', listener);\n window.postMessage(message, '*');", "score": 0.8428415656089783 }, { "filename": "src/background/index.ts", "retrieved_chunk": "import { handleCrxRpcRequest } from '../lib/messaging';\nimport { signEvent } from '../lib/nostr';\nimport { getKeyPair, getSignPower, setSignPower } from '../lib/store';\n// * -> ...\nchrome.runtime.onMessage.addListener((msg: CrxRpcRequestMessage, sender, _sendResponse) => {\n const { next, shouldBeHandled } = handleCrxRpcRequest(msg, 'background');\n if (!shouldBeHandled) {\n return;\n }\n const payload = msg.payload;", "score": 0.8418560028076172 }, { "filename": "src/lib/ring-con.ts", "retrieved_chunk": " );\n // get_ext_data_59\n await communicate(\n joycon,\n [0x59],\n [\n [14, 0x59],\n [16, 0x20],\n ],\n );", "score": 0.8417816162109375 } ]
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/@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": 0.8531366586685181 }, { "filename": "src/lib/nostr.ts", "retrieved_chunk": " unsignedEvent: UnsignedEvent,\n): Promise<SignedEvent> {\n const { created_at, kind, tags, content } = unsignedEvent;\n const id = secp256k1.utils.bytesToHex(\n sha256(utf8Encoder.encode(JSON.stringify([0, pubkey, created_at, kind, tags, content]))),\n );\n const sig = secp256k1.utils.bytesToHex(secp256k1.schnorr.signSync(id, seckey));\n return {\n id,\n pubkey,", "score": 0.8335388898849487 }, { "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": 0.8120384216308594 }, { "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": 0.8107807636260986 }, { "filename": "src/resource/nip07-provider.ts", "retrieved_chunk": " },\n ['content', 'background'],\n );\n return rpc(\n {\n kind: 'signEvent',\n request: event,\n },\n ['content', 'background'],\n );", "score": 0.808124303817749 } ]
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/@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": 0.8513618111610413 }, { "filename": "src/lib/nostr.ts", "retrieved_chunk": " unsignedEvent: UnsignedEvent,\n): Promise<SignedEvent> {\n const { created_at, kind, tags, content } = unsignedEvent;\n const id = secp256k1.utils.bytesToHex(\n sha256(utf8Encoder.encode(JSON.stringify([0, pubkey, created_at, kind, tags, content]))),\n );\n const sig = secp256k1.utils.bytesToHex(secp256k1.schnorr.signSync(id, seckey));\n return {\n id,\n pubkey,", "score": 0.8300842642784119 }, { "filename": "src/resource/nip07-provider.ts", "retrieved_chunk": " },\n ['content', 'background'],\n );\n return rpc(\n {\n kind: 'signEvent',\n request: event,\n },\n ['content', 'background'],\n );", "score": 0.8149354457855225 }, { "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": 0.8060094714164734 }, { "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": 0.8034043312072754 } ]
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": 0.8922743797302246 }, { "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": 0.8873039484024048 }, { "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": 0.8714563846588135 }, { "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": 0.8517381548881531 }, { "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": 0.834199070930481 } ]
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": " const response = (\n await asyncIterableToArray(\n executePromptStream(promptConfig, input, config, cache)\n )\n ).join(\"\");\n return parseResponse(response, input);\n}\nexport default executePrompt;", "score": 0.8762573003768921 }, { "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": 0.8749727010726929 }, { "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": 0.8711023926734924 }, { "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": 0.8542191982269287 }, { "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": 0.849511981010437 } ]
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/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": 0.8485596179962158 }, { "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": 0.8408994674682617 }, { "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": 0.83990079164505 }, { "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": 0.8382407426834106 }, { "filename": "src/prompts/eli5.ts", "retrieved_chunk": "export default promptConfiguration;", "score": 0.8287746906280518 } ]
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/lib/ring-con.ts", "retrieved_chunk": " // timeout: 5000,\n },\n );\n}\nexport function getStrain(event: HIDInputReportEvent) {\n if (event.reportId === 0x30) {\n return new DataView(event.data.buffer, 38, 2).getInt16(0, true);\n } else {\n return null;\n }", "score": 0.8621541261672974 }, { "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": 0.8432885408401489 }, { "filename": "src/lib/ring-con.ts", "retrieved_chunk": " }\n const data = new Uint8Array(event.data.buffer);\n if (expected.every(([pos, val]) => data[pos - 1] === val)) {\n resolve();\n }\n },\n {\n addEventListener: (listener) => device.addEventListener('inputreport', listener),\n removeEventListener: (listener) => device.removeEventListener('inputreport', listener),\n prepare: () => {", "score": 0.8210673332214355 }, { "filename": "src/lib/ring-con.ts", "retrieved_chunk": " device.sendReport(\n 0x01,\n new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ...subcommand]),\n );\n },\n // timeout: 5000,\n },\n );\n}\nexport async function getNextStrain(joycon: HIDDevice) {", "score": 0.817184567451477 }, { "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": 0.8046307563781738 } ]
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": " await rpc(\n {\n kind: 'enterChargeMode',\n request: {},\n },\n ['content'],\n );\n signPower = await rpc(\n {\n kind: 'getSignPower',", "score": 0.8434159159660339 }, { "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": 0.8361290097236633 }, { "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": 0.8243442177772522 }, { "filename": "src/resource/nip07-provider.ts", "retrieved_chunk": " request: {},\n },\n ['content', 'background'],\n );\n }\n if (signPower > 0) {\n rpc(\n {\n kind: 'setSignPower',\n request: { value: signPower - 1 },", "score": 0.8124393224716187 }, { "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": 0.8103224039077759 } ]
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/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": 0.8595110774040222 }, { "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": 0.8480882048606873 }, { "filename": "src/background/index.ts", "retrieved_chunk": "import { handleCrxRpcRequest } from '../lib/messaging';\nimport { signEvent } from '../lib/nostr';\nimport { getKeyPair, getSignPower, setSignPower } from '../lib/store';\n// * -> ...\nchrome.runtime.onMessage.addListener((msg: CrxRpcRequestMessage, sender, _sendResponse) => {\n const { next, shouldBeHandled } = handleCrxRpcRequest(msg, 'background');\n if (!shouldBeHandled) {\n return;\n }\n const payload = msg.payload;", "score": 0.8449206352233887 }, { "filename": "src/resource/nip07-provider.ts", "retrieved_chunk": " const messageId = Math.floor(Math.random() * 1000000);\n const message: CrxRpcRequestMessage = {\n ext,\n messageId,\n src: 'nip07-provider',\n path,\n payload: req,\n };\n window.addEventListener('message', listener);\n window.postMessage(message, '*');", "score": 0.8425471186637878 }, { "filename": "src/lib/ring-con.ts", "retrieved_chunk": " );\n // get_ext_data_59\n await communicate(\n joycon,\n [0x59],\n [\n [14, 0x59],\n [16, 0x20],\n ],\n );", "score": 0.8349952697753906 } ]
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": " ]);\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": 0.880944550037384 }, { "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": 0.8501557111740112 }, { "filename": "src/bin/cli.ts", "retrieved_chunk": "#!/usr/bin/env node\nimport { cli } from \"../index.js\";\nawait cli();", "score": 0.8437870740890503 }, { "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": 0.8414334654808044 }, { "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": 0.8378224968910217 } ]
typescript
.map((p) => {