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 express from 'express'; import { capture } from './helpers/sentry'; import { rpcError, rpcSuccess, storageEngine } from './helpers/utils'; import getModerationList from './lib/moderationList'; import VotesReport from './lib/votesReport'; import mintPayload from './lib/nftClaimer/mint'; import deployPayload from './lib/nftClaimer/deploy'; import { queue, getProgress } from './lib/queue'; import { snapshotFee } from './lib/nftClaimer/utils'; const router = express.Router(); router.post('/votes/:id', async (req, res) => { const { id } = req.params; const votesReport = new VotesReport(id, storageEngine(process.env.VOTE_REPORT_SUBDIR)); try { const file = await votesReport.getCache(); if (file) { res.header('Content-Type', 'text/csv'); res.attachment(votesReport.filename); return res.end(file); } try { await votesReport.isCacheable(); queue(votesReport); return rpcSuccess(res.status(202), getProgress(id).toString(), id); } catch (e: any) { capture(e); rpcError(res, e, id); } } catch (e) { capture(e); return rpcError(res, 'INTERNAL_ERROR', id); } }); router.get('/moderation', async (req, res) => { const { list } = req.query; try { res.json(await getModerationList(list ? (list as string).split(',') : undefined)); } catch (e) { capture(e); return rpcError(res, 'INTERNAL_ERROR', ''); } }); router.get('/nft-claimer', async (req, res) => { try { return res.json({ snapshotFee: await snapshotFee() }); } catch (e: any) { capture(e); return rpcError(res, e, ''); } }); router.post('/nft-claimer/deploy', async (req, res) => { const { address, id, salt, maxSupply, mintPrice, spaceTreasury, proposerFee } = req.body; try { return res.json( await deployPayload({ spaceOwner: address, id, maxSupply, mintPrice, proposerFee, salt, spaceTreasury }) ); } catch (e: any) { capture(e); return rpcError(res, e, salt); } }); router.post('/nft-claimer/mint', async (req, res) => { const { proposalAuthor, address, id, salt } = req.body; try { return res.json(
await mintPayload({ proposalAuthor, recipient: address, id, salt }));
} catch (e: any) { capture(e); return rpcError(res, e, salt); } }); export default router;
src/api.ts
snapshot-labs-snapshot-sidekick-800dacf
[ { "filename": "src/lib/nftClaimer/mint.ts", "retrieved_chunk": "const NFT_CLAIMER_NETWORK = process.env.NFT_CLAIMER_NETWORK;\nexport default async function payload(input: {\n proposalAuthor: string;\n recipient: string;\n id: string;\n salt: string;\n}) {\n const params = await validateMintInput(input);\n const proposal = await fetchProposal(params.id);\n validateProposal(proposal, params.proposalAuthor);", "score": 0.8210646510124207 }, { "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.8114022016525269 }, { "filename": "src/sentryTunnel.ts", "retrieved_chunk": " if (status !== 200) {\n console.debug(await response.text());\n }\n return res.sendStatus(status);\n } catch (e: any) {\n capture(e);\n rpcError(res, e, '');\n }\n});\nexport default router;", "score": 0.8011674880981445 }, { "filename": "src/index.ts", "retrieved_chunk": "app.use('/', sentryTunnel);\napp.get('/', (req, res) => {\n const commit = process.env.COMMIT_HASH || '';\n const v = commit ? `${version}#${commit.substring(0, 7)}` : version;\n return res.json({\n name,\n version: v\n });\n});\nfallbackLogger(app);", "score": 0.8011660575866699 }, { "filename": "src/webhook.ts", "retrieved_chunk": " return rpcError(res, 'Invalid Request', id);\n }\n try {\n processVotesReport(id, event);\n return rpcSuccess(res, 'Webhook received', id);\n } catch (e) {\n capture(e);\n return rpcError(res, 'INTERNAL_ERROR', id);\n }\n});", "score": 0.7956997156143188 } ]
typescript
await mintPayload({ proposalAuthor, recipient: address, id, salt }));
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.8254084587097168 }, { "filename": "src/helpers/utils.ts", "retrieved_chunk": " error: {\n code: errorCode,\n message: errorMessage\n },\n id\n });\n}\nexport async function sleep(time: number) {\n return new Promise(resolve => {\n setTimeout(resolve, time);", "score": 0.7820026874542236 }, { "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.7817507982254028 }, { "filename": "src/lib/nftClaimer/utils.ts", "retrieved_chunk": " }\n });\n return true;\n}\nexport async function validateProposerFee(fee: number) {\n if (fee < 0 || fee > 100) {\n throw new Error('proposerFee should be between 0 and 100');\n }\n const sFee = await snapshotFee();\n if (sFee + fee > 100) {", "score": 0.750613808631897 }, { "filename": "src/lib/cache.ts", "retrieved_chunk": " this.generationProgress = 0;\n }\n async getContent(): Promise<string | Buffer> {\n return '';\n }\n getCache() {\n return this.storage.get(this.filename);\n }\n async isCacheable() {\n return true;", "score": 0.7359083890914917 } ]
typescript
await fetchVotes(this.id, {
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.877016544342041 }, { "filename": "src/lib/nftClaimer/mint.ts", "retrieved_chunk": "const NFT_CLAIMER_NETWORK = process.env.NFT_CLAIMER_NETWORK;\nexport default async function payload(input: {\n proposalAuthor: string;\n recipient: string;\n id: string;\n salt: string;\n}) {\n const params = await validateMintInput(input);\n const proposal = await fetchProposal(params.id);\n validateProposal(proposal, params.proposalAuthor);", "score": 0.7762262225151062 }, { "filename": "src/lib/nftClaimer/utils.ts", "retrieved_chunk": " ...params\n };\n}\nexport async function snapshotFee(): Promise<number> {\n try {\n const provider = snapshot.utils.getProvider(NFT_CLAIMER_NETWORK);\n const contract = new Contract(\n DEPLOY_CONTRACT,\n ['function snapshotFee() public view returns (uint8)'],\n provider", "score": 0.7696132659912109 }, { "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.7596604824066162 }, { "filename": "src/lib/nftClaimer/mint.ts", "retrieved_chunk": "async function generateSignature(\n verifyingContract: string,\n domain: string,\n message: Record<string, string | bigint>\n) {\n return splitSignature(\n await signer._signTypedData(\n {\n name: domain,\n version: '0.1',", "score": 0.7559400796890259 } ]
typescript
console.debug('Signer', signer.address);
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.9934711456298828 }, { "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.987846314907074 }, { "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.9832852482795715 }, { "filename": "src/exceptions/bad-request.exception.ts", "retrieved_chunk": " });\n };\n /**\n * Returns a new instance of BadRequestException representing an Unexpected Error.\n * @param msg A string representing the error message.\n * @returns An instance of BadRequestException representing the error.\n */\n static UNEXPECTED = (msg?: string) => {\n return new BadRequestException({\n message: msg || 'Unexpected Error',", "score": 0.9269298315048218 }, { "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.9247045516967773 } ]
typescript
(exception.message, HttpStatus.INTERNAL_SERVER_ERROR, {
/** * 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.987540066242218 }, { "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.9829544425010681 }, { "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.9780689477920532 }, { "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.9271420240402222 }, { "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.9268754720687866 } ]
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/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.9931355714797974 }, { "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.9899098873138428 }, { "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.9721518158912659 }, { "filename": "src/exceptions/bad-request.exception.ts", "retrieved_chunk": " });\n };\n /**\n * Returns a new instance of BadRequestException representing an Unexpected Error.\n * @param msg A string representing the error message.\n * @returns An instance of BadRequestException representing the error.\n */\n static UNEXPECTED = (msg?: string) => {\n return new BadRequestException({\n message: msg || 'Unexpected Error',", "score": 0.9379236698150635 }, { "filename": "src/exceptions/bad-request.exception.ts", "retrieved_chunk": " code: ExceptionConstants.BadRequestCodes.UNEXPECTED_ERROR,\n });\n };\n /**\n * Returns a new instance of BadRequestException representing an Invalid Input.\n * @param msg A string representing the error message.\n * @returns An instance of BadRequestException representing the error.\n */\n static INVALID_INPUT = (msg?: string) => {\n return new BadRequestException({", "score": 0.9323561191558838 } ]
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.9929577112197876 }, { "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.9907255172729492 }, { "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.977769136428833 }, { "filename": "src/exceptions/bad-request.exception.ts", "retrieved_chunk": " });\n };\n /**\n * Returns a new instance of BadRequestException representing an Unexpected Error.\n * @param msg A string representing the error message.\n * @returns An instance of BadRequestException representing the error.\n */\n static UNEXPECTED = (msg?: string) => {\n return new BadRequestException({\n message: msg || 'Unexpected Error',", "score": 0.9362215995788574 }, { "filename": "src/exceptions/bad-request.exception.ts", "retrieved_chunk": " code: ExceptionConstants.BadRequestCodes.UNEXPECTED_ERROR,\n });\n };\n /**\n * Returns a new instance of BadRequestException representing an Invalid Input.\n * @param msg A string representing the error message.\n * @returns An instance of BadRequestException representing the error.\n */\n static INVALID_INPUT = (msg?: string) => {\n return new BadRequestException({", "score": 0.9297606945037842 } ]
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.9973416328430176 }, { "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.9950042963027954 }, { "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.9898760318756104 }, { "filename": "src/exceptions/unauthorized.exception.ts", "retrieved_chunk": " });\n };\n /**\n * Create a UnauthorizedException for when a resource is not found.\n * @param {string} [msg] - Optional message for the exception.\n * @returns {BadRequestException} - A UnauthorizedException with the appropriate error code and message.\n */\n static RESOURCE_NOT_FOUND = (msg?: string) => {\n return new UnauthorizedException({\n message: msg || 'Resource Not Found',", "score": 0.9155829548835754 }, { "filename": "src/filters/bad-request-exception.filter.ts", "retrieved_chunk": " * Constructs a new instance of `BadRequestExceptionFilter`.\n * @param httpAdapterHost - The HttpAdapterHost instance to be used.\n */\n constructor(private readonly httpAdapterHost: HttpAdapterHost) {}\n /**\n * Handles the `BadRequestException` and transforms it into a JSON response.\n * @param exception - The `BadRequestException` instance that was thrown.\n * @param host - The `ArgumentsHost` instance that represents the current execution context.\n */\n catch(exception: BadRequestException, host: ArgumentsHost): void {", "score": 0.9122654795646667 } ]
typescript
generateHttpResponseBody = (message?: string): IHttpBadRequestExceptionResponse => {
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.7041336297988892 }, { "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.6850285530090332 }, { "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.6527502536773682 }, { "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.632715106010437 }, { "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.6200599074363708 } ]
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 * 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.873347282409668 }, { "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.8516584038734436 }, { "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.8454791307449341 }, { "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.8413984775543213 }, { "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.8410969376564026 } ]
typescript
: (item: SearchJSItem) => void, onRemove: (item: SearchJSItem) => void, ): void {
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.9969971179962158 }, { "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.9893392324447632 }, { "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.9781869053840637 }, { "filename": "src/exceptions/bad-request.exception.ts", "retrieved_chunk": " });\n };\n /**\n * Returns a new instance of BadRequestException representing an Unexpected Error.\n * @param msg A string representing the error message.\n * @returns An instance of BadRequestException representing the error.\n */\n static UNEXPECTED = (msg?: string) => {\n return new BadRequestException({\n message: msg || 'Unexpected Error',", "score": 0.9363391995429993 }, { "filename": "src/exceptions/bad-request.exception.ts", "retrieved_chunk": " code: ExceptionConstants.BadRequestCodes.UNEXPECTED_ERROR,\n });\n };\n /**\n * Returns a new instance of BadRequestException representing an Invalid Input.\n * @param msg A string representing the error message.\n * @returns An instance of BadRequestException representing the error.\n */\n static INVALID_INPUT = (msg?: string) => {\n return new BadRequestException({", "score": 0.9305882453918457 } ]
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.9952808618545532 }, { "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.9901381731033325 }, { "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.9725840091705322 }, { "filename": "src/exceptions/bad-request.exception.ts", "retrieved_chunk": " });\n };\n /**\n * Returns a new instance of BadRequestException representing an Unexpected Error.\n * @param msg A string representing the error message.\n * @returns An instance of BadRequestException representing the error.\n */\n static UNEXPECTED = (msg?: string) => {\n return new BadRequestException({\n message: msg || 'Unexpected Error',", "score": 0.9308615326881409 }, { "filename": "src/exceptions/bad-request.exception.ts", "retrieved_chunk": " code: ExceptionConstants.BadRequestCodes.UNEXPECTED_ERROR,\n });\n };\n /**\n * Returns a new instance of BadRequestException representing an Invalid Input.\n * @param msg A string representing the error message.\n * @returns An instance of BadRequestException representing the error.\n */\n static INVALID_INPUT = (msg?: string) => {\n return new BadRequestException({", "score": 0.9239028692245483 } ]
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/index.ts", "retrieved_chunk": " * get singleton instance\n *\n * @param {SearchJSConfig} config\n * @returns {SearchJSApp}\n */\n public static getInstance(config: SearchJSConfig): SearchJSApp {\n return this._instance || (this._instance = new this(config))\n }\n /**\n * function to open search modal", "score": 0.8719445466995239 }, { "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.8637819290161133 }, { "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.8637604713439941 }, { "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.8586316108703613 }, { "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.8577905893325806 } ]
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.9940235614776611 }, { "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.9873547554016113 }, { "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.9744850397109985 }, { "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.9323487281799316 }, { "filename": "src/exceptions/bad-request.exception.ts", "retrieved_chunk": " });\n };\n /**\n * Returns a new instance of BadRequestException representing an Unexpected Error.\n * @param msg A string representing the error message.\n * @returns An instance of BadRequestException representing the error.\n */\n static UNEXPECTED = (msg?: string) => {\n return new BadRequestException({\n message: msg || 'Unexpected Error',", "score": 0.9298101663589478 } ]
typescript
message, HttpStatus.FORBIDDEN, {
import { CLASS_CLEAR_ICON, CLASS_CONTAINER, ATTR_DATA_PAYLOAD, ID, CLASS_INPUT, CLASS_ITEM, CLASS_ITEM_CLOSE, } from '../constant' import { SearchJSItem } from '../types' import { Encoder } from './Encoder' export class DomListener { /** * @var {string} EVENT_CLICK */ private EVENT_CLICK = 'click' /** * @var {string} EVENT_KEYUP */ private EVENT_KEYUP = 'keyup' /** * listen for on back drop click to hide modal * * @param {Function} callback * @returns {void} */ public onBackDropClick(callback: () => void): void { const element = document.querySelector(`#${ID}.${CLASS_CONTAINER}`) element.addEventListener(this.EVENT_CLICK, (event) => { if (event.target === element) { callback() } }) } /** * listen for on search * * @param {Function} callback * @returns {void} */ public onSearch(callback: (keyword: string) => void): void { const element: HTMLInputElement = document.querySelector(`#${ID} .${CLASS_INPUT}`) // search input keyup element.addEventListener(this.EVENT_KEYUP, (event: any) => { const keyword = event.target.value.toLowerCase() callback(keyword) }) // clear icon document.querySelector(`.${CLASS_CLEAR_ICON}`).addEventListener(this.EVENT_CLICK, () => { element.value = '' callback(null) }) } /** * listen for on item click * * @param {Function} onSelected * @param {Function} onRemove * @returns {void} */ public onItemClick(
onSelected: (item: SearchJSItem) => void, onRemove: (item: SearchJSItem) => void, ): void {
const items = document.querySelectorAll(`#${ID} .${CLASS_ITEM}`) items.forEach((el) => // item click to select el.addEventListener(this.EVENT_CLICK, (event: any) => { const closeElements = event.target.closest(`.${CLASS_ITEM_CLOSE} *`) if (event.target == closeElements) { return } const parentElement = event.target.closest(`.${CLASS_ITEM}`) const data = parentElement.getAttribute(ATTR_DATA_PAYLOAD) onSelected(Encoder.decode(data)) }), ) const closeItems = document.querySelectorAll(`#${ID} .${CLASS_ITEM_CLOSE}`) closeItems.forEach((el) => // item click to remove from history el.addEventListener(this.EVENT_CLICK, (event: any) => { const parentElement = event.target.closest(`.${CLASS_ITEM_CLOSE}`) const data = parentElement.getAttribute(ATTR_DATA_PAYLOAD) onRemove(Encoder.decode(data)) }), ) } }
src/utils/DomListener.ts
necessarylion-search-js-74bfb45
[ { "filename": "src/utils/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.8875887393951416 }, { "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.8675622940063477 }, { "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.8595485091209412 }, { "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.8479422330856323 }, { "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.846662163734436 } ]
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/components/Header.ts", "retrieved_chunk": "import { SearchJSConfig } from '../types'\nimport { clearIcon, searchIcon } from '../assets/Icon'\nimport { CLASS_CLEAR_ICON, CLASS_INPUT, DEFAULT_THEME_COLOR } from '../constant'\nexport class Header {\n /**\n * render header html string\n *\n * @param {SearchJSConfig} config\n * @returns {string}\n */", "score": 0.8203607797622681 }, { "filename": "src/themes/index.ts", "retrieved_chunk": " CssHeight,\n CssPositionTop,\n CssTheme,\n CssWidth,\n} from './AvailableThemes'\nexport class Theme {\n /**\n * create global css variables base on provided theme\n *\n * @param {SearchJSConfig} config", "score": 0.8165175914764404 }, { "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.8126172423362732 }, { "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.8030128479003906 }, { "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.8023957014083862 } ]
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.9193446636199951 }, { "filename": "src/index.ts", "retrieved_chunk": " * get singleton instance\n *\n * @param {SearchJSConfig} config\n * @returns {SearchJSApp}\n */\n public static getInstance(config: SearchJSConfig): SearchJSApp {\n return this._instance || (this._instance = new this(config))\n }\n /**\n * function to open search modal", "score": 0.8963567018508911 }, { "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.8916865587234497 }, { "filename": "src/utils/SearchHistory.ts", "retrieved_chunk": "import { SearchJSItem } from '../types'\nexport class SearchHistory {\n /**\n * local storage\n *\n * @var {Storage} db\n */\n private db: Storage\n /**\n * max items to store in history", "score": 0.8750563263893127 }, { "filename": "src/themes/index.ts", "retrieved_chunk": " CssHeight,\n CssPositionTop,\n CssTheme,\n CssWidth,\n} from './AvailableThemes'\nexport class Theme {\n /**\n * create global css variables base on provided theme\n *\n * @param {SearchJSConfig} config", "score": 0.8704013228416443 } ]
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/components/Footer.ts", "retrieved_chunk": "export class Footer {\n /**\n * render footer html string\n *\n * @returns {string}\n */\n render(): string {\n return `<div class=\"keyboard-button\">Esc</div> <span>to close</span>`\n }\n}", "score": 0.8356610536575317 }, { "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.8295106887817383 }, { "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.80884850025177 }, { "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.8048105239868164 }, { "filename": "src/components/Header.ts", "retrieved_chunk": "import { SearchJSConfig } from '../types'\nimport { clearIcon, searchIcon } from '../assets/Icon'\nimport { CLASS_CLEAR_ICON, CLASS_INPUT, DEFAULT_THEME_COLOR } from '../constant'\nexport class Header {\n /**\n * render header html string\n *\n * @param {SearchJSConfig} config\n * @returns {string}\n */", "score": 0.800832986831665 } ]
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": " 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.8509438037872314 }, { "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.8397911787033081 }, { "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.7782427072525024 }, { "filename": "src/components/Header.ts", "retrieved_chunk": "import { SearchJSConfig } from '../types'\nimport { clearIcon, searchIcon } from '../assets/Icon'\nimport { CLASS_CLEAR_ICON, CLASS_INPUT, DEFAULT_THEME_COLOR } from '../constant'\nexport class Header {\n /**\n * render header html string\n *\n * @param {SearchJSConfig} config\n * @returns {string}\n */", "score": 0.7747481465339661 }, { "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.7719421982765198 } ]
typescript
historyIcon(), }) this.handleItemClickListener() }
import { SearchJSTheme } from '../types' export const CssBackdropBackground = '--search-js-backdrop-bg' export const CssModalBackground = '--search-js-modal-bg' export const CssModalBoxShadow = '--search-js-modal-box-shadow' export const CssModalFooterBoxShadow = '--search-js-modal-footer-box-shadow' export const CssKeyboardButtonBoxShadow = '--search-js-keyboard-button-box-shadow' export const CssKeyboardButtonBackground = '--search-js-keyboard-button-bg' export const CssInputBackground = '--search-js-search-input-bg' export const CssInputPlaceholderColor = '--search-js-input-placeholder-color' export const CssItemBackground = '--search-js-item-bg' export const CssItemBoxShadow = '--search-js-item-box-shadow' export const CssTextColor = '--search-js-text-color' export const CssTheme = '--search-js-theme' export const CssWidth = '--search-js-width' export const CssHeight = '--search-js-height' export const CssFontFamily = '--search-js-font-family' export const CssPositionTop = '--search-js-top' export const AvailableThemes: any = { [SearchJSTheme.ThemeDark]: { [CssBackdropBackground]: 'rgba(47, 55, 69, 0.7)', [CssModalBackground]: '#1b1b1d', [CssModalBoxShadow]: 'inset 1px 1px 0 0 #2c2e40, 0 3px 8px 0 #000309', [CssModalFooterBoxShadow]: 'inset 0 1px 0 0 rgba(73, 76, 106, 0.5), 0 -4px 8px 0 rgba(0, 0, 0, 0.2)', [CssKeyboardButtonBoxShadow]: 'inset 0 -2px 0 0 #282d55, inset 0 0 1px 1px #51577d, 0 2px 2px 0 rgba(3, 4, 9, 0.3)', [CssKeyboardButtonBackground]: 'linear-gradient(-26.5deg, transparent 0%, transparent 100%)', [CssInputBackground]: 'black', [CssInputPlaceholderColor]: '#aeaeae', [CssItemBackground]: '#1c1e21', [CssItemBoxShadow]: 'none', [CssTextColor]: '#b3b3b3', }, [SearchJSTheme.ThemeLight]: { [CssBackdropBackground]: 'rgba(101, 108, 133, 0.8)', [CssModalBackground]: '#f5f6f7', [CssModalBoxShadow]: 'inset 1px 1px 0 0 hsla(0, 0%, 100%, 0.5), 0 3px 8px 0 #555a64', [CssModalFooterBoxShadow]: '0 -1px 0 0 #e0e3e8, 0 -3px 6px 0 rgba(69, 98, 155, 0.12)', [CssKeyboardButtonBoxShadow]: 'inset 0 -2px 0 0 #cdcde6, inset 0 0 1px 1px #fff, 0 1px 2px 1px rgba(30, 35, 90, 0.4)', [CssKeyboardButtonBackground]: 'linear-gradient(-225deg, #d5dbe4, #f8f8f8)', [CssInputBackground]: 'white', [CssInputPlaceholderColor]: '#969faf', [CssItemBackground]: 'white', [CssItemBoxShadow]: '0 1px 3px 0 #d4d9e1', [CssTextColor]: '#969faf', },
[SearchJSTheme.ThemeGithubDark]: {
[CssBackdropBackground]: 'rgba(1,4,9,0.8)', [CssModalBackground]: '#0D1116', [CssModalBoxShadow]: 'none', [CssModalFooterBoxShadow]: 'none', [CssKeyboardButtonBoxShadow]: 'none', [CssKeyboardButtonBackground]: 'none', [CssInputBackground]: 'transparent', [CssInputPlaceholderColor]: '#6D7681', [CssItemBackground]: 'transparent', [CssItemBoxShadow]: 'none', [CssTextColor]: '#C5CED6', [CssTheme]: 'transparent', }, [SearchJSTheme.ThemeGithubLight]: { [CssBackdropBackground]: 'rgba(27,31,36,0.5)', [CssModalBackground]: '#FFFFFF', [CssModalBoxShadow]: 'none', [CssModalFooterBoxShadow]: 'none', [CssKeyboardButtonBoxShadow]: 'none', [CssKeyboardButtonBackground]: 'none', [CssInputBackground]: 'transparent', [CssInputPlaceholderColor]: '#6E7781', [CssItemBackground]: 'transparent', [CssItemBoxShadow]: 'none', [CssTextColor]: '#1F2329', [CssTheme]: 'transparent', }, }
src/themes/AvailableThemes.ts
necessarylion-search-js-74bfb45
[ { "filename": "src/assets/Icon/index.ts", "retrieved_chunk": "<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.6430431604385376 }, { "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.6117203235626221 }, { "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.605277955532074 }, { "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.600080132484436 }, { "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.5976625084877014 } ]
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.9170142412185669 }, { "filename": "src/index.ts", "retrieved_chunk": " * get singleton instance\n *\n * @param {SearchJSConfig} config\n * @returns {SearchJSApp}\n */\n public static getInstance(config: SearchJSConfig): SearchJSApp {\n return this._instance || (this._instance = new this(config))\n }\n /**\n * function to open search modal", "score": 0.8942087888717651 }, { "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.8938167691230774 }, { "filename": "src/utils/SearchHistory.ts", "retrieved_chunk": "import { SearchJSItem } from '../types'\nexport class SearchHistory {\n /**\n * local storage\n *\n * @var {Storage} db\n */\n private db: Storage\n /**\n * max items to store in history", "score": 0.8798021078109741 }, { "filename": "src/themes/index.ts", "retrieved_chunk": " CssHeight,\n CssPositionTop,\n CssTheme,\n CssWidth,\n} from './AvailableThemes'\nexport class Theme {\n /**\n * create global css variables base on provided theme\n *\n * @param {SearchJSConfig} config", "score": 0.8687412738800049 } ]
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.917766273021698 }, { "filename": "src/index.ts", "retrieved_chunk": " * get singleton instance\n *\n * @param {SearchJSConfig} config\n * @returns {SearchJSApp}\n */\n public static getInstance(config: SearchJSConfig): SearchJSApp {\n return this._instance || (this._instance = new this(config))\n }\n /**\n * function to open search modal", "score": 0.8954846858978271 }, { "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.8954195380210876 }, { "filename": "src/utils/SearchHistory.ts", "retrieved_chunk": "import { SearchJSItem } from '../types'\nexport class SearchHistory {\n /**\n * local storage\n *\n * @var {Storage} db\n */\n private db: Storage\n /**\n * max items to store in history", "score": 0.8834185004234314 }, { "filename": "src/themes/index.ts", "retrieved_chunk": " CssHeight,\n CssPositionTop,\n CssTheme,\n CssWidth,\n} from './AvailableThemes'\nexport class Theme {\n /**\n * create global css variables base on provided theme\n *\n * @param {SearchJSConfig} config", "score": 0.8707510828971863 } ]
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/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.9193446636199951 }, { "filename": "src/index.ts", "retrieved_chunk": " * get singleton instance\n *\n * @param {SearchJSConfig} config\n * @returns {SearchJSApp}\n */\n public static getInstance(config: SearchJSConfig): SearchJSApp {\n return this._instance || (this._instance = new this(config))\n }\n /**\n * function to open search modal", "score": 0.8963567018508911 }, { "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.8916865587234497 }, { "filename": "src/utils/SearchHistory.ts", "retrieved_chunk": "import { SearchJSItem } from '../types'\nexport class SearchHistory {\n /**\n * local storage\n *\n * @var {Storage} db\n */\n private db: Storage\n /**\n * max items to store in history", "score": 0.8750563263893127 }, { "filename": "src/themes/index.ts", "retrieved_chunk": " CssHeight,\n CssPositionTop,\n CssTheme,\n CssWidth,\n} from './AvailableThemes'\nexport class Theme {\n /**\n * create global css variables base on provided theme\n *\n * @param {SearchJSConfig} config", "score": 0.8704013228416443 } ]
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/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.8968119025230408 }, { "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.893770694732666 }, { "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.8821460008621216 }, { "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.8795777559280396 }, { "filename": "src/index.ts", "retrieved_chunk": " *\n * @returns {void}\n */\n public open(): void {\n this.component.element.style.display = 'flex'\n this.focusOnSearch()\n }\n /**\n * function to close search modal\n *", "score": 0.878349781036377 } ]
typescript
this.domListener.onSearch(async (keyword: string) => {
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon' import { Footer } from '../components/Footer' import { Header } from '../components/Header' import { Item } from '../components/Item' import { DomListener } from './DomListener' import { SearchHistory } from './SearchHistory' import { SearchJSApp } from '..' import { SearchJSItem, SearchJSTheme } from '../types' import { Theme } from '../themes' import { CLASS_CONTAINER, ID, CLASS_MODAL, ID_HISTORIES, ID_LOADING, ID_RESULTS, CLASS_MODAL_HEADER, CLASS_MODAL_FOOTER, CLASS_MODAL_CONTENT, } from '../constant' export class SearchComponent { /** * the entire search js element * * @var {HTMLElement} element */ public element: HTMLElement /** * timer placeholder to handle search * * @var {number} searchTimer */ private searchTimer?: number /** * class constructor * * @param {SearchJSApp} app * @param {DomListener} domListener * @param {SearchHistory} searchHistory * @param {Theme} theme */ constructor( private app: SearchJSApp, private domListener: DomListener, private searchHistory: SearchHistory, private theme: Theme, ) { // add global css variable this.theme.createGlobalCssVariable(this.app.config) // append search element on parent element this.getParentElement().appendChild(this.createElement()) // render initial data list this.showHistory(this.searchHistory.getList()) this.domListener.onBackDropClick(() => { this.app.close() }) this.handleOnSearch() } /** * handle search and show list on result * * @returns {void} */ private handleOnSearch(): void { this.domListener.onSearch(async (keyword: string) => { if (!keyword) { clearTimeout(this.searchTimer) this.hideLoading() this.showHistory(this.searchHistory.getList()) this.hideSearchResult() return } this.hideHistories() this.hideSearchResult() if (this.app.config.onSearch) { this.showLoading() clearTimeout(this.searchTimer) this.searchTimer = setTimeout(async () => { const items = await this.app.config.onSearch(keyword) this.hideLoading() this.showSearchResult(items) }, this.app.config.onSearchDelay ?? 500) } else { this.showSearchResult(this.getItems(keyword)) } }) } /** * get list of items from config and filter with keyword from search input * * @param {string} keyword * @returns {Array<SearchJSItem> | null | undefined} */ private getItems(keyword: string): Array<SearchJSItem> | null | undefined { const items = this.app.config.data return items.filter((item) => { return ( (item.title && item.title.toLowerCase().includes(keyword)) || (item.description && item.description.toLowerCase().includes(keyword)) ) }) } /** * get parent element to append search-js element * * @returns {HTMLElement} */ private getParentElement(): HTMLElement { return this.app.config.element ?? document.body } private createElement() { const element = document.createElement('div') element.id = ID if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) { element.classList.add(this.app.config.theme) } element.classList.add(CLASS_CONTAINER) const footer = new Footer() const header = new Header() element.innerHTML = `<div class="${CLASS_MODAL}"> <div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div> <div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div> <div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div> <div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div> <div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div> </div> ` this.element = element return this.element } /** * show item lists * * @param {Array<SearchJSItem>} items * @returns {void} */ private showSearchResult(items: Array<SearchJSItem>): void { const itemInstance = new Item() itemInstance.renderList({ id: ID_RESULTS, items: items, hideRemoveButton: true, notFoundLabel: 'No match found',
icon: hashIcon(), }) this.handleItemClickListener() }
/** * hide search result * * @returns {void} */ private hideSearchResult(): void { document.getElementById(ID_RESULTS).style.display = 'none' } /** * show history list * * @param {Array<SearchJSItem>} items * @returns {void} */ private showHistory(items: Array<SearchJSItem>): void { const itemInstance = new Item() itemInstance.renderList({ id: ID_HISTORIES, items: items, hideRemoveButton: false, notFoundLabel: 'No recent data', icon: historyIcon(), }) this.handleItemClickListener() } /** * hide history * * @returns {void} */ private hideHistories(): void { document.getElementById(ID_HISTORIES).style.display = 'none' } /** * listen on select and on remove event on item * * @return {void} */ private handleItemClickListener(): void { this.domListener.onItemClick( (data: any) => { this.searchHistory.add(data) this.app.config.onSelected(data) }, (data: any) => { this.searchHistory.remove(data) this.showHistory(this.searchHistory.getList()) }, ) } /** * show loading * * @returns {void} */ private showLoading(): void { document.getElementById(ID_LOADING).style.display = 'flex' } /** * hide loading * * @returns {void} */ private hideLoading(): void { document.getElementById(ID_LOADING).style.display = 'none' } }
src/utils/SearchComponent.ts
necessarylion-search-js-74bfb45
[ { "filename": "src/components/Item.ts", "retrieved_chunk": " id: string\n items?: Array<SearchJSItem>\n icon: string\n hideRemoveButton: boolean\n notFoundLabel: string\n}\nexport class Item {\n /**\n * render item list\n *", "score": 0.8335260152816772 }, { "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.8201653957366943 }, { "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.7780438661575317 }, { "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.7549763917922974 }, { "filename": "src/components/Header.ts", "retrieved_chunk": "import { SearchJSConfig } from '../types'\nimport { clearIcon, searchIcon } from '../assets/Icon'\nimport { CLASS_CLEAR_ICON, CLASS_INPUT, DEFAULT_THEME_COLOR } from '../constant'\nexport class Header {\n /**\n * render header html string\n *\n * @param {SearchJSConfig} config\n * @returns {string}\n */", "score": 0.7502045631408691 } ]
typescript
icon: hashIcon(), }) this.handleItemClickListener() }
/** * 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.9909899234771729 }, { "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.9794325232505798 }, { "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.9722889065742493 }, { "filename": "src/exceptions/bad-request.exception.ts", "retrieved_chunk": " });\n };\n /**\n * Returns a new instance of BadRequestException representing an Unexpected Error.\n * @param msg A string representing the error message.\n * @returns An instance of BadRequestException representing the error.\n */\n static UNEXPECTED = (msg?: string) => {\n return new BadRequestException({\n message: msg || 'Unexpected Error',", "score": 0.9310996532440186 }, { "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.9290030002593994 } ]
typescript
super(exception.message, HttpStatus.UNAUTHORIZED, {
import { DEFAULT_HEIGHT, DEFAULT_POSITION_TOP, DEFAULT_THEME_COLOR, DEFAULT_WIDTH, } from '../constant' import { SearchJSConfig, SearchJSTheme } from '../types' import { AvailableThemes, CssFontFamily, CssHeight, CssPositionTop, CssTheme, CssWidth, } from './AvailableThemes' export class Theme { /** * create global css variables base on provided theme * * @param {SearchJSConfig} config */ public createGlobalCssVariable(config: SearchJSConfig) { const bodyStyle = window.getComputedStyle(document.body) const styleElement = document.createElement('style') const cssObject = { [CssWidth]: config.width ?? DEFAULT_WIDTH, [CssHeight]: config.height ?? DEFAULT_HEIGHT, [CssTheme]: config.theme ?? DEFAULT_THEME_COLOR, [CssFontFamily]: bodyStyle.getPropertyValue('font-family'), [CssPositionTop]: config.positionTop ?? DEFAULT_POSITION_TOP, } styleElement.innerHTML = `:root{${this.getCssVariables(cssObject)} ${this.getTheme(config)}}` document.head.appendChild(styleElement) } /** * get list of read made themes * * @returns {Array<SearchJSTheme>} */
public getReadyMadeThemes(): Array<SearchJSTheme> {
return [SearchJSTheme.ThemeGithubLight, SearchJSTheme.ThemeGithubDark] } /** * get theme css string from config * * @param {SearchJSConfig} config * @returns {string} */ private getTheme(config: SearchJSConfig): string { const defaultTheme = config.darkMode ? SearchJSTheme.ThemeDark : SearchJSTheme.ThemeLight const themeName = this.getReadyMadeThemes().includes(config.theme as SearchJSTheme) ? config.theme : defaultTheme return this.getCssVariables(this.getThemeValues(themeName)) } /** * get theme css variable values * * @param {string} theme * @returns {object} */ private getThemeValues(theme: string): object { return AvailableThemes[theme] } /** * get theme css string * * @param {object} obj * @returns {string} */ private getCssVariables(obj: object): string { let css = '' Object.entries(obj).forEach(([key, value]) => { css += `${key} : ${value};` }) return css } }
src/themes/index.ts
necessarylion-search-js-74bfb45
[ { "filename": "src/utils/SearchComponent.ts", "retrieved_chunk": " })\n }\n /**\n * get parent element to append search-js element\n *\n * @returns {HTMLElement}\n */\n private getParentElement(): HTMLElement {\n return this.app.config.element ?? document.body\n }", "score": 0.7675304412841797 }, { "filename": "src/utils/SearchComponent.ts", "retrieved_chunk": " * @returns {void}\n */\n private hideSearchResult(): void {\n document.getElementById(ID_RESULTS).style.display = 'none'\n }\n /**\n * show history list\n *\n * @param {Array<SearchJSItem>} items\n * @returns {void}", "score": 0.7640743255615234 }, { "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.7633102536201477 }, { "filename": "src/components/Header.ts", "retrieved_chunk": "import { SearchJSConfig } from '../types'\nimport { clearIcon, searchIcon } from '../assets/Icon'\nimport { CLASS_CLEAR_ICON, CLASS_INPUT, DEFAULT_THEME_COLOR } from '../constant'\nexport class Header {\n /**\n * render header html string\n *\n * @param {SearchJSConfig} config\n * @returns {string}\n */", "score": 0.7616428732872009 }, { "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.7588695883750916 } ]
typescript
public getReadyMadeThemes(): Array<SearchJSTheme> {
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/components/Footer.ts", "retrieved_chunk": "export class Footer {\n /**\n * render footer html string\n *\n * @returns {string}\n */\n render(): string {\n return `<div class=\"keyboard-button\">Esc</div> <span>to close</span>`\n }\n}", "score": 0.8510756492614746 }, { "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.8422996997833252 }, { "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.8244011402130127 }, { "filename": "src/components/Header.ts", "retrieved_chunk": "import { SearchJSConfig } from '../types'\nimport { clearIcon, searchIcon } from '../assets/Icon'\nimport { CLASS_CLEAR_ICON, CLASS_INPUT, DEFAULT_THEME_COLOR } from '../constant'\nexport class Header {\n /**\n * render header html string\n *\n * @param {SearchJSConfig} config\n * @returns {string}\n */", "score": 0.8186705708503723 }, { "filename": "src/utils/SearchComponent.ts", "retrieved_chunk": " * @returns {void}\n */\n private showLoading(): void {\n document.getElementById(ID_LOADING).style.display = 'flex'\n }\n /**\n * hide loading\n *\n * @returns {void}\n */", "score": 0.8182141780853271 } ]
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/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.9193446636199951 }, { "filename": "src/index.ts", "retrieved_chunk": " * get singleton instance\n *\n * @param {SearchJSConfig} config\n * @returns {SearchJSApp}\n */\n public static getInstance(config: SearchJSConfig): SearchJSApp {\n return this._instance || (this._instance = new this(config))\n }\n /**\n * function to open search modal", "score": 0.8963567018508911 }, { "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.8916865587234497 }, { "filename": "src/utils/SearchHistory.ts", "retrieved_chunk": "import { SearchJSItem } from '../types'\nexport class SearchHistory {\n /**\n * local storage\n *\n * @var {Storage} db\n */\n private db: Storage\n /**\n * max items to store in history", "score": 0.8750563263893127 }, { "filename": "src/themes/index.ts", "retrieved_chunk": " CssHeight,\n CssPositionTop,\n CssTheme,\n CssWidth,\n} from './AvailableThemes'\nexport class Theme {\n /**\n * create global css variables base on provided theme\n *\n * @param {SearchJSConfig} config", "score": 0.8704013228416443 } ]
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/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.8909896612167358 }, { "filename": "src/index.ts", "retrieved_chunk": " * get singleton instance\n *\n * @param {SearchJSConfig} config\n * @returns {SearchJSApp}\n */\n public static getInstance(config: SearchJSConfig): SearchJSApp {\n return this._instance || (this._instance = new this(config))\n }\n /**\n * function to open search modal", "score": 0.8906697630882263 }, { "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.8888628482818604 }, { "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.8855273127555847 }, { "filename": "src/themes/index.ts", "retrieved_chunk": " */\n private getThemeValues(theme: string): object {\n return AvailableThemes[theme]\n }\n /**\n * get theme css string\n *\n * @param {object} obj\n * @returns {string}\n */", "score": 0.8787983655929565 } ]
typescript
return this.app.config.element ?? document.body }
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.8959828615188599 }, { "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.8904317617416382 }, { "filename": "src/themes/index.ts", "retrieved_chunk": " */\n private getThemeValues(theme: string): object {\n return AvailableThemes[theme]\n }\n /**\n * get theme css string\n *\n * @param {object} obj\n * @returns {string}\n */", "score": 0.8864973187446594 }, { "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.8798468112945557 }, { "filename": "src/utils/SearchHistory.ts", "retrieved_chunk": "import { SearchJSItem } from '../types'\nexport class SearchHistory {\n /**\n * local storage\n *\n * @var {Storage} db\n */\n private db: Storage\n /**\n * max items to store in history", "score": 0.8786887526512146 } ]
typescript
: Array<SearchJSItem> | null | undefined {
import { DEFAULT_HEIGHT, DEFAULT_POSITION_TOP, DEFAULT_THEME_COLOR, DEFAULT_WIDTH, } from '../constant' import { SearchJSConfig, SearchJSTheme } from '../types' import { AvailableThemes, CssFontFamily, CssHeight, CssPositionTop, CssTheme, CssWidth, } from './AvailableThemes' export class Theme { /** * create global css variables base on provided theme * * @param {SearchJSConfig} config */ public createGlobalCssVariable(config: SearchJSConfig) { const bodyStyle = window.getComputedStyle(document.body) const styleElement = document.createElement('style') const cssObject = { [CssWidth]: config.width ?? DEFAULT_WIDTH, [CssHeight]: config.height ?? DEFAULT_HEIGHT, [CssTheme]: config.theme ?? DEFAULT_THEME_COLOR, [CssFontFamily]: bodyStyle.getPropertyValue('font-family'), [CssPositionTop]: config.positionTop ?? DEFAULT_POSITION_TOP, } styleElement.innerHTML = `:root{${this.getCssVariables(cssObject)} ${this.getTheme(config)}}` document.head.appendChild(styleElement) } /** * get list of read made themes * * @returns {Array<SearchJSTheme>} */ public getReadyMadeThemes()
: Array<SearchJSTheme> {
return [SearchJSTheme.ThemeGithubLight, SearchJSTheme.ThemeGithubDark] } /** * get theme css string from config * * @param {SearchJSConfig} config * @returns {string} */ private getTheme(config: SearchJSConfig): string { const defaultTheme = config.darkMode ? SearchJSTheme.ThemeDark : SearchJSTheme.ThemeLight const themeName = this.getReadyMadeThemes().includes(config.theme as SearchJSTheme) ? config.theme : defaultTheme return this.getCssVariables(this.getThemeValues(themeName)) } /** * get theme css variable values * * @param {string} theme * @returns {object} */ private getThemeValues(theme: string): object { return AvailableThemes[theme] } /** * get theme css string * * @param {object} obj * @returns {string} */ private getCssVariables(obj: object): string { let css = '' Object.entries(obj).forEach(([key, value]) => { css += `${key} : ${value};` }) return css } }
src/themes/index.ts
necessarylion-search-js-74bfb45
[ { "filename": "src/utils/SearchComponent.ts", "retrieved_chunk": " })\n }\n /**\n * get parent element to append search-js element\n *\n * @returns {HTMLElement}\n */\n private getParentElement(): HTMLElement {\n return this.app.config.element ?? document.body\n }", "score": 0.7631736397743225 }, { "filename": "src/components/Header.ts", "retrieved_chunk": "import { SearchJSConfig } from '../types'\nimport { clearIcon, searchIcon } from '../assets/Icon'\nimport { CLASS_CLEAR_ICON, CLASS_INPUT, DEFAULT_THEME_COLOR } from '../constant'\nexport class Header {\n /**\n * render header html string\n *\n * @param {SearchJSConfig} config\n * @returns {string}\n */", "score": 0.7605829238891602 }, { "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.7589681148529053 }, { "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.7566869854927063 }, { "filename": "src/utils/SearchComponent.ts", "retrieved_chunk": " * @returns {void}\n */\n private hideSearchResult(): void {\n document.getElementById(ID_RESULTS).style.display = 'none'\n }\n /**\n * show history list\n *\n * @param {Array<SearchJSItem>} items\n * @returns {void}", "score": 0.7566297650337219 } ]
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.9186355471611023 }, { "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.8960748314857483 }, { "filename": "src/index.ts", "retrieved_chunk": " * get singleton instance\n *\n * @param {SearchJSConfig} config\n * @returns {SearchJSApp}\n */\n public static getInstance(config: SearchJSConfig): SearchJSApp {\n return this._instance || (this._instance = new this(config))\n }\n /**\n * function to open search modal", "score": 0.8949007987976074 }, { "filename": "src/utils/SearchHistory.ts", "retrieved_chunk": "import { SearchJSItem } from '../types'\nexport class SearchHistory {\n /**\n * local storage\n *\n * @var {Storage} db\n */\n private db: Storage\n /**\n * max items to store in history", "score": 0.8835926055908203 }, { "filename": "src/themes/index.ts", "retrieved_chunk": " CssHeight,\n CssPositionTop,\n CssTheme,\n CssWidth,\n} from './AvailableThemes'\nexport class Theme {\n /**\n * create global css variables base on provided theme\n *\n * @param {SearchJSConfig} config", "score": 0.8730341196060181 } ]
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.8974657654762268 }, { "filename": "src/index.ts", "retrieved_chunk": " * get singleton instance\n *\n * @param {SearchJSConfig} config\n * @returns {SearchJSApp}\n */\n public static getInstance(config: SearchJSConfig): SearchJSApp {\n return this._instance || (this._instance = new this(config))\n }\n /**\n * function to open search modal", "score": 0.8854764699935913 }, { "filename": "src/themes/index.ts", "retrieved_chunk": " */\n private getThemeValues(theme: string): object {\n return AvailableThemes[theme]\n }\n /**\n * get theme css string\n *\n * @param {object} obj\n * @returns {string}\n */", "score": 0.8746849298477173 }, { "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.8627663850784302 }, { "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.8606878519058228 } ]
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.8053469657897949 }, { "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.8044493198394775 }, { "filename": "src/themes/index.ts", "retrieved_chunk": " const themeName = this.getReadyMadeThemes().includes(config.theme as SearchJSTheme)\n ? config.theme\n : defaultTheme\n return this.getCssVariables(this.getThemeValues(themeName))\n }\n /**\n * get theme css variable values\n *\n * @param {string} theme\n * @returns {object}", "score": 0.8030850887298584 }, { "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.8016679286956787 }, { "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.7933087348937988 } ]
typescript
as SearchJSTheme)) {
import { SearchJSTheme } from '../types' export const CssBackdropBackground = '--search-js-backdrop-bg' export const CssModalBackground = '--search-js-modal-bg' export const CssModalBoxShadow = '--search-js-modal-box-shadow' export const CssModalFooterBoxShadow = '--search-js-modal-footer-box-shadow' export const CssKeyboardButtonBoxShadow = '--search-js-keyboard-button-box-shadow' export const CssKeyboardButtonBackground = '--search-js-keyboard-button-bg' export const CssInputBackground = '--search-js-search-input-bg' export const CssInputPlaceholderColor = '--search-js-input-placeholder-color' export const CssItemBackground = '--search-js-item-bg' export const CssItemBoxShadow = '--search-js-item-box-shadow' export const CssTextColor = '--search-js-text-color' export const CssTheme = '--search-js-theme' export const CssWidth = '--search-js-width' export const CssHeight = '--search-js-height' export const CssFontFamily = '--search-js-font-family' export const CssPositionTop = '--search-js-top' export const AvailableThemes: any = { [SearchJSTheme.ThemeDark]: { [CssBackdropBackground]: 'rgba(47, 55, 69, 0.7)', [CssModalBackground]: '#1b1b1d', [CssModalBoxShadow]: 'inset 1px 1px 0 0 #2c2e40, 0 3px 8px 0 #000309', [CssModalFooterBoxShadow]: 'inset 0 1px 0 0 rgba(73, 76, 106, 0.5), 0 -4px 8px 0 rgba(0, 0, 0, 0.2)', [CssKeyboardButtonBoxShadow]: 'inset 0 -2px 0 0 #282d55, inset 0 0 1px 1px #51577d, 0 2px 2px 0 rgba(3, 4, 9, 0.3)', [CssKeyboardButtonBackground]: 'linear-gradient(-26.5deg, transparent 0%, transparent 100%)', [CssInputBackground]: 'black', [CssInputPlaceholderColor]: '#aeaeae', [CssItemBackground]: '#1c1e21', [CssItemBoxShadow]: 'none', [CssTextColor]: '#b3b3b3', },
[SearchJSTheme.ThemeLight]: {
[CssBackdropBackground]: 'rgba(101, 108, 133, 0.8)', [CssModalBackground]: '#f5f6f7', [CssModalBoxShadow]: 'inset 1px 1px 0 0 hsla(0, 0%, 100%, 0.5), 0 3px 8px 0 #555a64', [CssModalFooterBoxShadow]: '0 -1px 0 0 #e0e3e8, 0 -3px 6px 0 rgba(69, 98, 155, 0.12)', [CssKeyboardButtonBoxShadow]: 'inset 0 -2px 0 0 #cdcde6, inset 0 0 1px 1px #fff, 0 1px 2px 1px rgba(30, 35, 90, 0.4)', [CssKeyboardButtonBackground]: 'linear-gradient(-225deg, #d5dbe4, #f8f8f8)', [CssInputBackground]: 'white', [CssInputPlaceholderColor]: '#969faf', [CssItemBackground]: 'white', [CssItemBoxShadow]: '0 1px 3px 0 #d4d9e1', [CssTextColor]: '#969faf', }, [SearchJSTheme.ThemeGithubDark]: { [CssBackdropBackground]: 'rgba(1,4,9,0.8)', [CssModalBackground]: '#0D1116', [CssModalBoxShadow]: 'none', [CssModalFooterBoxShadow]: 'none', [CssKeyboardButtonBoxShadow]: 'none', [CssKeyboardButtonBackground]: 'none', [CssInputBackground]: 'transparent', [CssInputPlaceholderColor]: '#6D7681', [CssItemBackground]: 'transparent', [CssItemBoxShadow]: 'none', [CssTextColor]: '#C5CED6', [CssTheme]: 'transparent', }, [SearchJSTheme.ThemeGithubLight]: { [CssBackdropBackground]: 'rgba(27,31,36,0.5)', [CssModalBackground]: '#FFFFFF', [CssModalBoxShadow]: 'none', [CssModalFooterBoxShadow]: 'none', [CssKeyboardButtonBoxShadow]: 'none', [CssKeyboardButtonBackground]: 'none', [CssInputBackground]: 'transparent', [CssInputPlaceholderColor]: '#6E7781', [CssItemBackground]: 'transparent', [CssItemBoxShadow]: 'none', [CssTextColor]: '#1F2329', [CssTheme]: 'transparent', }, }
src/themes/AvailableThemes.ts
necessarylion-search-js-74bfb45
[ { "filename": "src/assets/Icon/index.ts", "retrieved_chunk": "<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.6380536556243896 }, { "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.6236058473587036 }, { "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.6235530376434326 }, { "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.623005747795105 }, { "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.5882475972175598 } ]
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.8075928092002869 }, { "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.8019521832466125 }, { "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.8012427091598511 }, { "filename": "src/themes/index.ts", "retrieved_chunk": " const themeName = this.getReadyMadeThemes().includes(config.theme as SearchJSTheme)\n ? config.theme\n : defaultTheme\n return this.getCssVariables(this.getThemeValues(themeName))\n }\n /**\n * get theme css variable values\n *\n * @param {string} theme\n * @returns {object}", "score": 0.8011388778686523 }, { "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.7898777723312378 } ]
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/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.7496973276138306 }, { "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.7472286224365234 }, { "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.7441179752349854 }, { "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.7385684251785278 }, { "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.7326900362968445 } ]
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.8055069446563721 }, { "filename": "src/themes/index.ts", "retrieved_chunk": " const themeName = this.getReadyMadeThemes().includes(config.theme as SearchJSTheme)\n ? config.theme\n : defaultTheme\n return this.getCssVariables(this.getThemeValues(themeName))\n }\n /**\n * get theme css variable values\n *\n * @param {string} theme\n * @returns {object}", "score": 0.7989262342453003 }, { "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.7959641218185425 }, { "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.795850396156311 }, { "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.7893781661987305 } ]
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/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.8545634746551514 }, { "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.8452106714248657 }, { "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.8094501495361328 }, { "filename": "src/components/Header.ts", "retrieved_chunk": "import { SearchJSConfig } from '../types'\nimport { clearIcon, searchIcon } from '../assets/Icon'\nimport { CLASS_CLEAR_ICON, CLASS_INPUT, DEFAULT_THEME_COLOR } from '../constant'\nexport class Header {\n /**\n * render header html string\n *\n * @param {SearchJSConfig} config\n * @returns {string}\n */", "score": 0.7721301317214966 }, { "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.7710941433906555 } ]
typescript
: hashIcon(), }) this.handleItemClickListener() }
import { hashIcon, historyIcon, loadingIcon } from '../assets/Icon' import { Footer } from '../components/Footer' import { Header } from '../components/Header' import { Item } from '../components/Item' import { DomListener } from './DomListener' import { SearchHistory } from './SearchHistory' import { SearchJSApp } from '..' import { SearchJSItem, SearchJSTheme } from '../types' import { Theme } from '../themes' import { CLASS_CONTAINER, ID, CLASS_MODAL, ID_HISTORIES, ID_LOADING, ID_RESULTS, CLASS_MODAL_HEADER, CLASS_MODAL_FOOTER, CLASS_MODAL_CONTENT, } from '../constant' export class SearchComponent { /** * the entire search js element * * @var {HTMLElement} element */ public element: HTMLElement /** * timer placeholder to handle search * * @var {number} searchTimer */ private searchTimer?: number /** * class constructor * * @param {SearchJSApp} app * @param {DomListener} domListener * @param {SearchHistory} searchHistory * @param {Theme} theme */ constructor( private app: SearchJSApp, private domListener: DomListener, private searchHistory: SearchHistory, private theme: Theme, ) { // add global css variable this.theme.createGlobalCssVariable(this.app.config) // append search element on parent element this.getParentElement().appendChild(this.createElement()) // render initial data list this.showHistory(this.searchHistory.getList()) this.domListener.onBackDropClick(() => { this.app.close() }) this.handleOnSearch() } /** * handle search and show list on result * * @returns {void} */ private handleOnSearch(): void { this.domListener.onSearch(async (keyword: string) => { if (!keyword) { clearTimeout(this.searchTimer) this.hideLoading() this.showHistory(this.searchHistory.getList()) this.hideSearchResult() return } this.hideHistories() this.hideSearchResult() if (this.app.config.onSearch) { this.showLoading() clearTimeout(this.searchTimer) this.searchTimer = setTimeout(async () => { const items = await this.app.config.onSearch(keyword) this.hideLoading() this.showSearchResult(items) }, this.app.config.onSearchDelay ?? 500) } else { this.showSearchResult(this.getItems(keyword)) } }) } /** * get list of items from config and filter with keyword from search input * * @param {string} keyword * @returns {Array<SearchJSItem> | null | undefined} */ private getItems(keyword: string): Array<SearchJSItem> | null | undefined { const items = this.app.config.data return items.filter((item) => { return ( (item.title && item.title.toLowerCase().includes(keyword)) || (item.description && item.description.toLowerCase().includes(keyword)) ) }) } /** * get parent element to append search-js element * * @returns {HTMLElement} */ private getParentElement(): HTMLElement { return this.app.config.element ?? document.body } private createElement() { const element = document.createElement('div') element.id = ID if (this.theme.getReadyMadeThemes().includes(this.app.config.theme as SearchJSTheme)) { element.classList.add(this.app.config.theme) } element.classList.add(CLASS_CONTAINER) const footer = new Footer() const header = new Header() element.innerHTML = `<div class="${CLASS_MODAL}"> <div class="${CLASS_MODAL_HEADER}">${header.render(this.app.config)}</div> <div id="${ID_LOADING}" class="${CLASS_MODAL_CONTENT}">${loadingIcon()}</div> <div id="${ID_HISTORIES}" class="${CLASS_MODAL_CONTENT}"></div> <div id="${ID_RESULTS}" class="${CLASS_MODAL_CONTENT}"></div> <div class="${CLASS_MODAL_FOOTER}">${footer.render()}</div> </div> ` this.element = element return this.element } /** * show item lists * * @param {Array<SearchJSItem>} items * @returns {void} */ private showSearchResult(items: Array<SearchJSItem>): void { const itemInstance = new Item() itemInstance.renderList({ id: ID_RESULTS, items: items, hideRemoveButton: true, notFoundLabel: 'No match found', icon: hashIcon(), }) this.handleItemClickListener() } /** * hide search result * * @returns {void} */ private hideSearchResult(): void { document.getElementById(ID_RESULTS).style.display = 'none' } /** * show history list * * @param {Array<SearchJSItem>} items * @returns {void} */ private showHistory(items: Array<SearchJSItem>): void { const itemInstance = new Item() itemInstance.renderList({ id: ID_HISTORIES, items: items, hideRemoveButton: false, notFoundLabel: 'No recent data', icon: historyIcon(), }) this.handleItemClickListener() } /** * hide history * * @returns {void} */ private hideHistories(): void { document.getElementById(ID_HISTORIES).style.display = 'none' } /** * listen on select and on remove event on item * * @return {void} */ private handleItemClickListener(): void { this.domListener.onItemClick( (data: any) => { this
.searchHistory.add(data) this.app.config.onSelected(data) }, (data: any) => {
this.searchHistory.remove(data) this.showHistory(this.searchHistory.getList()) }, ) } /** * show loading * * @returns {void} */ private showLoading(): void { document.getElementById(ID_LOADING).style.display = 'flex' } /** * hide loading * * @returns {void} */ private hideLoading(): void { document.getElementById(ID_LOADING).style.display = 'none' } }
src/utils/SearchComponent.ts
necessarylion-search-js-74bfb45
[ { "filename": "src/utils/DomListener.ts", "retrieved_chunk": " 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.816222071647644 }, { "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.8052197694778442 }, { "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.7997207641601562 }, { "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.7834120988845825 }, { "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.7814302444458008 } ]
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/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.8299807906150818 }, { "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.8216250538825989 }, { "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.766627311706543 }, { "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.7583491802215576 }, { "filename": "src/components/Header.ts", "retrieved_chunk": "import { SearchJSConfig } from '../types'\nimport { clearIcon, searchIcon } from '../assets/Icon'\nimport { CLASS_CLEAR_ICON, CLASS_INPUT, DEFAULT_THEME_COLOR } from '../constant'\nexport class Header {\n /**\n * render header html string\n *\n * @param {SearchJSConfig} config\n * @returns {string}\n */", "score": 0.7548647522926331 } ]
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/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.8166797757148743 }, { "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.8050699830055237 }, { "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.796207070350647 }, { "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.7791094779968262 }, { "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.7771774530410767 } ]
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": " 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.9039525985717773 }, { "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.8836536407470703 }, { "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.8727157711982727 }, { "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.8632175326347351 }, { "filename": "src/index.ts", "retrieved_chunk": " *\n * @returns {void}\n */\n public open(): void {\n this.component.element.style.display = 'flex'\n this.focusOnSearch()\n }\n /**\n * function to close search modal\n *", "score": 0.8617264032363892 } ]
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/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.7175658941268921 }, { "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.704433262348175 }, { "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.7039698958396912 }, { "filename": "src/scorer/feature/reblogsFeatureScorer.ts", "retrieved_chunk": "import FeatureScorer from \"../FeatureScorer\";\nimport { StatusType, accFeatureType } from \"../../types\";\nimport { mastodon } from \"masto\";\nimport FeatureStorage from \"../../features/FeatureStore\";\nexport default class reblogsFeatureScorer extends FeatureScorer {\n constructor() {\n super({\n featureGetter: (api: mastodon.Client) => { return FeatureStorage.getTopReblogs(api) },\n verboseName: \"Reblogs\",\n description: \"Posts that are from your most reblogger users\",", "score": 0.7009954452514648 }, { "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.6984045505523682 } ]
typescript
async getWeights(): Promise<weightsType> {
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.8498878479003906 }, { "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.8467345833778381 }, { "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.8196742534637451 }, { "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.7998167276382446 }, { "filename": "src/Storage.ts", "retrieved_chunk": " OPENINGS = \"openings\",\n}\ntype StorageValue = serverFeatureType | accFeatureType | mastodon.v1.Account | weightsType | string\nexport default class Storage {\n protected static async get(key: Key, groupedByUser = true, suffix = \"\"): Promise<StorageValue> {\n const suffixKey = this.suffix(key, suffix);\n const storageKey = groupedByUser ? await this.prefix(suffixKey) : suffixKey;\n const jsonValue = await AsyncStorage.getItem(storageKey);\n const value = jsonValue != null ? JSON.parse(jsonValue) : null;\n return value != null ? value[storageKey] : null;", "score": 0.7931277751922607 } ]
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/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.8117821216583252 }, { "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.8007510304450989 }, { "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.7945094108581543 }, { "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.7785799503326416 }, { "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.7746692895889282 } ]
typescript
async weightAdjust(statusWeights: weightsType): Promise<weightsType | undefined> {
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/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.8216443061828613 }, { "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.8060808181762695 }, { "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.8003972172737122 }, { "filename": "src/features/reblogsFeature.ts", "retrieved_chunk": "import { login, mastodon } from \"masto\";\nexport default async function getReblogsFeature(api: mastodon.Client) {\n let results: any[] = [];\n let pages = 3;\n for await (const page of api.v1.timelines.listHome({ limit: 80 })) {\n results = results.concat(page)\n pages--;\n if (pages === 0 || results.length < 80) {\n break;\n }", "score": 0.8003266453742981 }, { "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.7938219308853149 } ]
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/feeds/homeFeed.ts", "retrieved_chunk": "import { mastodon } from \"masto\";\nexport default async function getHomeFeed(api: mastodon.Client, user: mastodon.v1.Account) {\n let results: any[] = [];\n let pages = 10;\n for await (const page of api.v1.timelines.listHome()) {\n results = results.concat(page)\n pages--;\n //check if status is less than 12 hours old\n if (pages === 0 || new Date(page[0].createdAt) < new Date(Date.now() - 43200000)) {\n break;", "score": 0.7897750735282898 }, { "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.7764666080474854 }, { "filename": "src/feeds/topPostsFeed.ts", "retrieved_chunk": " return [];\n }\n const data: any[] = serializer.deserialize('application/json', await res.text());\n if (data === undefined) {\n return [];\n }\n return data.map((status: any) => {\n status.topPost = true;\n return status;\n }).slice(0, 10)", "score": 0.7568337917327881 }, { "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.7507968544960022 }, { "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.7457640171051025 } ]
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.8072684407234192 }, { "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.7906205654144287 }, { "filename": "src/scorer/index.ts", "retrieved_chunk": " interactsFeatureScorer,\n reblogsFeatureScorer,\n topPostFeatureScorer,\n diversityFeedScorer,\n reblogsFeedScorer,\n FeedScorer,\n FeatureScorer\n}", "score": 0.7660797834396362 }, { "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.7575770616531372 }, { "filename": "src/scorer/feature/reblogsFeatureScorer.ts", "retrieved_chunk": "import FeatureScorer from \"../FeatureScorer\";\nimport { StatusType, accFeatureType } from \"../../types\";\nimport { mastodon } from \"masto\";\nimport FeatureStorage from \"../../features/FeatureStore\";\nexport default class reblogsFeatureScorer extends FeatureScorer {\n constructor() {\n super({\n featureGetter: (api: mastodon.Client) => { return FeatureStorage.getTopReblogs(api) },\n verboseName: \"Reblogs\",\n description: \"Posts that are from your most reblogger users\",", "score": 0.756264328956604 } ]
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/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.8526663184165955 }, { "filename": "src/Storage.ts", "retrieved_chunk": " const openings = parseInt(await this.get(Key.OPENINGS, true) as string);\n return openings;\n }\n static async getIdentity(): Promise<mastodon.v1.Account> {\n const userJson = await AsyncStorage.getItem(Key.USER);\n const user: mastodon.v1.Account = userJson != null ? JSON.parse(userJson) : null;\n return user;\n }\n static async setIdentity(user: mastodon.v1.Account) {\n const userJson = JSON.stringify(user);", "score": 0.836604118347168 }, { "filename": "src/Storage.ts", "retrieved_chunk": " OPENINGS = \"openings\",\n}\ntype StorageValue = serverFeatureType | accFeatureType | mastodon.v1.Account | weightsType | string\nexport default class Storage {\n protected static async get(key: Key, groupedByUser = true, suffix = \"\"): Promise<StorageValue> {\n const suffixKey = this.suffix(key, suffix);\n const storageKey = groupedByUser ? await this.prefix(suffixKey) : suffixKey;\n const jsonValue = await AsyncStorage.getItem(storageKey);\n const value = jsonValue != null ? JSON.parse(jsonValue) : null;\n return value != null ? value[storageKey] : null;", "score": 0.8325125575065613 }, { "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.8265904188156128 }, { "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.8145813345909119 } ]
typescript
const user = await this.getIdentity();
import { mastodon } from "masto"; import { FeedFetcher, Scorer, StatusType, weightsType } from "./types"; import { favsFeatureScorer, interactsFeatureScorer, reblogsFeatureScorer, diversityFeedScorer, reblogsFeedScorer, FeatureScorer, FeedScorer, topPostFeatureScorer } from "./scorer"; import weightsStore from "./weights/weightsStore"; import getHomeFeed from "./feeds/homeFeed"; import topPostsFeed from "./feeds/topPostsFeed"; import Storage from "./Storage"; import { StaticArrayPaginator } from "./Paginator" export default class TheAlgorithm { user: mastodon.v1.Account; fetchers = [getHomeFeed, topPostsFeed] featureScorer = [new favsFeatureScorer(), new reblogsFeatureScorer(), new interactsFeatureScorer(), new topPostFeatureScorer()] feedScorer = [new reblogsFeedScorer(), new diversityFeedScorer()] feed: StatusType[] = []; api: mastodon.Client; constructor(api: mastodon.Client, user: mastodon.v1.Account, valueCalculator: (((scores: weightsType) => Promise<number>) | null) = null) { this.api = api; this.user = user; Storage.setIdentity(user); Storage.logOpening(); if (valueCalculator) { this._getValueFromScores = valueCalculator; } this.setDefaultWeights(); } async getFeedAdvanced( fetchers: Array<FeedFetcher>, featureScorer: Array<FeatureScorer>, feedScorer: Array<FeedScorer> ) { this.fetchers = fetchers; this.featureScorer = featureScorer; this.feedScorer = feedScorer; return this.getFeed(); } async getFeed(): Promise<StatusType[]> { const { fetchers, featureScorer, feedScorer } = this; const response = await Promise.all(fetchers.map(fetcher => fetcher(this.api, this.user))) this.feed = response.flat(); // Load and Prepare Features await Promise.all(featureScorer.map(scorer => scorer.getFeature(this.api))); await Promise.all(feedScorer.map(scorer => scorer.setFeed(this.feed))); // Get Score Names const scoreNames = featureScorer.map(scorer => scorer.getVerboseName()); const feedScoreNames = feedScorer.map(scorer => scorer.getVerboseName()); // Score Feed let scoredFeed: StatusType[] = [] for (const status of this.feed) { // Load Scores for each status const featureScore = await Promise.all(featureScorer.map(scorer => scorer.score(this.api, status))); const feedScore = await Promise.all(feedScorer.map(scorer => scorer.score(status))); // Turn Scores into Weight Objects const featureScoreObj = this._getScoreObj(scoreNames, featureScore); const feedScoreObj = this._getScoreObj(feedScoreNames, feedScore); const scoreObj = { ...featureScoreObj, ...feedScoreObj }; // Add Weight Object to Status status["scores"] = scoreObj; status["value"] = await this._getValueFromScores(scoreObj); scoredFeed.push(status); } // Remove Replies, Stuff Already Retweeted, and Nulls scoredFeed = scoredFeed .filter((item: StatusType) => item != undefined) .filter((item: StatusType) => item.inReplyToId === null) .filter((item: StatusType) => item.content.includes("RT @") === false) .filter((item: StatusType) => !(item?.reblog?.reblogged ?? false)) // Add Time Penalty scoredFeed = scoredFeed.map((item: StatusType) => { const seconds = Math.floor((new Date().getTime() - new Date(item.createdAt).getTime()) / 1000); const timediscount = Math.pow((1 + 0.7 * 0.2), -Math.pow((seconds / 3600), 2)); item.value = (item.value ?? 0) * timediscount return item; }) // Sort Feed scoredFeed = scoredFeed.sort((a, b) => (b.value ?? 0) - (a.value ?? 0)); //Remove duplicates scoredFeed = [...new Map(scoredFeed.map((item: StatusType) => [item["uri"], item])).values()]; this.feed = scoredFeed console.log(this.feed); return this.feed; } private _getScoreObj(scoreNames: string[], scores: number[]): weightsType { return scoreNames.reduce((obj: weightsType, cur, i) => { obj[cur] = scores[i]; return obj; }, {}); } private async _getValueFromScores(scores: weightsType): Promise<number> { const weights = await weightsStore.getWeightsMulti(Object.keys(scores)); const weightedScores = Object.keys(scores).reduce((obj: number, cur) => { obj = obj + (scores[cur] * weights[cur] ?? 0) return obj; }, 0); return weightedScores; } getWeightNames(): string[] { const scorers = [...this.featureScorer, ...this.feedScorer]; return [...scorers.map(scorer => scorer.getVerboseName())] } async setDefaultWeights(): Promise<void> { //Set Default Weights if they don't exist const scorers = [...this.featureScorer, ...this.feedScorer]; Promise.all(scorers.map(
scorer => weightsStore.defaultFallback(scorer.getVerboseName(), scorer.getDefaultWeight()))) }
getWeightDescriptions(): string[] { const scorers = [...this.featureScorer, ...this.feedScorer]; return [...scorers.map(scorer => scorer.getDescription())] } async getWeights(): Promise<weightsType> { const verboseNames = this.getWeightNames(); const weights = await weightsStore.getWeightsMulti(verboseNames); return weights; } async setWeights(weights: weightsType): Promise<StatusType[]> { await weightsStore.setWeightsMulti(weights); const scoredFeed: StatusType[] = [] for (const status of this.feed) { if (!status["scores"]) { return this.getFeed(); } status["value"] = await this._getValueFromScores(status["scores"]); scoredFeed.push(status); } this.feed = scoredFeed.sort((a, b) => (b.value ?? 0) - (a.value ?? 0)); return this.feed; } getDescription(verboseName: string): string { const scorers = [...this.featureScorer, ...this.feedScorer]; const scorer = scorers.find(scorer => scorer.getVerboseName() === verboseName); if (scorer) { return scorer.getDescription(); } return ""; } async weightAdjust(statusWeights: weightsType): Promise<weightsType | undefined> { //Adjust Weights based on user interaction if (statusWeights == undefined) return; const mean = Object.values(statusWeights).reduce((accumulator, currentValue) => accumulator + Math.abs(currentValue), 0) / Object.values(statusWeights).length; const currentWeight: weightsType = await this.getWeights() const currentMean = Object.values(currentWeight).reduce((accumulator, currentValue) => accumulator + currentValue, 0) / Object.values(currentWeight).length; for (let key in currentWeight) { let reweight = 1 - (Math.abs(statusWeights[key]) / mean) / (currentWeight[key] / currentMean); currentWeight[key] = currentWeight[key] + 0.02 * currentWeight[key] * reweight; console.log(reweight); } await this.setWeights(currentWeight); return currentWeight; } }
src/index.ts
pkreissel-fedialgo-a1b7a40
[ { "filename": "src/scorer/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.7149541974067688 }, { "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.7110738754272461 }, { "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.7092731595039368 }, { "filename": "src/scorer/feature/favsFeatureScorer.ts", "retrieved_chunk": "import FeatureScorer from '../FeatureScorer'\nimport favsFeature from '../../features/favsFeature'\nimport { StatusType, accFeatureType } from '../../types'\nimport { mastodon } from 'masto'\nimport FeatureStorage from '../../features/FeatureStore'\nexport default class favsFeatureScorer extends FeatureScorer {\n constructor() {\n super({\n featureGetter: (api: mastodon.Client) => FeatureStorage.getTopFavs(api),\n verboseName: \"Favs\",", "score": 0.6985479593276978 }, { "filename": "src/scorer/feature/reblogsFeatureScorer.ts", "retrieved_chunk": "import FeatureScorer from \"../FeatureScorer\";\nimport { StatusType, accFeatureType } from \"../../types\";\nimport { mastodon } from \"masto\";\nimport FeatureStorage from \"../../features/FeatureStore\";\nexport default class reblogsFeatureScorer extends FeatureScorer {\n constructor() {\n super({\n featureGetter: (api: mastodon.Client) => { return FeatureStorage.getTopReblogs(api) },\n verboseName: \"Reblogs\",\n description: \"Posts that are from your most reblogger users\",", "score": 0.6935962438583374 } ]
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/feeds/homeFeed.ts", "retrieved_chunk": "import { mastodon } from \"masto\";\nexport default async function getHomeFeed(api: mastodon.Client, user: mastodon.v1.Account) {\n let results: any[] = [];\n let pages = 10;\n for await (const page of api.v1.timelines.listHome()) {\n results = results.concat(page)\n pages--;\n //check if status is less than 12 hours old\n if (pages === 0 || new Date(page[0].createdAt) < new Date(Date.now() - 43200000)) {\n break;", "score": 0.7628172636032104 }, { "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.7499120235443115 }, { "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.7415852546691895 }, { "filename": "src/feeds/topPostsFeed.ts", "retrieved_chunk": " return [];\n }\n const data: any[] = serializer.deserialize('application/json', await res.text());\n if (data === undefined) {\n return [];\n }\n return data.map((status: any) => {\n status.topPost = true;\n return status;\n }).slice(0, 10)", "score": 0.7350857257843018 }, { "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.7139623165130615 } ]
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/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.8555649518966675 }, { "filename": "src/Storage.ts", "retrieved_chunk": " OPENINGS = \"openings\",\n}\ntype StorageValue = serverFeatureType | accFeatureType | mastodon.v1.Account | weightsType | string\nexport default class Storage {\n protected static async get(key: Key, groupedByUser = true, suffix = \"\"): Promise<StorageValue> {\n const suffixKey = this.suffix(key, suffix);\n const storageKey = groupedByUser ? await this.prefix(suffixKey) : suffixKey;\n const jsonValue = await AsyncStorage.getItem(storageKey);\n const value = jsonValue != null ? JSON.parse(jsonValue) : null;\n return value != null ? value[storageKey] : null;", "score": 0.836664617061615 }, { "filename": "src/Storage.ts", "retrieved_chunk": " const openings = parseInt(await this.get(Key.OPENINGS, true) as string);\n return openings;\n }\n static async getIdentity(): Promise<mastodon.v1.Account> {\n const userJson = await AsyncStorage.getItem(Key.USER);\n const user: mastodon.v1.Account = userJson != null ? JSON.parse(userJson) : null;\n return user;\n }\n static async setIdentity(user: mastodon.v1.Account) {\n const userJson = JSON.stringify(user);", "score": 0.8259830474853516 }, { "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.824828565120697 }, { "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.8151462078094482 } ]
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/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.738487720489502 }, { "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.7343310117721558 }, { "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.7337306141853333 }, { "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.7316746711730957 }, { "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.7285752296447754 } ]
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.8551422357559204 }, { "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.8241796493530273 }, { "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.8075729608535767 }, { "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.8002238273620605 }, { "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.7948628664016724 } ]
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\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.7843818664550781 }, { "filename": "src/web/index.ts", "retrieved_chunk": "\t\t)\n\t\tanimationId = window.requestAnimationFrame(_gameloop)\n\t}\n\tlet animationId = window.requestAnimationFrame(_gameloop)\n\tconst setLegend = (...bitmaps: [string, string][]): void => {\n\t\tif (bitmaps.length == 0) throw new Error('There needs to be at least one sprite in the legend.')\n\t\tif (!Array.isArray(bitmaps[0])) throw new Error('The sprites passed into setLegend each need to be in square brackets, like setLegend([player, bitmap`...`]).')\n\t\tbitmaps.forEach(([ key ]) => {\n\t\t\tif (key === '.') throw new Error(`Can't reassign \".\" bitmap`)\n\t\t\tif (key.length !== 1) throw new Error(`Bitmaps must have one character names`)", "score": 0.7656669616699219 }, { "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.7651787400245667 }, { "filename": "src/web/index.ts", "retrieved_chunk": "\t}\n\tconst afterInputs: (() => void)[] = []\n\tconst keydown = (e: KeyboardEvent) => {\n\t\tconst key = e.key\n\t\tif (!VALID_INPUTS.includes(key as any)) return\n\t\tfor (const validKey of VALID_INPUTS)\n\t\t\tif (key === validKey) tileInputs[key].forEach(fn => fn())\n\t\tafterInputs.forEach(f => f())\n\t\tstate.sprites.forEach((s: any) => {\n\t\t\ts.dx = 0", "score": 0.763896107673645 }, { "filename": "src/base/text.ts", "retrieved_chunk": "import type { Rgba, TextElement } from '../api.js'\nexport function composeText(texts: TextElement[]): { char: string, color: Rgba }[][] {\n\tconst emptyCell = () => ({ char: ' ', color: [0, 0, 0, 0] as Rgba })\n\tconst range = <T>(length: number, fn: () => T): T[] => Array.from({ length }, fn)\n\tconst gridFromSize = (w: number, h: number) => range(h, () => range(w, emptyCell))\n\tconst CHARS_MAX_X = 20\n\tconst CHARS_MAX_Y = 16\n\tconst grid = gridFromSize(CHARS_MAX_X, CHARS_MAX_Y)\n\tfor (const { x: sx, y: sy, content, color } of texts) {\n\t\tlet y = sy", "score": 0.762993574142456 } ]
typescript
addText = (str: string, opts: AddTextOptions = {}): 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\tsprite._y += dy\n\t\t}\n\t\treturn canMove\n\t}\n\tconst getGrid = (): SpriteType[][] => {\n\t\tconst { width, height } = gameState.dimensions\n\t\tconst grid: SpriteType[][] = new Array(width*height).fill(0).map(_ => [])\n\t\tgameState.sprites.forEach(s => {\n\t\t\tconst i = s.x+s.y*width\n\t\t\tgrid[i]!.push(s)", "score": 0.8113245368003845 }, { "filename": "src/base/index.ts", "retrieved_chunk": "\t\t}\n\t}\n\tconst _canMoveToPush = (sprite: Sprite, dx: number, dy: number): boolean => {\n\t\tconst { x, y, type } = sprite\n\t\tconst { width, height } = gameState.dimensions\n\t\tconst i = (x+dx)+(y+dy)*width\n\t\tconst inBounds = (x+dx < width && x+dx >= 0 && y+dy < height && y+dy >= 0)\n\t\tif (!inBounds) return false\n\t\tconst grid = getGrid()\n\t\tconst notSolid = !gameState.solids.includes(type)", "score": 0.7431327700614929 }, { "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.7341361045837402 }, { "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.7308201193809509 }, { "filename": "src/base/index.ts", "retrieved_chunk": "\t\tset y(newY) {\n\t\t\tconst dy = newY - this.y\n\t\t\tif (_canMoveToPush(this, 0, dy)) this.dy = dy\n\t\t}\n\t\tget y() {\n\t\t\treturn this._y\n\t\t}\n\t\tremove() {\n\t\t\tgameState.sprites = gameState.sprites.filter(s => s !== this)\n\t\t\treturn this", "score": 0.7127581834793091 } ]
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/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.815125584602356 }, { "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.7998828887939453 }, { "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.7659828662872314 }, { "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.7072579860687256 }, { "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.6996731758117676 } ]
typescript
export function baseEngine(): { api: BaseEngineAPI, state: GameState } {
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": "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.7877089381217957 }, { "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.7704691886901855 }, { "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.7440125942230225 }, { "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.7319178581237793 }, { "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.6586052775382996 } ]
typescript
if (instruments.includes(instrument) && frequency !== undefined) playFrequency(frequency, duration, instrument, ctx, dest) }
/* song form [ [duration, instrument, pitch, duration, ...], ] Syntax: 500: 64.4~500 + c5~1000 [500, 'sine', 64.4, 500, 'sine', 'c5', 1000] Comma between each tune element. Whitespace ignored. */ import { type Tune, instrumentKey, InstrumentType, reverseInstrumentKey } from '../api.js' export const textToTune = (text: string): Tune => { const elements = text.replace(/\s/g, '').split(',') const tune = [] for (const element of elements) { if (!element) continue const [durationRaw, notesRaw] = element.split(':') const duration = Math.round(parseInt(durationRaw ?? '0', 10)) const notes = (notesRaw || '').split('+').map((noteRaw) => { if (!noteRaw) return [] const [, pitchRaw, instrumentRaw, durationRaw] = noteRaw.match(/^(.+)([~\-^\/])(.+)$/)! return [ instrumentKey[instrumentRaw!] ?? 'sine', isNaN(parseInt(pitchRaw ?? '', 10)) ? pitchRaw! : parseInt(pitchRaw!, 10), parseInt(durationRaw ?? '0', 10) ] }) tune.push([duration, ...notes].flat()) } return tune as Tune } export const tuneToText = (tune: Tune): string => { const groupNotes = (notes: (number | string)[]) => { const groups = [] for (let i = 0; i < notes.length; i++) { if (i % 3 === 0) { groups.push([notes[i]!]) } else { groups[groups.length-1]!.push(notes[i]!) } } return groups } const notesToString = ([duration, ...notes]: Tune[number]) => ( notes.length === 0 ? duration : `${duration}: ${groupNotes(notes).map(notesToStringHelper).join(' + ')}` ) const notesToStringHelper = ([instrument, duration, note]: (number | string)[]) => ( `${duration
}${reverseInstrumentKey[instrument as InstrumentType]}${note}` ) return tune.map(notesToString).join(',\n') }
src/base/tune.ts
hackclub-sprig-engine-e5e3c0c
[ { "filename": "src/web/tune.ts", "retrieved_chunk": "\t\t\tconst duration = noteSet[j+2] as number\n\t\t\tconst frequency = typeof note === 'string' \n\t\t\t\t? tones[note.toUpperCase()]\n\t\t\t\t: 2**((note-69)/12)*440\n\t\t\tif (instruments.includes(instrument) && frequency !== undefined) playFrequency(frequency, duration, instrument, ctx, dest)\n\t\t}\n\t\tawait sleep(sleepTime)\n\t}\n}\nlet audioCtx: AudioContext | null = null", "score": 0.7086147665977478 }, { "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.6826202869415283 }, { "filename": "src/base/index.ts", "retrieved_chunk": "\t\t\tthrow new Error('Tagged template literal must be used like name`text`, instead of name(`text`)')\n\t\t}\n\t\tconst string = strings.reduce((p, c, i) => p + c + (interps[i] ?? ''), '')\n\t\treturn cb(string)\n\t}\n}\nexport type BaseEngineAPI = Pick<\n\tFullSprigAPI,\n\t| 'setMap'\n\t| 'addText'", "score": 0.6641687154769897 }, { "filename": "src/web/index.ts", "retrieved_chunk": "\t\t\ts.dy = 0\n\t\t})\n\t\te.preventDefault()\n\t}\n\tcanvas.addEventListener('keydown', keydown)\n\tconst onInput = (key: InputKey, fn: () => void): void => {\n\t\tif (!VALID_INPUTS.includes(key))\n\t\t\tthrow new Error(`Unknown input key, \"${key}\": expected one of ${VALID_INPUTS.join(', ')}`)\n\t\ttileInputs[key].push(fn)\n\t}", "score": 0.6604883670806885 }, { "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.6520297527313232 } ]
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.7976030707359314 }, { "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.7915955781936646 }, { "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.7612801790237427 }, { "filename": "src/web/text.ts", "retrieved_chunk": "\t\t\t\t\ty++\n\t\t\t}\n\t\t\txt += 8\n\t\t}\n\t}\n\tconst canvas = makeCanvas(160, 128)\n\tcanvas.getContext('2d')!.putImageData(img, 0, 0)\n\treturn canvas\n}", "score": 0.75543612241745 }, { "filename": "src/base/index.ts", "retrieved_chunk": "\t\t\tsprite._y += dy\n\t\t}\n\t\treturn canMove\n\t}\n\tconst getGrid = (): SpriteType[][] => {\n\t\tconst { width, height } = gameState.dimensions\n\t\tconst grid: SpriteType[][] = new Array(width*height).fill(0).map(_ => [])\n\t\tgameState.sprites.forEach(s => {\n\t\t\tconst i = s.x+s.y*width\n\t\t\tgrid[i]!.push(s)", "score": 0.7240328192710876 } ]
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\tsprite._y += dy\n\t\t}\n\t\treturn canMove\n\t}\n\tconst getGrid = (): SpriteType[][] => {\n\t\tconst { width, height } = gameState.dimensions\n\t\tconst grid: SpriteType[][] = new Array(width*height).fill(0).map(_ => [])\n\t\tgameState.sprites.forEach(s => {\n\t\t\tconst i = s.x+s.y*width\n\t\t\tgrid[i]!.push(s)", "score": 0.806067705154419 }, { "filename": "src/base/index.ts", "retrieved_chunk": "\t\t}\n\t}\n\tconst _canMoveToPush = (sprite: Sprite, dx: number, dy: number): boolean => {\n\t\tconst { x, y, type } = sprite\n\t\tconst { width, height } = gameState.dimensions\n\t\tconst i = (x+dx)+(y+dy)*width\n\t\tconst inBounds = (x+dx < width && x+dx >= 0 && y+dy < height && y+dy >= 0)\n\t\tif (!inBounds) return false\n\t\tconst grid = getGrid()\n\t\tconst notSolid = !gameState.solids.includes(type)", "score": 0.720461368560791 }, { "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.7175912261009216 }, { "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.7008395791053772 }, { "filename": "src/base/index.ts", "retrieved_chunk": "\t\t\tthis._y = y\n\t\t\tthis.dx = 0\n\t\t\tthis.dy = 0\n\t\t}\n\t\tset type(newType) {\n\t\t\tconst legendDict = Object.fromEntries(gameState.legend)\n\t\t\tif (!(newType in legendDict)) throw new Error(`\"${newType}\" isn\\'t in the legend.`)\n\t\t\tthis.remove()\n\t\t\taddSprite(this._x, this._y, newType)\n\t\t}", "score": 0.699951171875 } ]
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/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.7800809144973755 }, { "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.7579957842826843 }, { "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.7481301426887512 }, { "filename": "src/image-data/index.ts", "retrieved_chunk": "\t\t},\n\t\tsetBackground: (kind: string) => background = kind,\n\t\tsetTimeout: (fn: TimerHandler, ms: number) => {\n\t\t\tconst timer = setTimeout(fn, ms)\n\t\t\ttimeouts.push(timer)\n\t\t\treturn timer\n\t\t},\n\t\tsetInterval: (fn: TimerHandler, ms: number) => {\n\t\t\tconst timer = setInterval(fn, ms)\n\t\t\tintervals.push(timer)", "score": 0.7220548987388611 }, { "filename": "src/base/index.ts", "retrieved_chunk": "\t\tgetGrid,\n\t\tgetTile,\n\t\ttilesWith,\n\t\tclearTile, \n\t\tsetSolids, \n\t\tsetPushables, \n\t\tsetBackground: (type: string) => { gameState.background = type },\n\t\tmap: _makeTag(text => text),\n\t\tbitmap: _makeTag(text => text),\n\t\tcolor: _makeTag(text => text),", "score": 0.7193318605422974 } ]
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": "\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.7601419687271118 }, { "filename": "src/web/index.ts", "retrieved_chunk": "\t}\n\tlet tileInputs: Record<InputKey, (() => void)[]> = {\n\t\tw: [],\n\t\ts: [],\n\t\ta: [],\n\t\td: [],\n\t\ti: [],\n\t\tj: [],\n\t\tk: [],\n\t\tl: []", "score": 0.6924964189529419 }, { "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.6883310079574585 }, { "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.6847820281982422 }, { "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.6650571227073669 } ]
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/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.7800809144973755 }, { "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.7579957842826843 }, { "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.7481301426887512 }, { "filename": "src/image-data/index.ts", "retrieved_chunk": "\t\t},\n\t\tsetBackground: (kind: string) => background = kind,\n\t\tsetTimeout: (fn: TimerHandler, ms: number) => {\n\t\t\tconst timer = setTimeout(fn, ms)\n\t\t\ttimeouts.push(timer)\n\t\t\treturn timer\n\t\t},\n\t\tsetInterval: (fn: TimerHandler, ms: number) => {\n\t\t\tconst timer = setInterval(fn, ms)\n\t\t\tintervals.push(timer)", "score": 0.7220548987388611 }, { "filename": "src/base/index.ts", "retrieved_chunk": "\t\tgetGrid,\n\t\tgetTile,\n\t\ttilesWith,\n\t\tclearTile, \n\t\tsetSolids, \n\t\tsetPushables, \n\t\tsetBackground: (type: string) => { gameState.background = type },\n\t\tmap: _makeTag(text => text),\n\t\tbitmap: _makeTag(text => text),\n\t\tcolor: _makeTag(text => text),", "score": 0.7193318605422974 } ]
typescript
const playTuneRes = playTune(tune, n) tunes.push(playTuneRes) return playTuneRes }
import type { AddTextOptions, FullSprigAPI, GameState, SpriteType } from '../api.js' import { palette } from './palette.js' export * from './font.js' export * from './palette.js' export * from './text.js' export * from './tune.js' // Tagged template literal factory go brrr const _makeTag = <T>(cb: (string: string) => T) => { return (strings: TemplateStringsArray, ...interps: string[]) => { if (typeof strings === 'string') { throw new Error('Tagged template literal must be used like name`text`, instead of name(`text`)') } const string = strings.reduce((p, c, i) => p + c + (interps[i] ?? ''), '') return cb(string) } } export type BaseEngineAPI = Pick< FullSprigAPI, | 'setMap' | 'addText' | 'clearText' | 'addSprite' | 'getGrid' | 'getTile' | 'tilesWith' | 'clearTile' | 'setSolids' | 'setPushables' | 'setBackground' | 'map' | 'bitmap' | 'color' | 'tune' | 'getFirst' | 'getAll' | 'width' | 'height' > export function baseEngine(): { api
: BaseEngineAPI, state: GameState } {
const gameState: GameState = { legend: [], texts: [], dimensions: { width: 0, height: 0, }, sprites: [], solids: [], pushable: {}, background: null } class Sprite implements SpriteType { _type: string _x: number _y: number dx: number dy: number constructor(type: string, x: number, y: number) { this._type = type this._x = x this._y = y this.dx = 0 this.dy = 0 } set type(newType) { const legendDict = Object.fromEntries(gameState.legend) if (!(newType in legendDict)) throw new Error(`"${newType}" isn\'t in the legend.`) this.remove() addSprite(this._x, this._y, newType) } get type() { return this._type } set x(newX) { const dx = newX - this.x if (_canMoveToPush(this, dx, 0)) this.dx = dx } get x() { return this._x } set y(newY) { const dy = newY - this.y if (_canMoveToPush(this, 0, dy)) this.dy = dy } get y() { return this._y } remove() { gameState.sprites = gameState.sprites.filter(s => s !== this) return this } } const _canMoveToPush = (sprite: Sprite, dx: number, dy: number): boolean => { const { x, y, type } = sprite const { width, height } = gameState.dimensions const i = (x+dx)+(y+dy)*width const inBounds = (x+dx < width && x+dx >= 0 && y+dy < height && y+dy >= 0) if (!inBounds) return false const grid = getGrid() const notSolid = !gameState.solids.includes(type) const noMovement = dx === 0 && dy === 0 const movingToEmpty = i < grid.length && grid[i]!.length === 0 if (notSolid || noMovement || movingToEmpty) { sprite._x += dx sprite._y += dy return true } let canMove = true const { pushable } = gameState grid[i]!.forEach(sprite => { const isSolid = gameState.solids.includes(sprite.type) const isPushable = (type in pushable) && pushable[type]!.includes(sprite.type) if (isSolid && !isPushable) canMove = false if (isSolid && isPushable) { canMove = canMove && _canMoveToPush(sprite as Sprite, dx, dy) } }) if (canMove) { sprite._x += dx sprite._y += dy } return canMove } const getGrid = (): SpriteType[][] => { const { width, height } = gameState.dimensions const grid: SpriteType[][] = new Array(width*height).fill(0).map(_ => []) gameState.sprites.forEach(s => { const i = s.x+s.y*width grid[i]!.push(s) }) const legendIndex = (t: SpriteType) => gameState.legend.findIndex(l => l[0] == t.type) for (const tile of grid) tile.sort((a, b) => legendIndex(a) - legendIndex(b)) return grid } const _checkBounds = (x: number, y: number): void => { const { width, height } = gameState.dimensions if (x >= width || x < 0 || y < 0 || y >= height) throw new Error(`Sprite out of bounds.`) } const _checkLegend = (type: string): void => { if (!(type in Object.fromEntries(gameState.legend))) throw new Error(`Unknown sprite type: ${type}`) } const addSprite = (x: number, y: number, type: string): void => { if (type === '.') return _checkBounds(x, y) _checkLegend(type) const s = new Sprite(type, x, y) gameState.sprites.push(s) } const _allEqual = <T>(arr: T[]): boolean => arr.every(val => val === arr[0]) const setMap = (string: string): void => { if (!string) throw new Error('Tried to set empty map.') if (string.constructor == Object) throw new Error('setMap() takes a string, not a dict.') // https://stackoverflow.com/a/51285298 if (Array.isArray(string)) throw new Error('It looks like you passed an array into setMap(). Did you mean to use something like setMap(levels[level]) instead of setMap(levels)?') const rows = string.trim().split("\n").map(x => x.trim()) const rowLengths = rows.map(x => x.length) const isRect = _allEqual(rowLengths) if (!isRect) throw new Error('Level must be rectangular.') const w = rows[0]?.length ?? 0 const h = rows.length gameState.dimensions.width = w gameState.dimensions.height = h gameState.sprites = [] const nonSpace = string.split("").filter(x => x !== " " && x !== "\n") // \S regex was too slow for (let i = 0; i < w*h; i++) { const type = nonSpace[i]! if (type === '.') continue const x = i%w const y = Math.floor(i/w) addSprite(x, y, type) } } const clearTile = (x: number, y: number): void => { gameState.sprites = gameState.sprites.filter(s => s.x !== x || s.y !== y) } const addText = (str: string, opts: AddTextOptions = {}): void => { const CHARS_MAX_X = 21 const padLeft = Math.floor((CHARS_MAX_X - str.length)/2) if (Array.isArray(opts.color)) throw new Error('addText no longer takes an RGBA color. Please use a Sprig color instead with \"{ color: color`` }\"') const [, rgba ] = palette.find(([key]) => key === opts.color) ?? palette.find(([key]) => key === 'L')! gameState.texts.push({ x: opts.x ?? padLeft, y: opts.y ?? 0, color: rgba, content: str }) } const clearText = (): void => { gameState.texts = [] } const getTile = (x: number, y: number): SpriteType[] => { if (y < 0) return [] if (x < 0) return [] if (y >= gameState.dimensions.height) return [] if (x >= gameState.dimensions.width) return [] return getGrid()[gameState.dimensions.width*y+x] ?? [] } const _hasDuplicates = <T>(array: T[]): boolean => (new Set(array)).size !== array.length const tilesWith = (...matchingTypes: string[]): SpriteType[][] => { const { width, height } = gameState.dimensions const tiles: SpriteType[][] = [] const grid = getGrid() for (let x = 0; x < width; x++) { for (let y = 0; y < height; y++) { const tile = grid[width*y+x] || [] const matchIndices = matchingTypes.map(type => { return tile.map(s => s.type).indexOf(type) }) if (!_hasDuplicates(matchIndices) && !matchIndices.includes(-1)) tiles.push(tile) } } return tiles } const setSolids = (arr: string[]): void => { if (!Array.isArray(arr)) throw new Error('The sprites passed into setSolids() need to be an array.') gameState.solids = arr } const setPushables = (map: Record<string, string[]>): void => { for (const key in map) { if(key.length != 1) { throw new Error('Your sprite name must be wrapped in [] brackets here.'); } _checkLegend(key) } gameState.pushable = map } const api: BaseEngineAPI = { setMap, addText, clearText, addSprite, getGrid, getTile, tilesWith, clearTile, setSolids, setPushables, setBackground: (type: string) => { gameState.background = type }, map: _makeTag(text => text), bitmap: _makeTag(text => text), color: _makeTag(text => text), tune: _makeTag(text => text), getFirst: (type: string): SpriteType | undefined => gameState.sprites.find(t => t.type === type), // ** getAll: (type: string): SpriteType[] => type ? gameState.sprites.filter(t => t.type === type) : gameState.sprites, // ** width: () => gameState.dimensions.width, height: () => gameState.dimensions.height } return { api, state: gameState } }
src/base/index.ts
hackclub-sprig-engine-e5e3c0c
[ { "filename": "src/web/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.8112940788269043 }, { "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.8008659482002258 }, { "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.7492063045501709 }, { "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.7154818773269653 }, { "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.6837375164031982 } ]
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.835917592048645 }, { "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.8041716814041138 }, { "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.778130054473877 }, { "filename": "src/base/index.ts", "retrieved_chunk": "\t\t\taddSprite(x, y, type)\n\t\t}\n\t}\n\tconst clearTile = (x: number, y: number): void => {\n\t\tgameState.sprites = gameState.sprites.filter(s => s.x !== x || s.y !== y)\n\t}\n\tconst addText = (str: string, opts: AddTextOptions = {}): void => {\n\t\tconst CHARS_MAX_X = 21\n\t\tconst padLeft = Math.floor((CHARS_MAX_X - str.length)/2)\n\t\tif (Array.isArray(opts.color)) throw new Error('addText no longer takes an RGBA color. Please use a Sprig color instead with \\\"{ color: color`` }\\\"')", "score": 0.774838924407959 }, { "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.7737842798233032 } ]
typescript
PlayTuneRes[] = [] return {
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\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.733216404914856 }, { "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.6926430463790894 }, { "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.6843402981758118 }, { "filename": "src/web/index.ts", "retrieved_chunk": "\t}\n\tconst afterInputs: (() => void)[] = []\n\tconst keydown = (e: KeyboardEvent) => {\n\t\tconst key = e.key\n\t\tif (!VALID_INPUTS.includes(key as any)) return\n\t\tfor (const validKey of VALID_INPUTS)\n\t\t\tif (key === validKey) tileInputs[key].forEach(fn => fn())\n\t\tafterInputs.forEach(f => f())\n\t\tstate.sprites.forEach((s: any) => {\n\t\t\ts.dx = 0", "score": 0.671451210975647 }, { "filename": "src/web/index.ts", "retrieved_chunk": "\t\t\ts.dy = 0\n\t\t})\n\t\te.preventDefault()\n\t}\n\tcanvas.addEventListener('keydown', keydown)\n\tconst onInput = (key: InputKey, fn: () => void): void => {\n\t\tif (!VALID_INPUTS.includes(key))\n\t\t\tthrow new Error(`Unknown input key, \"${key}\": expected one of ${VALID_INPUTS.join(', ')}`)\n\t\ttileInputs[key].push(fn)\n\t}", "score": 0.6328635811805725 } ]
typescript
.sprites = gameState.sprites.filter(s => s !== this) return this }
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/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.7619808316230774 }, { "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.7564685940742493 }, { "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.7401824593544006 }, { "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.730513334274292 }, { "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.7246249914169312 } ]
typescript
: 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/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.8262286186218262 }, { "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.8056212663650513 }, { "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.75791335105896 }, { "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.7204458713531494 }, { "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.6999884843826294 } ]
typescript
: { api: BaseEngineAPI, state: GameState } {
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/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.7630581259727478 }, { "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.7446078062057495 }, { "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.7391411066055298 }, { "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.7374569177627563 }, { "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.7309304475784302 } ]
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/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.7772555351257324 }, { "filename": "src/web/index.ts", "retrieved_chunk": "\t}\n\tlet tileInputs: Record<InputKey, (() => void)[]> = {\n\t\tw: [],\n\t\ts: [],\n\t\ta: [],\n\t\td: [],\n\t\ti: [],\n\t\tj: [],\n\t\tk: [],\n\t\tl: []", "score": 0.7186629176139832 }, { "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.6706323623657227 }, { "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.6690880060195923 }, { "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.6630538105964661 } ]
typescript
class Sprite implements SpriteType {
/* song form [ [duration, instrument, pitch, duration, ...], ] Syntax: 500: 64.4~500 + c5~1000 [500, 'sine', 64.4, 500, 'sine', 'c5', 1000] Comma between each tune element. Whitespace ignored. */ import { type Tune, instrumentKey, InstrumentType, reverseInstrumentKey } from '../api.js' export const textToTune = (text: string): Tune => { const elements = text.replace(/\s/g, '').split(',') const tune = [] for (const element of elements) { if (!element) continue const [durationRaw, notesRaw] = element.split(':') const duration = Math.round(parseInt(durationRaw ?? '0', 10)) const notes = (notesRaw || '').split('+').map((noteRaw) => { if (!noteRaw) return [] const [, pitchRaw, instrumentRaw, durationRaw] = noteRaw.match(/^(.+)([~\-^\/])(.+)$/)! return [ instrumentKey[instrumentRaw!] ?? 'sine', isNaN(parseInt(pitchRaw ?? '', 10)) ? pitchRaw! : parseInt(pitchRaw!, 10), parseInt(durationRaw ?? '0', 10) ] }) tune.push([duration, ...notes].flat()) } return tune as Tune } export const tuneToText = (tune: Tune): string => { const groupNotes = (notes: (number | string)[]) => { const groups = [] for (let i = 0; i < notes.length; i++) { if (i % 3 === 0) { groups.push([notes[i]!]) } else { groups[groups.length-1]!.push(notes[i]!) } } return groups } const notesToString = ([duration, ...notes]: Tune[number]) => ( notes.length === 0 ? duration : `${duration}: ${groupNotes(notes).map(notesToStringHelper).join(' + ')}` ) const notesToStringHelper = ([instrument, duration, note]: (number | string)[]) => ( `${duration}${
reverseInstrumentKey[instrument as InstrumentType]}${note}` ) return tune.map(notesToString).join(',\n') }
src/base/tune.ts
hackclub-sprig-engine-e5e3c0c
[ { "filename": "src/web/tune.ts", "retrieved_chunk": "\t\t\tconst duration = noteSet[j+2] as number\n\t\t\tconst frequency = typeof note === 'string' \n\t\t\t\t? tones[note.toUpperCase()]\n\t\t\t\t: 2**((note-69)/12)*440\n\t\t\tif (instruments.includes(instrument) && frequency !== undefined) playFrequency(frequency, duration, instrument, ctx, dest)\n\t\t}\n\t\tawait sleep(sleepTime)\n\t}\n}\nlet audioCtx: AudioContext | null = null", "score": 0.7083336114883423 }, { "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.685784637928009 }, { "filename": "src/base/index.ts", "retrieved_chunk": "\t\t\tthrow new Error('Tagged template literal must be used like name`text`, instead of name(`text`)')\n\t\t}\n\t\tconst string = strings.reduce((p, c, i) => p + c + (interps[i] ?? ''), '')\n\t\treturn cb(string)\n\t}\n}\nexport type BaseEngineAPI = Pick<\n\tFullSprigAPI,\n\t| 'setMap'\n\t| 'addText'", "score": 0.6643118858337402 }, { "filename": "src/web/index.ts", "retrieved_chunk": "\t\t\ts.dy = 0\n\t\t})\n\t\te.preventDefault()\n\t}\n\tcanvas.addEventListener('keydown', keydown)\n\tconst onInput = (key: InputKey, fn: () => void): void => {\n\t\tif (!VALID_INPUTS.includes(key))\n\t\t\tthrow new Error(`Unknown input key, \"${key}\": expected one of ${VALID_INPUTS.join(', ')}`)\n\t\ttileInputs[key].push(fn)\n\t}", "score": 0.6599628925323486 }, { "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.651695966720581 } ]
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\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.8218299746513367 }, { "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.773446798324585 }, { "filename": "src/base/index.ts", "retrieved_chunk": "\t\t\taddSprite(x, y, type)\n\t\t}\n\t}\n\tconst clearTile = (x: number, y: number): void => {\n\t\tgameState.sprites = gameState.sprites.filter(s => s.x !== x || s.y !== y)\n\t}\n\tconst addText = (str: string, opts: AddTextOptions = {}): void => {\n\t\tconst CHARS_MAX_X = 21\n\t\tconst padLeft = Math.floor((CHARS_MAX_X - str.length)/2)\n\t\tif (Array.isArray(opts.color)) throw new Error('addText no longer takes an RGBA color. Please use a Sprig color instead with \\\"{ color: color`` }\\\"')", "score": 0.7561864852905273 }, { "filename": "src/base/index.ts", "retrieved_chunk": "\t\tif (!(type in Object.fromEntries(gameState.legend)))\n\t\t\tthrow new Error(`Unknown sprite type: ${type}`)\n\t}\n\tconst addSprite = (x: number, y: number, type: string): void => {\n\t\tif (type === '.') return\n\t\t_checkBounds(x, y)\n\t\t_checkLegend(type)\n\t\tconst s = new Sprite(type, x, y)\n\t\tgameState.sprites.push(s)\n\t}", "score": 0.7556898593902588 }, { "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.7456634640693665 } ]
typescript
throw new Error(`Unknown input key, "${key}": expected one of ${VALID_INPUTS.join(', ')}`) tileInputs[key].push(fn) }
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.7622531652450562 }, { "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.7059588432312012 }, { "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.7033560276031494 }, { "filename": "src/base/index.ts", "retrieved_chunk": "\t\tset y(newY) {\n\t\t\tconst dy = newY - this.y\n\t\t\tif (_canMoveToPush(this, 0, dy)) this.dy = dy\n\t\t}\n\t\tget y() {\n\t\t\treturn this._y\n\t\t}\n\t\tremove() {\n\t\t\tgameState.sprites = gameState.sprites.filter(s => s !== this)\n\t\t\treturn this", "score": 0.677932858467102 }, { "filename": "src/base/index.ts", "retrieved_chunk": "\t\t\tsprite._y += dy\n\t\t}\n\t\treturn canMove\n\t}\n\tconst getGrid = (): SpriteType[][] => {\n\t\tconst { width, height } = gameState.dimensions\n\t\tconst grid: SpriteType[][] = new Array(width*height).fill(0).map(_ => [])\n\t\tgameState.sprites.forEach(s => {\n\t\t\tconst i = s.x+s.y*width\n\t\t\tgrid[i]!.push(s)", "score": 0.6725159287452698 } ]
typescript
tunes.forEach(tune => tune.end()) }
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.783167839050293 }, { "filename": "src/web/index.ts", "retrieved_chunk": "\t\t)\n\t\tanimationId = window.requestAnimationFrame(_gameloop)\n\t}\n\tlet animationId = window.requestAnimationFrame(_gameloop)\n\tconst setLegend = (...bitmaps: [string, string][]): void => {\n\t\tif (bitmaps.length == 0) throw new Error('There needs to be at least one sprite in the legend.')\n\t\tif (!Array.isArray(bitmaps[0])) throw new Error('The sprites passed into setLegend each need to be in square brackets, like setLegend([player, bitmap`...`]).')\n\t\tbitmaps.forEach(([ key ]) => {\n\t\t\tif (key === '.') throw new Error(`Can't reassign \".\" bitmap`)\n\t\t\tif (key.length !== 1) throw new Error(`Bitmaps must have one character names`)", "score": 0.745835542678833 }, { "filename": "src/base/text.ts", "retrieved_chunk": "import type { Rgba, TextElement } from '../api.js'\nexport function composeText(texts: TextElement[]): { char: string, color: Rgba }[][] {\n\tconst emptyCell = () => ({ char: ' ', color: [0, 0, 0, 0] as Rgba })\n\tconst range = <T>(length: number, fn: () => T): T[] => Array.from({ length }, fn)\n\tconst gridFromSize = (w: number, h: number) => range(h, () => range(w, emptyCell))\n\tconst CHARS_MAX_X = 20\n\tconst CHARS_MAX_Y = 16\n\tconst grid = gridFromSize(CHARS_MAX_X, CHARS_MAX_Y)\n\tfor (const { x: sx, y: sy, content, color } of texts) {\n\t\tlet y = sy", "score": 0.7283654808998108 }, { "filename": "src/base/palette.ts", "retrieved_chunk": "\tconst [ r, g, b, a ] = hex.match(/\\w\\w/g)?.map((x) => parseInt(x, 16)) ?? []\n\treturn [ r!, g!, b!, a ?? 255 ]\n}\nexport const rgbaToHex = (rgba: Rgba): string => {\n\treturn '#' + rgba.map(n => n.toString(16).padStart(2, '0')).join('')\n}", "score": 0.7234114408493042 }, { "filename": "src/web/index.ts", "retrieved_chunk": "\t\t\ts.dy = 0\n\t\t})\n\t\te.preventDefault()\n\t}\n\tcanvas.addEventListener('keydown', keydown)\n\tconst onInput = (key: InputKey, fn: () => void): void => {\n\t\tif (!VALID_INPUTS.includes(key))\n\t\t\tthrow new Error(`Unknown input key, \"${key}\": expected one of ${VALID_INPUTS.join(', ')}`)\n\t\ttileInputs[key].push(fn)\n\t}", "score": 0.6997064352035522 } ]
typescript
opts.y ?? 0, color: rgba, content: str }) }
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/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.7614820003509521 }, { "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.7540906667709351 }, { "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.736725389957428 }, { "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.7319799661636353 }, { "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.721563994884491 } ]
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/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.7153701782226562 }, { "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.6875332593917847 }, { "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.6801937818527222 }, { "filename": "src/web/index.ts", "retrieved_chunk": "\t}\n\tconst afterInputs: (() => void)[] = []\n\tconst keydown = (e: KeyboardEvent) => {\n\t\tconst key = e.key\n\t\tif (!VALID_INPUTS.includes(key as any)) return\n\t\tfor (const validKey of VALID_INPUTS)\n\t\t\tif (key === validKey) tileInputs[key].forEach(fn => fn())\n\t\tafterInputs.forEach(f => f())\n\t\tstate.sprites.forEach((s: any) => {\n\t\t\ts.dx = 0", "score": 0.6611583232879639 }, { "filename": "src/web/index.ts", "retrieved_chunk": "\t\t\ts.dy = 0\n\t\t})\n\t\te.preventDefault()\n\t}\n\tcanvas.addEventListener('keydown', keydown)\n\tconst onInput = (key: InputKey, fn: () => void): void => {\n\t\tif (!VALID_INPUTS.includes(key))\n\t\t\tthrow new Error(`Unknown input key, \"${key}\": expected one of ${VALID_INPUTS.join(', ')}`)\n\t\ttileInputs[key].push(fn)\n\t}", "score": 0.6221293210983276 } ]
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\tsprite._y += dy\n\t\t}\n\t\treturn canMove\n\t}\n\tconst getGrid = (): SpriteType[][] => {\n\t\tconst { width, height } = gameState.dimensions\n\t\tconst grid: SpriteType[][] = new Array(width*height).fill(0).map(_ => [])\n\t\tgameState.sprites.forEach(s => {\n\t\t\tconst i = s.x+s.y*width\n\t\t\tgrid[i]!.push(s)", "score": 0.8036462664604187 }, { "filename": "src/base/index.ts", "retrieved_chunk": "\t\t}\n\t}\n\tconst _canMoveToPush = (sprite: Sprite, dx: number, dy: number): boolean => {\n\t\tconst { x, y, type } = sprite\n\t\tconst { width, height } = gameState.dimensions\n\t\tconst i = (x+dx)+(y+dy)*width\n\t\tconst inBounds = (x+dx < width && x+dx >= 0 && y+dy < height && y+dy >= 0)\n\t\tif (!inBounds) return false\n\t\tconst grid = getGrid()\n\t\tconst notSolid = !gameState.solids.includes(type)", "score": 0.7210060358047485 }, { "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.7196314334869385 }, { "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.7018188834190369 }, { "filename": "src/base/index.ts", "retrieved_chunk": "\t\t\tthis._y = y\n\t\t\tthis.dx = 0\n\t\t\tthis.dy = 0\n\t\t}\n\t\tset type(newType) {\n\t\t\tconst legendDict = Object.fromEntries(gameState.legend)\n\t\t\tif (!(newType in legendDict)) throw new Error(`\"${newType}\" isn\\'t in the legend.`)\n\t\t\tthis.remove()\n\t\t\taddSprite(this._x, this._y, newType)\n\t\t}", "score": 0.7016994953155518 } ]
typescript
((sprite) => {
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/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.862372636795044 }, { "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.8493262529373169 }, { "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.8281325101852417 }, { "filename": "src/prompts/regex.ts", "retrieved_chunk": "import { PromptConfiguration } from \"../types.js\";\nconst promptConfiguration: PromptConfiguration = {\n description:\n \"Gives a JavaScript compatible RegEx that matches the input examples.\",\n createPrompt(input: string) {\n return `Output a JavaScript regex that matches the following examples: ${input}.\\n###\\n`;\n },\n};\nexport default promptConfiguration;", "score": 0.79735267162323 }, { "filename": "src/prompts/convert-to-typescript.ts", "retrieved_chunk": "import { PromptConfiguration } from \"../types.js\";\nconst promptConfiguration: PromptConfiguration = {\n description: \"Converts source file to TypeScript\",\n createPrompt(input: string) {\n return `Rewrite this file in TypeScript. Only output valid code, no comments. ${input}\\n\\n`;\n },\n};\nexport default promptConfiguration;", "score": 0.7907930612564087 } ]
typescript
ParsedResponse> {
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.8401228785514832 }, { "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.82253098487854 }, { "filename": "src/executePrompt.ts", "retrieved_chunk": "import { asyncIterableToArray } from \"./utils.js\";\nfunction defaultParseResponse(content: string, _input: string): ParsedResponse {\n return { message: content };\n}\nfunction toModel(promptConfig: PromptConfiguration): Model {\n const model = promptConfig.model\n ? models.get(promptConfig.model)\n : defaultModel;\n if (!model) {\n throw new AppError({", "score": 0.8206538558006287 }, { "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.817160964012146 }, { "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.8058937191963196 } ]
typescript
? new FileSystemKVS({ baseDir: config.paths.cache }) : undefined;
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": "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.781076192855835 }, { "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.7713579535484314 }, { "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.7444607615470886 }, { "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.7282117605209351 }, { "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.6770462989807129 } ]
typescript
(instruments.includes(instrument) && frequency !== undefined) playFrequency(frequency, duration, instrument, ctx, dest) }
import { executePrompt, executePromptStream } from "./executePrompt.js"; import { loadConfig } from "./config.js"; import { loadPromptConfig, listPrompts } from "./loadPromptConfig.js"; import { APPNAME } from "./types.js"; import FileSystemKVS from "./kvs/kvs-filesystem.js"; import { AppError } from "./errors.js"; import { readFileSync } from "node:fs"; function parseArgs(argv: string[]) { const [_nodeBin, _jsFile, promptId, ...rest] = argv; const input = rest.join(" "); return { promptId, input }; } function printUsageAndExit() { console.log("Usage:"); console.log(`$ ${APPNAME} <promptType> <input>`); console.log(`$ ${APPNAME} --list`); console.log(""); console.log("Example: "); console.log(""); console.log(`$ ${APPNAME} eli5 "what are large language models?"`); process.exit(1); } function getInput(argvInput: string) { try { const stdinInput = readFileSync(process.stdin.fd, "utf-8"); // console.log({ stdinInput }); return `${argvInput} ${stdinInput}`; } catch (err) { return argvInput; } } export async function cli() { try { const config = loadConfig(); const { promptId, input: argvInput } = parseArgs(process.argv); if (promptId === "--list") { const prompts = await listPrompts(config); console.log( prompts .map((
p) => {
const description = p.description ? `: ${p.description}` : ""; return `${p.name}${description}`; }) .join("\n") ); return; } else if (promptId && promptId.startsWith("--")) { printUsageAndExit(); } const input = getInput(argvInput); if (!promptId || !input) { printUsageAndExit(); } const promptConfig = await loadPromptConfig(promptId, config); const cache = config.useCache ? new FileSystemKVS({ baseDir: config.paths.cache }) : undefined; const stream = executePromptStream(promptConfig, input, config, cache); for await (const chunk of stream) { process.stdout.write(chunk); } process.stdout.write("\n"); } catch (err) { if (err instanceof AppError) { console.error(err.toString()); process.exit(err.exitCode); } console.error(err); process.exit(1); } } export default cli;
src/index.ts
clevercli-clevercli-c660fae
[ { "filename": "src/loadPromptConfig.ts", "retrieved_chunk": " ]);\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.8514794707298279 }, { "filename": "src/executePrompt.ts", "retrieved_chunk": "import { asyncIterableToArray } from \"./utils.js\";\nfunction defaultParseResponse(content: string, _input: string): ParsedResponse {\n return { message: content };\n}\nfunction toModel(promptConfig: PromptConfiguration): Model {\n const model = promptConfig.model\n ? models.get(promptConfig.model)\n : defaultModel;\n if (!model) {\n throw new AppError({", "score": 0.8182673454284668 }, { "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.7999531626701355 }, { "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.7996333837509155 }, { "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.7964070439338684 } ]
typescript
p) => {
/* song form [ [duration, instrument, pitch, duration, ...], ] Syntax: 500: 64.4~500 + c5~1000 [500, 'sine', 64.4, 500, 'sine', 'c5', 1000] Comma between each tune element. Whitespace ignored. */ import { type Tune, instrumentKey, InstrumentType, reverseInstrumentKey } from '../api.js' export const textToTune = (text: string): Tune => { const elements = text.replace(/\s/g, '').split(',') const tune = [] for (const element of elements) { if (!element) continue const [durationRaw, notesRaw] = element.split(':') const duration = Math.round(parseInt(durationRaw ?? '0', 10)) const notes = (notesRaw || '').split('+').map((noteRaw) => { if (!noteRaw) return [] const [, pitchRaw, instrumentRaw, durationRaw] = noteRaw.match(/^(.+)([~\-^\/])(.+)$/)! return [ instrumentKey[instrumentRaw!] ?? 'sine', isNaN(parseInt(pitchRaw ?? '', 10)) ? pitchRaw! : parseInt(pitchRaw!, 10), parseInt(durationRaw ?? '0', 10) ] }) tune.push([duration, ...notes].flat()) } return tune as Tune } export const tuneToText = (tune: Tune): string => { const groupNotes = (notes: (number | string)[]) => { const groups = [] for (let i = 0; i < notes.length; i++) { if (i % 3 === 0) { groups.push([notes[i]!]) } else { groups[groups.length-1]!.push(notes[i]!) } } return groups } const notesToString = ([duration, ...notes]: Tune[number]) => ( notes.length === 0 ? duration : `${duration}: ${groupNotes(notes).map(notesToStringHelper).join(' + ')}` ) const notesToStringHelper = ([instrument, duration, note]: (number | string)[]) => ( `${duration}${reverseInstrumentKey[instrument as InstrumentType]}${note}` ) return tune.
map(notesToString).join(',\n') }
src/base/tune.ts
hackclub-sprig-engine-e5e3c0c
[ { "filename": "src/web/tune.ts", "retrieved_chunk": "\t\t\tconst duration = noteSet[j+2] as number\n\t\t\tconst frequency = typeof note === 'string' \n\t\t\t\t? tones[note.toUpperCase()]\n\t\t\t\t: 2**((note-69)/12)*440\n\t\t\tif (instruments.includes(instrument) && frequency !== undefined) playFrequency(frequency, duration, instrument, ctx, dest)\n\t\t}\n\t\tawait sleep(sleepTime)\n\t}\n}\nlet audioCtx: AudioContext | null = null", "score": 0.7045753002166748 }, { "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.6830278038978577 }, { "filename": "src/base/index.ts", "retrieved_chunk": "\t\t\tthrow new Error('Tagged template literal must be used like name`text`, instead of name(`text`)')\n\t\t}\n\t\tconst string = strings.reduce((p, c, i) => p + c + (interps[i] ?? ''), '')\n\t\treturn cb(string)\n\t}\n}\nexport type BaseEngineAPI = Pick<\n\tFullSprigAPI,\n\t| 'setMap'\n\t| 'addText'", "score": 0.6637309193611145 }, { "filename": "src/web/index.ts", "retrieved_chunk": "\t\t\ts.dy = 0\n\t\t})\n\t\te.preventDefault()\n\t}\n\tcanvas.addEventListener('keydown', keydown)\n\tconst onInput = (key: InputKey, fn: () => void): void => {\n\t\tif (!VALID_INPUTS.includes(key))\n\t\t\tthrow new Error(`Unknown input key, \"${key}\": expected one of ${VALID_INPUTS.join(', ')}`)\n\t\ttileInputs[key].push(fn)\n\t}", "score": 0.6631145477294922 }, { "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.647737443447113 } ]
typescript
map(notesToString).join(',\n') }
import { executePrompt, executePromptStream } from "./executePrompt.js"; import { loadConfig } from "./config.js"; import { loadPromptConfig, listPrompts } from "./loadPromptConfig.js"; import { APPNAME } from "./types.js"; import FileSystemKVS from "./kvs/kvs-filesystem.js"; import { AppError } from "./errors.js"; import { readFileSync } from "node:fs"; function parseArgs(argv: string[]) { const [_nodeBin, _jsFile, promptId, ...rest] = argv; const input = rest.join(" "); return { promptId, input }; } function printUsageAndExit() { console.log("Usage:"); console.log(`$ ${APPNAME} <promptType> <input>`); console.log(`$ ${APPNAME} --list`); console.log(""); console.log("Example: "); console.log(""); console.log(`$ ${APPNAME} eli5 "what are large language models?"`); process.exit(1); } function getInput(argvInput: string) { try { const stdinInput = readFileSync(process.stdin.fd, "utf-8"); // console.log({ stdinInput }); return `${argvInput} ${stdinInput}`; } catch (err) { return argvInput; } } export async function cli() { try { const config = loadConfig(); const { promptId, input: argvInput } = parseArgs(process.argv); if (promptId === "--list") { const prompts = await listPrompts(config); console.log( prompts .map((p) => { const description = p.description ? `: ${p.description}` : ""; return `${p.name}${description}`; }) .join("\n") ); return; } else if (promptId && promptId.startsWith("--")) { printUsageAndExit(); } const input = getInput(argvInput); if (!promptId || !input) { printUsageAndExit(); } const promptConfig = await loadPromptConfig(promptId, config); const cache = config.useCache ? new FileSystemKVS({ baseDir: config.paths.cache }) : undefined; const stream = executePromptStream(promptConfig, input, config, cache); for await (const chunk of stream) { process.stdout.write(chunk); } process.stdout.write("\n"); } catch (err) { if (err instanceof AppError) { console
.error(err.toString());
process.exit(err.exitCode); } console.error(err); process.exit(1); } } export default cli;
src/index.ts
clevercli-clevercli-c660fae
[ { "filename": "src/executePrompt.ts", "retrieved_chunk": " }\n const stream = openAIQuery(model, formattedPrompt, config);\n const chunks = [];\n for await (const chunk of stream) {\n chunks.push(chunk);\n yield chunk;\n }\n if (cache) {\n const response = chunks.join(\"\");\n await cache.set(cacheKey, response);", "score": 0.8248618841171265 }, { "filename": "src/openai.ts", "retrieved_chunk": " }\n }\n throw err;\n }\n })();\n /* @ts-ignore */\n const stream = res.data as IncomingMessage;\n for await (const chunk of chunksToLines(stream)) {\n const data = JSON.parse(chunk);\n const content = data.choices[0].delta.content;", "score": 0.7976504564285278 }, { "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.7819567322731018 }, { "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.7789872884750366 }, { "filename": "src/openai.ts", "retrieved_chunk": " let previous = \"\";\n for await (const chunk of chunksAsync) {\n const bufferChunk = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n previous += bufferChunk;\n let eolIndex;\n while ((eolIndex = previous.indexOf(\"\\n\")) >= 0) {\n // line includes the EOL\n const line = previous.slice(0, eolIndex + 1).trimEnd();\n if (line === \"data: [DONE]\") break;\n if (line.startsWith(\"data: \")) {", "score": 0.7781214714050293 } ]
typescript
.error(err.toString());
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.8472975492477417 }, { "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.84030681848526 }, { "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.8248865008354187 }, { "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.8050633668899536 }, { "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.8017997741699219 } ]
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.8052016496658325 }, { "filename": "src/executePrompt.ts", "retrieved_chunk": "import { asyncIterableToArray } from \"./utils.js\";\nfunction defaultParseResponse(content: string, _input: string): ParsedResponse {\n return { message: content };\n}\nfunction toModel(promptConfig: PromptConfiguration): Model {\n const model = promptConfig.model\n ? models.get(promptConfig.model)\n : defaultModel;\n if (!model) {\n throw new AppError({", "score": 0.7825797200202942 }, { "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.7823609113693237 }, { "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.7737318277359009 }, { "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.7608826160430908 } ]
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.8594706058502197 }, { "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.8476506471633911 }, { "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.8279778361320496 }, { "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.8122504949569702 }, { "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.8120361566543579 } ]
typescript
await asyncIterableToArray( executePromptStream(promptConfig, input, config, cache) ) ).join("");
import { ext, generateMessageId, handleCrxRpcRequest, wait } from '../lib/messaging'; import { getJoyconDevice, getNextStrain, getStrain, setupJoycon } from '../lib/ring-con'; injectResourceScript('js/nip07-provider.js'); // 'nip07-provider' -> ... window.addEventListener('message', async ({ data }: MessageEvent<CrxRpcRequestMessage>) => { const { next, shouldBeHandled } = handleCrxRpcRequest(data, 'content'); if (!shouldBeHandled) { return; } if (next === 'background') { // ... -> HERE -> 'background' const response: CrxRpcResponseMessage = await chrome.runtime.sendMessage(data); window.postMessage(response); return; } else if (!!next) { console.warn('Unexpected message', data); return; } //... -> HERE switch (data.payload.kind) { case 'enterChargeMode': { try { const response = await enterChargeMode(data); window.postMessage(response); } catch (err) { console.error(err); window.postMessage({ ext, messageId: data.messageId, payload: { kind: 'enterChargeMode', response: false, }, }); throw err; } } break; default: break; } }); async function enterChargeMode({ messageId, payload, }: CrxRpcRequestMessage): Promise<CrxRpcResponseMessage> { if (payload.kind !== 'enterChargeMode') { throw 'Unexpected message'; } const openChargeWindowReq: CrxRpcMessage = { ext, messageId: generateMessageId(), src: 'content', path: ['background'], payload: { kind: 'openChargeWindow', request: {}, }, }; const { payload: result }: CrxRpcResponseMessage = await chrome.runtime.sendMessage( openChargeWindowReq, ); if (result.kind !== 'openChargeWindow') { throw 'Unexpected message'; } // Keep sending strain signals.
const joycon = await getJoyconDevice();
await setupJoycon(joycon); const neutral = await getNextStrain(joycon); const sendStrain = (value: number) => { const req: CrxRpcMessage = { ext, messageId: generateMessageId(), src: 'content', path: ['charge'], payload: { kind: 'sendStrain', request: { value, neutral, }, }, }; chrome.runtime.sendMessage(req); }; const reportListener = (ev: HIDInputReportEvent) => { const value = getStrain(ev); if (value) { sendStrain(value); } }; joycon.addEventListener('inputreport', reportListener); // Wait for `leaveChargeMode` signal. await wait<CrxRpcRequestMessage, void>( (resolve) => (msg) => { const { next, shouldBeHandled } = handleCrxRpcRequest(msg, 'content'); if (!shouldBeHandled) { return; } if (!!next) { console.warn('Unexpected message', msg); return; } if (msg.payload.kind === 'leaveChargeMode') { resolve(); } }, { addEventListener: (listener) => { chrome.runtime.onMessage.addListener(listener); }, removeEventListener: (listener) => { chrome.runtime.onMessage.removeListener(listener); }, }, ); // Stop sending strain signals. joycon.removeEventListener('inputreport', reportListener); return { ext, messageId, payload: { kind: 'enterChargeMode', response: true, }, }; } function injectResourceScript(path: string) { const script = document.createElement('script'); script.setAttribute('async', 'false'); script.setAttribute('type', 'text/javascript'); script.setAttribute('src', chrome.runtime.getURL(path)); document.head.appendChild(script); }
src/content/index.ts
penpenpng-nostronger-851a990
[ { "filename": "src/background/index.ts", "retrieved_chunk": " if (next === 'content' && payload.kind === 'leaveChargeMode') {\n chrome.tabs.sendMessage(payload.request.senderTabId, msg);\n return;\n } else if (!!next) {\n console.warn('Unexpected message', msg);\n return;\n }\n const sendResponse = (val: any) => {\n const res: CrxRpcResponseMessage = {\n ...msg,", "score": 0.8736701011657715 }, { "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.8121052980422974 }, { "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.7970966100692749 }, { "filename": "src/lib/ring-con.ts", "retrieved_chunk": "import { wait } from './messaging';\nexport async function getJoyconDevice() {\n const [device] = await navigator.hid.requestDevice({\n filters: [\n {\n vendorId: 0x057e, // Nintendo vendor ID\n productId: 0x2007, // joy-con R\n },\n ],\n });", "score": 0.7897789478302002 }, { "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.7862182855606079 } ]
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/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.8228874206542969 }, { "filename": "src/content/index.ts", "retrieved_chunk": " if (!!next) {\n console.warn('Unexpected message', msg);\n return;\n }\n if (msg.payload.kind === 'leaveChargeMode') {\n resolve();\n }\n },\n {\n addEventListener: (listener) => {", "score": 0.8222024440765381 }, { "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.8078168630599976 }, { "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.8064178228378296 }, { "filename": "src/resource/nip07-provider.ts", "retrieved_chunk": "// Note that web accessible scripts cannot import or export because they must be compiled into a single file by tsc.\n(window as any).nostr = {\n async getPublicKey(): Promise<string> {\n return rpc(\n {\n kind: 'getPubkey',\n request: {},\n },\n ['content', 'background'],\n );", "score": 0.8051106333732605 } ]
typescript
getKeyPair().then(async (keypair) => {
import { Config } from "./types.js"; import { join as pathJoin } from "node:path"; import { AppError } from "./errors.js"; import { fileURLToPath } from "node:url"; import { dirname, parse } from "node:path"; import { readdir } from "node:fs/promises"; async function readFilesInDirectory(path: string) { try { const files = await readdir(path); return files .filter((f) => f.endsWith(".js") || f.endsWith(".mjs")) .map((filename) => pathJoin(path, filename)); } catch (err) { if (err instanceof Error && "code" in err) { if (err.code == "ENOENT") { // ignore error: ENOENT: no such file or directory return []; } } throw err; } } // Returns a path relative to import.meta.filename export function sourceRelativePath( meta: { url: string }, ...relPaths: string[] ) { const __dirname = dirname(fileURLToPath(meta.url)); return pathJoin(__dirname, ...relPaths); } export async function loadFromPath(path: string) { const promptConfig = await import(path); // TODO: validate promptConfig? return promptConfig.default; } export async function loadPromptConfig(promptId
: string, config: Config) {
try { const promptConfig = await Promise.any([ loadFromPath(sourceRelativePath(import.meta, `./prompts/${promptId}.js`)), loadFromPath(pathJoin(config.paths.data, `${promptId}.mjs`)), ]); return promptConfig; } catch (err) { throw new AppError({ message: `Could not find prompt ${promptId}. Are you sure it is a builtin prompt or that ${config.paths.data}/${promptId}.mjs exists?`, }); } } export async function listPrompts(config: Config) { const [localFiles, builtinFiles] = await Promise.all( [ sourceRelativePath(import.meta, `./prompts`), pathJoin(config.paths.data), ].map(readFilesInDirectory) ); const allFiles = [...localFiles, ...builtinFiles]; const allPromptConfigs = await Promise.all(allFiles.map(loadFromPath)); return allPromptConfigs.map((config, i) => { const name = parse(allFiles[i]).name; return { name, description: config.description, }; }); }
src/loadPromptConfig.ts
clevercli-clevercli-c660fae
[ { "filename": "src/executePrompt.ts", "retrieved_chunk": "import { asyncIterableToArray } from \"./utils.js\";\nfunction defaultParseResponse(content: string, _input: string): ParsedResponse {\n return { message: content };\n}\nfunction toModel(promptConfig: PromptConfiguration): Model {\n const model = promptConfig.model\n ? models.get(promptConfig.model)\n : defaultModel;\n if (!model) {\n throw new AppError({", "score": 0.8398698568344116 }, { "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.83722984790802 }, { "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.8104877471923828 }, { "filename": "src/kvs/kvs-filesystem.ts", "retrieved_chunk": " const baseDir = this.baseDir;\n const filePath = pathJoin(baseDir, this._keyToFilename(key));\n // console.log({ filePath });\n return filePath;\n }\n async set(key: K, value: V) {\n await this.waitInit;\n await writeFile(this._keyToFilePath(key), `${value}`);\n }\n async get(key: K): Promise<string | undefined> {", "score": 0.8079468011856079 }, { "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.8009867668151855 } ]
typescript
: string, config: Config) {
import { handleCrxRpcRequest } from '../lib/messaging'; import { signEvent } from '../lib/nostr'; import { getKeyPair, getSignPower, setSignPower } from '../lib/store'; // * -> ... chrome.runtime.onMessage.addListener((msg: CrxRpcRequestMessage, sender, _sendResponse) => { const { next, shouldBeHandled } = handleCrxRpcRequest(msg, 'background'); if (!shouldBeHandled) { return; } const payload = msg.payload; if (next === 'content' && payload.kind === 'leaveChargeMode') { chrome.tabs.sendMessage(payload.request.senderTabId, msg); return; } else if (!!next) { console.warn('Unexpected message', msg); return; } const sendResponse = (val: any) => { const res: CrxRpcResponseMessage = { ...msg, payload: { kind: payload.kind, response: val, }, }; _sendResponse(res); }; // ... -> HERE switch (payload.kind) { case 'getPubkey': getKeyPair().then(({ pubkey }) => { sendResponse(pubkey); }); return true; // For async response case 'signEvent': getKeyPair().then(async (keypair) => { const signed = await
signEvent(keypair, payload.request);
sendResponse(signed); }); return true; case 'getSignPower': getSignPower().then((power) => { sendResponse(power); }); return true; case 'setSignPower': setSignPower(payload.request.value).then(() => { sendResponse(void 0); }); return true; case 'openChargeWindow': chrome.windows .create({ url: chrome.runtime.getURL('charge.html'), type: 'popup', }) .then((res) => { const tabId = res.tabs?.[0].id; sendResponse(tabId); }); return true; default: break; } });
src/background/index.ts
penpenpng-nostronger-851a990
[ { "filename": "src/resource/nip07-provider.ts", "retrieved_chunk": " },\n async signEvent(event: UnsignedEvent): Promise<SignedEvent | undefined> {\n let signPower = await rpc(\n {\n kind: 'getSignPower',\n request: {},\n },\n ['content', 'background'],\n );\n if (signPower <= 0) {", "score": 0.8217010498046875 }, { "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.8081121444702148 }, { "filename": "src/content/index.ts", "retrieved_chunk": " if (!!next) {\n console.warn('Unexpected message', msg);\n return;\n }\n if (msg.payload.kind === 'leaveChargeMode') {\n resolve();\n }\n },\n {\n addEventListener: (listener) => {", "score": 0.8076687455177307 }, { "filename": "src/content/index.ts", "retrieved_chunk": " }\n };\n joycon.addEventListener('inputreport', reportListener);\n // Wait for `leaveChargeMode` signal.\n await wait<CrxRpcRequestMessage, void>(\n (resolve) => (msg) => {\n const { next, shouldBeHandled } = handleCrxRpcRequest(msg, 'content');\n if (!shouldBeHandled) {\n return;\n }", "score": 0.791188657283783 }, { "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.7882480621337891 } ]
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/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.8310664892196655 }, { "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.825696587562561 }, { "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.8255533576011658 }, { "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.8135637044906616 }, { "filename": "src/executePrompt.ts", "retrieved_chunk": "import { asyncIterableToArray } from \"./utils.js\";\nfunction defaultParseResponse(content: string, _input: string): ParsedResponse {\n return { message: content };\n}\nfunction toModel(promptConfig: PromptConfiguration): Model {\n const model = promptConfig.model\n ? models.get(promptConfig.model)\n : defaultModel;\n if (!model) {\n throw new AppError({", "score": 0.8096628189086914 } ]
typescript
const stream = executePromptStream(promptConfig, input, config, cache);
import { executePrompt, executePromptStream } from "./executePrompt.js"; import { loadConfig } from "./config.js"; import { loadPromptConfig, listPrompts } from "./loadPromptConfig.js"; import { APPNAME } from "./types.js"; import FileSystemKVS from "./kvs/kvs-filesystem.js"; import { AppError } from "./errors.js"; import { readFileSync } from "node:fs"; function parseArgs(argv: string[]) { const [_nodeBin, _jsFile, promptId, ...rest] = argv; const input = rest.join(" "); return { promptId, input }; } function printUsageAndExit() { console.log("Usage:"); console.log(`$ ${APPNAME} <promptType> <input>`); console.log(`$ ${APPNAME} --list`); console.log(""); console.log("Example: "); console.log(""); console.log(`$ ${APPNAME} eli5 "what are large language models?"`); process.exit(1); } function getInput(argvInput: string) { try { const stdinInput = readFileSync(process.stdin.fd, "utf-8"); // console.log({ stdinInput }); return `${argvInput} ${stdinInput}`; } catch (err) { return argvInput; } } export async function cli() { try { const config = loadConfig(); const { promptId, input: argvInput } = parseArgs(process.argv); if (promptId === "--list") { const prompts = await listPrompts(config); console.log( prompts .map((p) => { const description = p.description ? `: ${p.description}` : ""; return `${p.name}${description}`; }) .join("\n") ); return; } else if (promptId && promptId.startsWith("--")) { printUsageAndExit(); } const input = getInput(argvInput); if (!promptId || !input) { printUsageAndExit(); } const promptConfig = await loadPromptConfig(promptId, config); const cache = config.useCache ? new FileSystemKVS({ baseDir: config.paths.cache }) : undefined; const stream = executePromptStream(promptConfig, input, config, cache); for await (const chunk of stream) { process.stdout.write(chunk); } process.stdout.write("\n"); } catch (err) { if (err instanceof AppError) {
console.error(err.toString());
process.exit(err.exitCode); } console.error(err); process.exit(1); } } export default cli;
src/index.ts
clevercli-clevercli-c660fae
[ { "filename": "src/executePrompt.ts", "retrieved_chunk": " }\n const stream = openAIQuery(model, formattedPrompt, config);\n const chunks = [];\n for await (const chunk of stream) {\n chunks.push(chunk);\n yield chunk;\n }\n if (cache) {\n const response = chunks.join(\"\");\n await cache.set(cacheKey, response);", "score": 0.8176144361495972 }, { "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.7990301847457886 }, { "filename": "src/openai.ts", "retrieved_chunk": " }\n }\n throw err;\n }\n })();\n /* @ts-ignore */\n const stream = res.data as IncomingMessage;\n for await (const chunk of chunksToLines(stream)) {\n const data = JSON.parse(chunk);\n const content = data.choices[0].delta.content;", "score": 0.7960329055786133 }, { "filename": "src/kvs/kvs-filesystem.ts", "retrieved_chunk": " await this.waitInit;\n const filePath = this._keyToFilePath(key);\n try {\n const val = await readFile(filePath, \"utf8\");\n return val;\n } catch (err) {\n return;\n }\n }\n async delete(key: K) {", "score": 0.7937610149383545 }, { "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.7896768450737 } ]
typescript
console.error(err.toString());
import { executePrompt, executePromptStream } from "./executePrompt.js"; import { loadConfig } from "./config.js"; import { loadPromptConfig, listPrompts } from "./loadPromptConfig.js"; import { APPNAME } from "./types.js"; import FileSystemKVS from "./kvs/kvs-filesystem.js"; import { AppError } from "./errors.js"; import { readFileSync } from "node:fs"; function parseArgs(argv: string[]) { const [_nodeBin, _jsFile, promptId, ...rest] = argv; const input = rest.join(" "); return { promptId, input }; } function printUsageAndExit() { console.log("Usage:"); console.log(`$ ${APPNAME} <promptType> <input>`); console.log(`$ ${APPNAME} --list`); console.log(""); console.log("Example: "); console.log(""); console.log(`$ ${APPNAME} eli5 "what are large language models?"`); process.exit(1); } function getInput(argvInput: string) { try { const stdinInput = readFileSync(process.stdin.fd, "utf-8"); // console.log({ stdinInput }); return `${argvInput} ${stdinInput}`; } catch (err) { return argvInput; } } export async function cli() { try { const config = loadConfig(); const { promptId, input: argvInput } = parseArgs(process.argv); if (promptId === "--list") { const prompts = await listPrompts(config); console.log( prompts .map((p) => { const description = p.description ? `: ${p.description}` : ""; return `${p.name}${description}`; }) .join("\n") ); return; } else if (promptId && promptId.startsWith("--")) { printUsageAndExit(); } const input = getInput(argvInput); if (!promptId || !input) { printUsageAndExit(); } const promptConfig = await
loadPromptConfig(promptId, config);
const cache = config.useCache ? new FileSystemKVS({ baseDir: config.paths.cache }) : undefined; const stream = executePromptStream(promptConfig, input, config, cache); for await (const chunk of stream) { process.stdout.write(chunk); } process.stdout.write("\n"); } catch (err) { if (err instanceof AppError) { console.error(err.toString()); process.exit(err.exitCode); } console.error(err); process.exit(1); } } export default cli;
src/index.ts
clevercli-clevercli-c660fae
[ { "filename": "src/loadPromptConfig.ts", "retrieved_chunk": " ]);\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.8015326261520386 }, { "filename": "src/executePrompt.ts", "retrieved_chunk": "import { asyncIterableToArray } from \"./utils.js\";\nfunction defaultParseResponse(content: string, _input: string): ParsedResponse {\n return { message: content };\n}\nfunction toModel(promptConfig: PromptConfiguration): Model {\n const model = promptConfig.model\n ? models.get(promptConfig.model)\n : defaultModel;\n if (!model) {\n throw new AppError({", "score": 0.7848913669586182 }, { "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.7768897414207458 }, { "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.7699638605117798 }, { "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.7698264122009277 } ]
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/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.8297563791275024 }, { "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.8163083791732788 }, { "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.8070148229598999 }, { "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.8013969659805298 }, { "filename": "src/resource/nip07-provider.ts", "retrieved_chunk": " const timeoutId = timeout\n ? setTimeout(() => {\n window.removeEventListener('message', listener);\n reject(`Request \\`${req.kind}\\` timed out`);\n }, timeout)\n : -1;\n function listener(ev: MessageEvent<CrxRpcResponseMessage>) {\n const data = ev.data;\n if (\n data.ext !== 'nostronger' ||", "score": 0.789691686630249 } ]
typescript
= getStrain(ev);
import { handleCrxRpcRequest } from '../lib/messaging'; import { signEvent } from '../lib/nostr'; import { getKeyPair, getSignPower, setSignPower } from '../lib/store'; // * -> ... chrome.runtime.onMessage.addListener((msg: CrxRpcRequestMessage, sender, _sendResponse) => { const { next, shouldBeHandled } = handleCrxRpcRequest(msg, 'background'); if (!shouldBeHandled) { return; } const payload = msg.payload; if (next === 'content' && payload.kind === 'leaveChargeMode') { chrome.tabs.sendMessage(payload.request.senderTabId, msg); return; } else if (!!next) { console.warn('Unexpected message', msg); return; } const sendResponse = (val: any) => { const res: CrxRpcResponseMessage = { ...msg, payload: { kind: payload.kind, response: val, }, }; _sendResponse(res); }; // ... -> HERE switch (payload.kind) { case 'getPubkey': getKeyPair().then(({ pubkey }) => { sendResponse(pubkey); }); return true; // For async response case 'signEvent': getKeyPair().then(async (keypair) => { const signed = await signEvent(keypair, payload.request); sendResponse(signed); }); return true; case 'getSignPower': getSignPower().then(
(power) => {
sendResponse(power); }); return true; case 'setSignPower': setSignPower(payload.request.value).then(() => { sendResponse(void 0); }); return true; case 'openChargeWindow': chrome.windows .create({ url: chrome.runtime.getURL('charge.html'), type: 'popup', }) .then((res) => { const tabId = res.tabs?.[0].id; sendResponse(tabId); }); return true; default: break; } });
src/background/index.ts
penpenpng-nostronger-851a990
[ { "filename": "src/resource/nip07-provider.ts", "retrieved_chunk": " },\n async signEvent(event: UnsignedEvent): Promise<SignedEvent | undefined> {\n let signPower = await rpc(\n {\n kind: 'getSignPower',\n request: {},\n },\n ['content', 'background'],\n );\n if (signPower <= 0) {", "score": 0.8341114521026611 }, { "filename": "src/content/index.ts", "retrieved_chunk": " if (!!next) {\n console.warn('Unexpected message', msg);\n return;\n }\n if (msg.payload.kind === 'leaveChargeMode') {\n resolve();\n }\n },\n {\n addEventListener: (listener) => {", "score": 0.7927666902542114 }, { "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.7817114591598511 }, { "filename": "src/content/index.ts", "retrieved_chunk": " }\n };\n joycon.addEventListener('inputreport', reportListener);\n // Wait for `leaveChargeMode` signal.\n await wait<CrxRpcRequestMessage, void>(\n (resolve) => (msg) => {\n const { next, shouldBeHandled } = handleCrxRpcRequest(msg, 'content');\n if (!shouldBeHandled) {\n return;\n }", "score": 0.7796138525009155 }, { "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.7766685485839844 } ]
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": " 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.8234959840774536 }, { "filename": "src/lib/ring-con.ts", "retrieved_chunk": " if (!device) {\n throw new Error('device not found.');\n }\n if (!device.opened) {\n await device.open();\n }\n await setupJoycon(device);\n return device;\n}\nexport async function setupJoycon(joycon: HIDDevice) {", "score": 0.8215216398239136 }, { "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.7938940525054932 }, { "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.7699010372161865 }, { "filename": "src/lib/ring-con.ts", "retrieved_chunk": "import { wait } from './messaging';\nexport async function getJoyconDevice() {\n const [device] = await navigator.hid.requestDevice({\n filters: [\n {\n vendorId: 0x057e, // Nintendo vendor ID\n productId: 0x2007, // joy-con R\n },\n ],\n });", "score": 0.7608742713928223 } ]
typescript
setupJoycon(joycon);
import { ext, generateMessageId, handleCrxRpcRequest, wait } from '../lib/messaging'; import { getJoyconDevice, getNextStrain, getStrain, setupJoycon } from '../lib/ring-con'; injectResourceScript('js/nip07-provider.js'); // 'nip07-provider' -> ... window.addEventListener('message', async ({ data }: MessageEvent<CrxRpcRequestMessage>) => { const { next, shouldBeHandled } = handleCrxRpcRequest(data, 'content'); if (!shouldBeHandled) { return; } if (next === 'background') { // ... -> HERE -> 'background' const response: CrxRpcResponseMessage = await chrome.runtime.sendMessage(data); window.postMessage(response); return; } else if (!!next) { console.warn('Unexpected message', data); return; } //... -> HERE switch (data.payload.kind) { case 'enterChargeMode': { try { const response = await enterChargeMode(data); window.postMessage(response); } catch (err) { console.error(err); window.postMessage({ ext, messageId: data.messageId, payload: { kind: 'enterChargeMode', response: false, }, }); throw err; } } break; default: break; } }); async function enterChargeMode({ messageId, payload, }: CrxRpcRequestMessage): Promise<CrxRpcResponseMessage> { if (payload.kind !== 'enterChargeMode') { throw 'Unexpected message'; } const openChargeWindowReq: CrxRpcMessage = { ext,
messageId: generateMessageId(), src: 'content', path: ['background'], payload: {
kind: 'openChargeWindow', request: {}, }, }; const { payload: result }: CrxRpcResponseMessage = await chrome.runtime.sendMessage( openChargeWindowReq, ); if (result.kind !== 'openChargeWindow') { throw 'Unexpected message'; } // Keep sending strain signals. const joycon = await getJoyconDevice(); await setupJoycon(joycon); const neutral = await getNextStrain(joycon); const sendStrain = (value: number) => { const req: CrxRpcMessage = { ext, messageId: generateMessageId(), src: 'content', path: ['charge'], payload: { kind: 'sendStrain', request: { value, neutral, }, }, }; chrome.runtime.sendMessage(req); }; const reportListener = (ev: HIDInputReportEvent) => { const value = getStrain(ev); if (value) { sendStrain(value); } }; joycon.addEventListener('inputreport', reportListener); // Wait for `leaveChargeMode` signal. await wait<CrxRpcRequestMessage, void>( (resolve) => (msg) => { const { next, shouldBeHandled } = handleCrxRpcRequest(msg, 'content'); if (!shouldBeHandled) { return; } if (!!next) { console.warn('Unexpected message', msg); return; } if (msg.payload.kind === 'leaveChargeMode') { resolve(); } }, { addEventListener: (listener) => { chrome.runtime.onMessage.addListener(listener); }, removeEventListener: (listener) => { chrome.runtime.onMessage.removeListener(listener); }, }, ); // Stop sending strain signals. joycon.removeEventListener('inputreport', reportListener); return { ext, messageId, payload: { kind: 'enterChargeMode', response: true, }, }; } function injectResourceScript(path: string) { const script = document.createElement('script'); script.setAttribute('async', 'false'); script.setAttribute('type', 'text/javascript'); script.setAttribute('src', chrome.runtime.getURL(path)); document.head.appendChild(script); }
src/content/index.ts
penpenpng-nostronger-851a990
[ { "filename": "src/background/index.ts", "retrieved_chunk": " if (next === 'content' && payload.kind === 'leaveChargeMode') {\n chrome.tabs.sendMessage(payload.request.senderTabId, msg);\n return;\n } else if (!!next) {\n console.warn('Unexpected message', msg);\n return;\n }\n const sendResponse = (val: any) => {\n const res: CrxRpcResponseMessage = {\n ...msg,", "score": 0.871208906173706 }, { "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.8382965326309204 }, { "filename": "src/lib/messaging.ts", "retrieved_chunk": " msg: CrxRpcRequestMessage,\n origin: CrxMessageOrigin,\n): { next?: CrxMessageOrigin; shouldBeHandled: boolean } {\n if (msg.ext !== 'nostronger' || !('request' in msg.payload) || msg.path[0] !== origin) {\n return {\n shouldBeHandled: false,\n };\n }\n msg.path.shift();\n const next = msg.path[0];", "score": 0.83826744556427 }, { "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.837191104888916 }, { "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.8343703746795654 } ]
typescript
messageId: generateMessageId(), src: 'content', path: ['background'], payload: {