repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
olujedai/sw-api
src/comment/dto/comment.param.dto.ts
<reponame>olujedai/sw-api import { ApiModelProperty } from '@nestjs/swagger'; export class CommentParamDto { @ApiModelProperty( { description: 'The movie ID to retrieve comments for', required: true, type: 'number', }, ) movieId: number; }
olujedai/sw-api
src/movies/dto/movies.dto.ts
import { ApiModelProperty } from '@nestjs/swagger'; /** * Data Transfer Object that specifies the movie fields used in this application */ export class MovieDto { @ApiModelProperty( { description: 'The ID of the movie', type: 'number', }, ) readonly id: number; @ApiModelProperty( { description: 'The name of the movie', type: 'string', }, ) readonly name: string; @ApiModelProperty( { description: 'The date the movie was released', type: 'string', }, ) readonly releaseDate: string; @ApiModelProperty( { description: 'The opening crawl of the movie', type: 'string', }, ) readonly openingCrawl: string; @ApiModelProperty( { description: 'An array of the character urls', type: 'string', }, ) readonly characters: string[]; @ApiModelProperty( { description: 'The number of comments the movie has', type: 'number', }, ) commentCount: number; }
olujedai/sw-api
src/movies/movies.module.ts
<filename>src/movies/movies.module.ts import { Module } from '@nestjs/common'; import { MoviesController } from './movies.controller'; import { MoviesService } from './movies.service'; import { RequestModule } from '../request/request.module'; import { UtilsModule } from '../utils/utils.module'; import { CommentModule } from '../comment/comment.module'; import { CharacterModule } from '../character/character.module'; import { MovieValidator } from './movies.validator'; /** * The controllers, providers, imports and exports of the Movies module are registered here */ @Module({ controllers: [MoviesController], providers: [MoviesService, MovieValidator], imports: [RequestModule, UtilsModule, CommentModule, CharacterModule], exports: [MoviesService], }) export class MoviesModule {}
olujedai/sw-api
src/movies/movies.validator.spec.ts
import { NotFoundException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { getRepositoryToken } from '@nestjs/typeorm'; import { MoviesService } from './movies.service'; import { MovieValidator } from './movies.validator'; import { RequestService } from '../request/request.service'; import { UtilsService } from '../utils/utils.service'; import { CommentService } from '../comment/comment.service'; import { Comment } from '../comment/comment.entity'; import * as fs from 'fs'; import { MovieDto } from './dto/movies.dto'; const processedMovieJson: Buffer = fs.readFileSync(`${__dirname}/static/processedMovie.json`); const processedMovie: MovieDto = JSON.parse(processedMovieJson.toString()); describe('Movie validation tests', () => { let movieService: MoviesService; let movieValidator: MovieValidator; let requestService: RequestService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ RequestService, CommentService, { provide: getRepositoryToken(Comment), useValue: {name: ''}, }, MoviesService, UtilsService, MovieValidator, ], }).compile(); movieService = module.get<MoviesService>(MoviesService); requestService = module.get<RequestService>(RequestService); movieValidator = module.get<MovieValidator>(MovieValidator); }); afterAll(() => requestService.closeRedisInstance()); it('should be defined', () => { expect(movieService).toBeDefined(); expect(movieValidator).toBeDefined(); }); it('should raise a Not found exception when a movie is not found', async () => { jest.spyOn(movieService, 'getMovie').mockResolvedValue(null); await expect(movieValidator.validateMovieId(1)).rejects.toThrow(NotFoundException); }); it('should return a movie', async () => { jest.spyOn(movieService, 'getMovie').mockResolvedValue(processedMovie); expect(await movieValidator.validateMovieId(1)).toBe(processedMovie); }); });
olujedai/sw-api
src/movies/movies.service.ts
import { Injectable } from '@nestjs/common'; import { MovieDto } from './dto/movies.dto'; import { RemoteMovieObjectDto } from './dto/remoteMovie.dto'; import { RemoteMoviesObjectDto } from './dto/remoteMovies.dto'; import { RequestService } from '../request/request.service'; import { UtilsService } from '../utils/utils.service'; import { CommentService } from '../comment/comment.service'; /* Provides methods that implement logic for responding to movie related requests by interacting with the cache, database and remote url */ @Injectable() export class MoviesService { constructor( private readonly requestService: RequestService, private readonly utilsService: UtilsService, private readonly commentService: CommentService, ) {} async getMovies(): Promise<MovieDto[]> { /** * This provides requests for movies from the cache or external api and returns processed movies to the caller. * @returns an array of MovieDto objects */ const path: string = 'films'; let movies: RemoteMovieObjectDto[] | MovieDto[] | string; movies = await this.requestService.getFromRedis(path); if (typeof(movies) === 'string') { const parsedMovies: MovieDto[] = JSON.parse(movies); return await this.getMovieCommentsAndSort(parsedMovies); } movies = await this.getMoviesFromRemote(path); movies = movies.map(movie => this.retrieveFields(movie)); movies = await this.getMovieCommentsAndSort(movies); this.requestService.storeInRedis(path, JSON.stringify(movies)); return movies; } async getMoviesFromRemote(path: string): Promise<RemoteMovieObjectDto[]> { /** * Request movies from a remote API * @param path: The path to be requested * @returns an array of movies */ const resp: RemoteMoviesObjectDto = await this.requestService.fetch(path); return resp.results; } async getMovieCommentsAndSort(movieList: MovieDto[]): Promise<MovieDto[]> { /** * This method returns the associated comment count of a movie while sorting the movie list by release date * @param movieList list of movies * @returns processed movies */ movieList = await this.getMovieComments(movieList); return this.sortMovieList(movieList); } async getMovieComments(movieList: MovieDto[]): Promise<MovieDto[]> { /** * This method returns the associated comment count of a movie while sorting the movie list by release date * @param movieList list of movies * @returns processed movies */ const movieIds: number[] = movieList.map(movie => movie.id); const movieComments: Array<Promise<number>> = movieIds.map(movieId => this.getCommentCount(movieId)); const resolvedComments: number[] = await Promise.all(movieComments); movieList.forEach((movie, index) => { movie.commentCount = resolvedComments[index]; }); return movieList; } sortMovieList(movieList: MovieDto[]): MovieDto[] { /** * This method takes in a list of movies of type MovieDto and returns the movies sorted by releaseDate * @param movieList list of movies * @returns list of movies sorted by releaseDate */ return movieList.sort(this.utilsService.sortFunction('releaseDate')); } async getMovie(movieId: number): Promise<MovieDto|null> { /** * Request a movie from the cache or remote API and store the api response in the cache * @param movieId: The ID of the movie to be requested * @returns an movie object */ const path: string = `films/${movieId}`; let movie: RemoteMovieObjectDto | MovieDto | string; movie = await this.requestService.getFromRedis(path); if (typeof(movie) === 'string') { return JSON.parse(movie); } const resp: RemoteMovieObjectDto | null = await this.getMovieFromRemote(path); if (typeof(resp) === 'undefined') { return resp; } movie = this.retrieveFields(resp); this.requestService.storeInRedis(path, JSON.stringify(movie)); return movie; } async getMovieFromRemote(path: string): Promise<RemoteMovieObjectDto|null> { /** * Request a movie from a remote api. * @param path the path to the movie * @returns a MovieDto object or null */ const resp: RemoteMovieObjectDto | null = await this.requestService.fetch(path); return resp; } retrieveFields(movie: RemoteMovieObjectDto): MovieDto { /** * Transform a movie object to the format used in this application. * @param movie the movie object from a remote api * @returns a MovieDto object */ return { id: movie.episode_id, name: movie.title, releaseDate: movie.release_date, openingCrawl: movie.opening_crawl, characters: movie.characters, commentCount: 0, }; } getCommentCount(movieId: number): Promise<number> { /** * Method for obtaining the number of comments a movie has * @param movieId: The ID of the movie * @returns a number indicating the number of comments a movie has */ const filter: { movieId: number; } = { movieId, }; return this.commentService.countMovieComments(filter); } }
olujedai/sw-api
src/character/dto/feet.dto.ts
<filename>src/character/dto/feet.dto.ts import { ApiModelProperty } from '@nestjs/swagger'; export class FeetDto { @ApiModelProperty( { description: 'Feet', type: 'number', }, ) readonly feet: number; @ApiModelProperty( { description: 'Inches', type: 'number', }, ) readonly inches: number; }
olujedai/sw-api
src/migrations/1568642525780-Comment-migration.ts
<gh_stars>0 import {MigrationInterface, QueryRunner} from 'typeorm'; export class CommentMigration1568642525780 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<any> { await queryRunner.query(`ALTER TABLE "comment" DROP COLUMN "commenter"`); } public async down(queryRunner: QueryRunner): Promise<any> { await queryRunner.query(`ALTER TABLE "comment" ADD "commenter" character varying(20) NOT NULL`); } }
olujedai/sw-api
src/request/request.service.ts
import { Injectable } from '@nestjs/common'; import * as rp from 'request-promise-native'; import { promisify } from 'util'; import * as redis from 'redis'; import { RemoteMoviesObjectDto } from '../movies/dto/remoteMovies.dto'; import { RemoteMovieObjectDto } from '../movies/dto/remoteMovie.dto'; /* Provides methods that implement logic for interacting with the cache and remote APIs */ const redisUrl = process.env.REDIS_URL; export const client = redis.createClient({ url: redisUrl, }); @Injectable() export class RequestService { storeInRedis = promisify(client.set).bind(client); getFromRedis = promisify(client.get).bind(client); closeRedisInstance = () => { client.quit(); } async fetch(path: string) { const endpoint = process.env.SWAPI_URL || 'https://swapi.co/api'; const options = { uri: `${endpoint}/${path}`, method: 'GET', simple: true, json: true, }; return rp(options).then( (resp: RemoteMoviesObjectDto|RemoteMovieObjectDto): RemoteMoviesObjectDto|RemoteMovieObjectDto => { return resp; }) .catch((err: {statusCode: number}): null => { if (err.statusCode === 400) { return null; } }); } async fetchUrl(url: string) { const options = { uri: url, method: 'GET', simple: true, json: true, }; return rp(options).then( (resp) => { return resp; }) .catch((err) => { return null; }); } }
olujedai/sw-api
src/utils/utils.service.spec.ts
import { Test, TestingModule } from '@nestjs/testing'; import { UtilsService } from './utils.service'; const objectArr: Array<{date: string}> = [ { date: '2037-05-25', }, { date: '1987-05-25', }, { date: '1977-05-25', }, { date: '1997-05-25', }, ]; const request: {headers: object, connection: {remoteAddress: string}, socket: {remoteAddress: string}} = { headers: { 'x-forwarded-for': '192.168.0.0', }, connection: { remoteAddress: '192.168.0.1', }, socket: { remoteAddress: '192.168.0.2', }, }; describe('UtilsService', () => { let utilsService: UtilsService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [UtilsService], }).compile(); utilsService = module.get<UtilsService>(UtilsService); }); it('should be defined', () => { expect(utilsService).toBeDefined(); }); it('should not sort array of objects in ascending order', () => { objectArr.sort(utilsService.sortFunction('releaseDate')); expect(objectArr[0].date).toBe('2037-05-25'); expect(objectArr[objectArr.length - 1].date).toBe('1997-05-25'); }); it('should not sort array of objects in descending order', () => { objectArr.sort(utilsService.sortFunction('releaseDate', 'desc')); expect(objectArr[0].date).toBe('2037-05-25'); expect(objectArr[objectArr.length - 1].date).toBe('1997-05-25'); }); it('should sort array of objects in ascending order', () => { objectArr.sort(utilsService.sortFunction('date')); expect(objectArr[0].date).toBe('1977-05-25'); expect(objectArr[objectArr.length - 1].date).toBe('2037-05-25'); }); it('should sort array of objects in descending order', () => { objectArr.sort(utilsService.sortFunction('date', 'desc')); expect(objectArr[0].date).toBe('2037-05-25'); expect(objectArr[objectArr.length - 1].date).toBe('1977-05-25'); }); it('returns that the passed in argument is a number', () => { expect(utilsService.isANumber('1')).toBe(true); expect(utilsService.isANumber(5)).toBe(true); }); it('returns that the passed in argument is not a number', () => { expect(utilsService.isANumber('this')).toBe(false); expect(utilsService.isANumber('that')).toBe(false); }); it('should return the ipaddress in the x-forwarded-for header', () => { // @ts-ignore expect(utilsService.getIpAddress(request)).toBe('192.168.0.0'); }); it('should return the ipaddress in request.connection.remoteAddress', () => { delete request.headers['x-forwarded-for']; // @ts-ignore expect(utilsService.getIpAddress(request)).toBe('192.168.0.1'); }); it('should return the ipaddress in request.socket.remoteAddress', () => { delete request.headers['x-forwarded-for']; delete request.connection.remoteAddress; // @ts-ignore expect(utilsService.getIpAddress(request)).toBe('192.168.0.2'); }); it('should return an empty string as the ipaddress', () => { delete request.headers['x-forwarded-for']; delete request.connection.remoteAddress; delete request.socket.remoteAddress; // @ts-ignore expect(utilsService.getIpAddress(request)).toBe(''); }); });
olujedai/sw-api
src/character/dto/characterMeta.dto.ts
<reponame>olujedai/sw-api<filename>src/character/dto/characterMeta.dto.ts import { HeightMeta } from './heightMeta.dto'; import { ApiModelProperty } from '@nestjs/swagger'; /** * Character meta Data Transfer Object */ export class Meta { @ApiModelProperty( { description: 'The total number of characters', type: 'number', }, ) readonly total: number; @ApiModelProperty( { description: 'Height metadata', type: HeightMeta, }, ) readonly totalHeight: HeightMeta; }
olujedai/sw-api
src/logger/logger.constant.ts
<filename>src/logger/logger.constant.ts export const LOGGER_MODULE_OPTIONS = 'LOGGER_MODULE_OPTIONS'; export const LOG_FORMAT = '[:date[iso]] ":method :url" :status :response-time \ :referrer :user-agent :http-version :res[content-length] :req[remote-address]';
olujedai/sw-api
src/comment/dto/commentResponse.dto.ts
<reponame>olujedai/sw-api<filename>src/comment/dto/commentResponse.dto.ts import { ApiModelProperty } from '@nestjs/swagger'; import { CommentBodyDto } from './comment.dto'; /** * Comment Data Transfer Object for creating a new movie comment along with the swagger api definition and * field validations are defined here. */ export class CommentResponseDto { @ApiModelProperty( { description: 'The number of movie comments', type: 'number', }, ) readonly count: number; @ApiModelProperty( { description: 'An array of movie comments', type: [CommentBodyDto], }, ) readonly comments: CommentBodyDto[]; }
olujedai/sw-api
src/character/dto/character.dto.ts
<filename>src/character/dto/character.dto.ts import { ApiModelProperty } from '@nestjs/swagger'; export class CharacterDto { @ApiModelProperty( { description: 'The name of the character', type: 'string', }, ) readonly name: string; @ApiModelProperty( { description: 'The gender of the character', type: 'string', }, ) readonly gender: string; @ApiModelProperty( { description: 'The height of the character', type: 'number', }, ) readonly height: number | null; }
olujedai/sw-api
src/validatation.pipe.ts
import { ValidationPipe, ArgumentMetadata, BadRequestException, NotFoundException } from '@nestjs/common'; export class ValidationPipe404 extends ValidationPipe { public async transform(value, metadata: ArgumentMetadata) { try { return await super.transform(value, metadata); } catch (e) { if (e instanceof BadRequestException) { if (e.message.message[0].property === 'movieId') { throw new NotFoundException(e.message.message); } throw new BadRequestException(e.message.message); } } } }
olujedai/sw-api
src/character/dto/apiResponse.dto.ts
<reponame>olujedai/sw-api<gh_stars>0 // tslint:disable:variable-name export interface RemoteCharacterObjectDto { readonly name: string; readonly height: string; readonly mass: string; readonly hair_colour: string; readonly skin_colour: string; readonly eye_colour: string; readonly birth_year: string; readonly gender: string; readonly homeworld: string; readonly films: string[]; readonly species: string[]; readonly vehicles: string[]; readonly star_ships: string[]; readonly created: string; readonly edited: string; readonly url: string; }
olujedai/sw-api
test/app.e2e-spec.ts
<gh_stars>0 import { Test, TestingModule } from '@nestjs/testing'; import * as request from 'supertest'; import { AppModule } from './../src/app.module'; import { TypeOrmModule, getRepositoryToken } from '@nestjs/typeorm'; import { Comment } from './../src/comment/comment.entity'; import { RequestService } from './../src/request/request.service'; import * as fs from 'fs'; import { MovieDto } from './../src/movies/dto/movies.dto'; import { Repository } from 'typeorm'; import { MoviesService } from './../src/movies/movies.service'; import { UtilsService } from './../src/utils/utils.service'; import { CommentService } from './../src/comment/comment.service'; const processedMoviesJson: Buffer = fs.readFileSync(`${__dirname}/../src/movies/static/processedMovies.json`); const processedMovies: MovieDto[] = JSON.parse(processedMoviesJson.toString()); const processedMovieJson: Buffer = fs.readFileSync(`${__dirname}/../src/movies/static/processedMovie.json`); const processedMovie: MovieDto = JSON.parse(processedMovieJson.toString()); describe('AppController (e2e)', () => { let app; let moduleFixture: TestingModule; let requestService: RequestService; let movieService: MoviesService; let utilsService: UtilsService; let repository: Repository<Comment>; beforeEach(async () => { moduleFixture = await Test.createTestingModule({ imports: [ AppModule, TypeOrmModule.forRoot({ type: 'postgres', host: String(process.env.DATABASE_HOST), port: Number(process.env.DATABASE_PORT), username: String(process.env.DATABASE_USER), password: String(process.env.DATABASE_PASSWORD), database: 'sw-api-test-db', entities: [Comment], dropSchema: true, synchronize: false, keepConnectionAlive: true, }), TypeOrmModule.forFeature([Comment]), ], providers: [ RequestService, MoviesService, UtilsService, CommentService, { provide: getRepositoryToken(Comment), useClass: Repository, }, ], }).compile(); requestService = moduleFixture.get<RequestService>(RequestService); movieService = moduleFixture.get<MoviesService>(MoviesService); utilsService = moduleFixture.get<UtilsService>(UtilsService); repository = moduleFixture.get<Repository<Comment>>(getRepositoryToken(Comment)); app = moduleFixture.createNestApplication(); await app.init(); }); it('should be defined', () => { expect(requestService).toBeDefined(); expect(movieService).toBeDefined(); expect(repository).toBeDefined(); }); it('/ (GET)', () => { return request(app.getHttpServer()) .get('/is-alive') .expect(200) .expect('This server is up'); }); it('/movies (GET)', async () => { jest.spyOn(movieService, 'getMovies').mockResolvedValueOnce(processedMovies); const response: request.Response = await request(app.getHttpServer()) .get('/movies') .expect(200); expect(response.body).toEqual(processedMovies); }); it('gets movie comments', async () => { // todo: add data to the database before querying for it. jest.spyOn(movieService, 'getMovie').mockResolvedValueOnce(processedMovie); const response: request.Response = await request(app.getHttpServer()) .get('/movies/1/comments') .expect(200); }); it('creates a new movie comment', async () => { const data = { comment: '<NAME>', }; const mockIpAddress: string = '192.168.0.1'; jest.spyOn(utilsService, 'getIpAddress').mockReturnValueOnce(mockIpAddress); jest.spyOn(movieService, 'getMovie').mockResolvedValueOnce(processedMovie); const response: request.Response = await request(app.getHttpServer()) .post('/movies/3/comments') .send(data) .set('Content-Type', 'application/json') .set('Accept', 'application/json') .expect(201); expect(response.body.comment).toEqual(data.comment); expect(response.body.ipAddress).toEqual(mockIpAddress); const movieComments = await repository.find({ where: { movieId: 3, }, }); expect(movieComments).toHaveLength(1); }); it('fails to create a new movie comment for a movie that doesnt exist', async () => { const data = { comment: 'Decent movie', }; jest.spyOn(utilsService, 'getIpAddress').mockReturnValueOnce('192.168.0.1'); jest.spyOn(movieService, 'getMovie').mockResolvedValueOnce(null); return request(app.getHttpServer()) .post('/movies/1/comments') .send(data) .set('Content-Type', 'application/json') .set('Accept', 'application/json') .expect(404); }); it('fails to retrieve movie comments for a movie that doesnt exist', async () => { jest.spyOn(movieService, 'getMovie').mockResolvedValueOnce(null); const response: request.Response = await request(app.getHttpServer()) .get('/movies/1/comments') .set('Content-Type', 'application/json') .set('Accept', 'application/json') .expect(404); }); it('fails to retrieve movie characters for a movie that doesnt exist', async () => { jest.spyOn(movieService, 'getMovie').mockResolvedValueOnce(null); const response: request.Response = await request(app.getHttpServer()) .get('/movies/1/characters') .set('Content-Type', 'application/json') .set('Accept', 'application/json') .expect(404); }); afterEach(async () => { moduleFixture.close(); }); afterAll(async () => { requestService.closeRedisInstance(); await app.close(); }); });
olujedai/sw-api
src/movies/dto/remoteMovies.dto.ts
<filename>src/movies/dto/remoteMovies.dto.ts // tslint:disable:variable-name import { RemoteMovieObjectDto } from './remoteMovie.dto'; /** * Data Transfer Object for specifying the expected api response */ export interface RemoteMoviesObjectDto { readonly id: number; readonly count: number; readonly next: null | boolean; readonly previous: null | boolean; readonly results: RemoteMovieObjectDto[]; }
olujedai/sw-api
src/utils/utils.service.ts
<gh_stars>0 import { Injectable } from '@nestjs/common'; import { Request } from 'express'; @Injectable() export class UtilsService { sortFunction = (key: string, order: string = 'asc') => (a, b): number => { /** * Method used for sorting an array of objects by the compareFunction array sort function. * @param key the property in the object to be used for sorting * @param order the order in which the objects will be sorted * @param a the first object to be compared * @param b the second object to be compared */ if (!Object.prototype.hasOwnProperty.call(a, key) || !Object.prototype.hasOwnProperty.call(b, key)) { return 0; } let valA: string | number ; let valB: string | number ; valA = a[key]; valB = b[key]; if (typeof(valA) === 'string') { valA = valA.toUpperCase(); } if (typeof(valB) === 'string') { valB = valB.toUpperCase(); } if (this.isANumber(valA)) { valA = Number(valA); } if (this.isANumber(valB)) { valB = Number(valB); } let comparison = 0; if (valA > valB) { comparison = 1; } else if (valA < valB) { comparison = -1; } return (order.toLowerCase() === 'desc') ? (comparison * -1) : comparison; } isANumber = (a: number | string): boolean => { return !Number.isNaN(Number(a)); } getIpAddress = (request: Request): string => { const ipAddress: string | string[] = (request.headers['x-forwarded-for']); if (typeof(ipAddress) === 'string') { return ipAddress.split(',').pop() || request.connection.remoteAddress || request.socket.remoteAddress || ''; } return request.connection.remoteAddress || request.socket.remoteAddress || ''; } }
olujedai/sw-api
src/app.module.ts
<filename>src/app.module.ts import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { MoviesModule } from './movies/movies.module'; import { RequestModule } from './request/request.module'; import { CharacterModule } from './character/character.module'; import { UtilsModule } from './utils/utils.module'; import { CommentModule } from './comment/comment.module'; import { TypeOrmModule } from '@nestjs/typeorm'; import { LoggerModule } from './logger/logger.module'; import { config } from './ormconfig'; @Module({ imports: [MoviesModule, RequestModule, CharacterModule, UtilsModule, CommentModule, TypeOrmModule.forRoot(config), LoggerModule, ], controllers: [AppController], providers: [AppService], }) export class AppModule {}
olujedai/sw-api
src/character/character.service.ts
<reponame>olujedai/sw-api import { Injectable } from '@nestjs/common'; import { RequestService } from '../request/request.service'; import { CharacterDto } from './dto/character.dto'; import { CharactersDto } from './dto/characters.dto'; import { UtilsService } from '../utils/utils.service'; import { FeetDto } from './dto/feet.dto'; import { RemoteCharacterObjectDto } from './dto/apiResponse.dto'; @Injectable() export class CharacterService { constructor( private readonly requestService: RequestService, private readonly utilsService: UtilsService, ) {} async getCharacters(characters: string[], sort?: string, order?: string, filter?: string): Promise<CharactersDto> { /** * This method requests for characters from redis or from the remote url. An returns the processed characters to the caller * @param characters an array of character urls * @param sort the rule to be used for sorting the characters * @param order the order in which the characters should be sorted. * @param filter rule to indicate if the response should be filtered by gender * @returns an array of movie characters along with metadata indicating the total number of characters and their heights in * centimeters as well as feets and inches. */ const resolvedPromisesList: RemoteCharacterObjectDto[] = await this.getCharactersFromUrls(characters); let allCharacters: CharacterDto[] = resolvedPromisesList.map(character => this.retrieveCharacterFields(character)); allCharacters = this.applyCharacterSortAndFilter(allCharacters, sort, order, filter); return this.createCharacterResponseObject(allCharacters); } async getCharactersFromUrls(characters: string[]): Promise<RemoteCharacterObjectDto[]> { /** * This method requests for characters from redis or from the remote url. */ const characterPromisesList = []; characters.forEach(characterUrl => { const character = this.getCharacter(characterUrl); characterPromisesList.push(character); }); return await Promise.all(characterPromisesList); } async getCharacter(characterUrl: string): Promise<CharacterDto|string> { /** * This method attempts to retrieve a character from the cache or from the remote url. * It returns a CharacterDto from redis or an object from the remote url if the remote request is successful, otherwise it returns null * @param characterUrl the url of the character. This is used as the key to the cache or the url to be retrieved by a remote request * @returns a character object defined by CharacterDto */ let character: string | CharacterDto; character = await this.requestService.getFromRedis(characterUrl); if (typeof(character) === 'string') { return JSON.parse(character); } character = await this.requestService.fetchUrl(characterUrl); this.requestService.storeInRedis(characterUrl, JSON.stringify(character)); return character; } applyCharacterSortAndFilter(allCharacters: CharacterDto[], sort?: string, order?: string, filter?: string): CharacterDto[] { /** * This method applies any sort or filter to all the characters and returns a response with metadata */ if (filter) { allCharacters = allCharacters.filter(character => this.filterMethod(character, filter)); } if (sort) { allCharacters = this.sort(allCharacters, sort, order); } return allCharacters; } createCharacterResponseObject(allCharacters: CharacterDto[]): CharactersDto { const totalNumberOfCharacters: number = allCharacters.length; const totalHeightInCm: number = this.calculateHeightInCm(allCharacters); const movieCharacters: CharactersDto = this.getResponseFormat(allCharacters, totalNumberOfCharacters, totalHeightInCm); return movieCharacters; } filterMethod(character: CharacterDto, gender: string): boolean { return this.formatGender(character.gender) === this.formatGender(gender); } sort(allCharacters: CharacterDto[], sort: string, order?: string): CharacterDto[] { return allCharacters.sort(this.utilsService.sortFunction(sort, order)); } formatGender(gender: string): string { return gender.toLowerCase(); } calculateHeightInCm(characterList: CharacterDto[]): number { const numOr0 = (n: number) => isNaN(n) ? 0 : Number(n); let totalHeightInCm: number = 0; characterList.forEach((character: CharacterDto) => totalHeightInCm += numOr0(character.height), ); return totalHeightInCm; } convertCmToFeet(heightInCm: number): FeetDto { const realFeet: number = ((heightInCm * 0.393700) / 12); const feet: number = Math.floor(realFeet); const inches: number = Math.round((realFeet - feet) * 12); return {feet, inches}; } formatFeet(heightInFeet: FeetDto): {feet: number, inches: number} { const {feet, inches} = heightInFeet; return {feet, inches}; } getResponseFormat(allCharacters: CharacterDto[], totalNumberOfCharacters: number, totalHeightInCm: number): CharactersDto { /* This method takes in an array of character objects (CharacterDto) and returns an object with characters and metadata */ return { metadata: { total: totalNumberOfCharacters, totalHeight: { cm: `${totalHeightInCm}cm`, feet: this.formatFeet(this.convertCmToFeet(totalHeightInCm)), }, }, characters: allCharacters, }; } retrieveCharacterFields(character: RemoteCharacterObjectDto): CharacterDto { /** * This method takes in a character object from an api and returns a character object in the format specified by the CharacterDto * @param character character object defined by RemoteCharacterObjectDto * @returns a character object defined by CharacterDto */ return { name: character.name, gender: this.formatGender(character.gender), height: this.utilsService.isANumber(character.height) ? Number(character.height) : null, }; } }
olujedai/sw-api
src/logger/logger.service.ts
<filename>src/logger/logger.service.ts import { Injectable, LoggerService as NestLoggerService } from '@nestjs/common'; import { createLogger, format, Logger, transports } from 'winston'; import { Request, RequestHandler, Response } from 'express'; import * as morgan from 'morgan'; import { LOG_FORMAT } from './logger.constant'; /** * The application logger based on winston and morgan is defined here. */ @Injectable() export class LoggerService implements NestLoggerService { private readonly logger: Logger; private readonly format: string; constructor() { this.format = LOG_FORMAT; this.logger = createLogger({ level: 'info', format: format.json(), transports: [ new transports.Console(), new transports.File({ filename: 'error.log', level: 'error' }), ]}); } logInfo(): RequestHandler { return morgan(this.format, { skip: (req: Request, res: Response) => res.statusCode < 400, stream: process.stdout, }); } logError(): RequestHandler { return morgan(this.format, { skip: (req: Request, res: Response) => res.statusCode >= 400, stream: process.stderr, }); } debug(message: string, context?: string): void { this.logger.debug(message, context); } error(message: string, trace?: string, context?: string): void { this.logger.debug(message, context, trace); } log(message: string, context?: string): void { this.logger.log({ level: 'info', message }); } verbose(message: string, context?: string): void { this.logger.verbose(message, context); } warn(message: string, context?: string): void { this.logger.verbose(message, context); } }
aranja/react-document
src/parts.tsx
<filename>src/parts.tsx import * as React from 'react' import * as PropTypes from 'prop-types' import * as serialize from 'serialize-javascript' import { DocumentProps, documentPropTypes } from './Document' export abstract class DocumentPart<Props> extends React.Component<Props, any> { static contextTypes = { documentProps: PropTypes.shape(documentPropTypes).isRequired } context: { documentProps: DocumentProps, } } export class Html extends DocumentPart<any> { render() { return ( <html {...this.context.documentProps.htmlProps} {...this.props} /> ) } } export class Head extends DocumentPart<any> { render() { const { title, viewport, head, css, js } = { ...this.context.documentProps, ...this.props } as DocumentProps return ( <head> <meta charSet="utf-8" /> {title && <title>{title}</title>} <meta name="viewport" content={viewport} /> {head && head.map((element, i) => React.cloneElement(element, { key: i }))} {css && css.map(file => <link key={file} href={file} rel="stylesheet" />)} {js && js.map(file => <script key={file} src={file} defer />)} {this.props.children} </head> ) } } export class Body extends DocumentPart<any> { render() { return ( <body {...this.context.documentProps.bodyProps} {...this.props} /> ) } } export class App extends DocumentPart<{ id?: string, children?: any }> { render() { const id = this.props.id || this.context.documentProps.appMountId const content = this.props.children || this.context.documentProps.app return ( <div id={id} dangerouslySetInnerHTML={{ __html: content || '' }} /> ) } } export class Footer extends DocumentPart<any> { render() { const { window, footer } = { ...this.context.documentProps, ...this.props } as DocumentProps const { children } = this.props if (!window && !footer && !children) { return null } return ( <div> {window && ( <script dangerouslySetInnerHTML={{ __html: Object.keys(window).map(key => `window['${key}'] = ${serialize(window[key])};` ).join('\n') }} /> )} {footer && footer.map((element, i) => React.cloneElement(element, { key: i })) } {children} </div> ) } }
aranja/react-document
src/Document.tsx
<gh_stars>1-10 import * as React from 'react' import * as PropTypes from 'prop-types' import { Html, Head, Body, App, Footer } from './parts' export interface DocumentProps { htmlProps?: { [key: string]: string } bodyProps?: { [key: string]: string } children?: string title?: string viewport?: string head?: React.ReactElement<any>[] footer?: React.ReactElement<any>[] css?: string[] js?: string[] appMountId?: string, app?: string, window?: { [key: string]: any } } export const documentPropTypes = { htmlProps: PropTypes.object, bodyProps: PropTypes.object, children: PropTypes.string, title: PropTypes.string, viewport: PropTypes.string, head: PropTypes.node, footer: PropTypes.node, css: PropTypes.arrayOf(PropTypes.string), js: PropTypes.arrayOf(PropTypes.string), appMountId: PropTypes.string, app: PropTypes.string, window: PropTypes.object, } class Document extends React.Component<DocumentProps, any> { static childContextTypes = { documentProps: PropTypes.shape(documentPropTypes).isRequired, } static propTypes = documentPropTypes getChildContext() { const props: any = Object.assign({}, this.props) if (props.children && !props.app) { props.app = props.children delete props.children } return { documentProps: props, } } static defaultProps = { app: '', appMountId: 'app', viewport: 'width=device-width, initial-scale=1', } render() { return ( <Html> <Head> </Head> <Body> <App /> <Footer /> </Body> </Html> ) } } export default Document
aranja/react-document
src/index.ts
export { default } from './Document' export * from './parts' export const file = require.resolve('./Document')
PabloLec/neoss
src/ui/popups.ts
<reponame>PabloLec/neoss import { Box } from "neo-blessed"; import { readFile } from "fs"; import { join } from "path"; import { whois } from "../utils/whois"; var screen: any; var currentBox: any = null; var strings = {}; const stringsNames = ["ports", "protocols", "queues", "states"]; // Load strings stringsNames.forEach(function (name) { readFile(join(__dirname, "..", "..", "src", "strings", name + ".json"), (err: any, data: any) => { if (err) throw err; strings[name] = JSON.parse(data); }); }); export function setDefaultScreen(defaultScreen: any) { screen = defaultScreen; } /** * If a popup exists in currentBox var, focus it. */ export function focusPopup() { if (currentBox != null) { currentBox.focus(); } } /** * Remove popup currently stored in currentBox var and returns focus to main table. */ export function removePopup() { if (currentBox == null) { return; } screen.remove(currentBox); currentBox = null; screen.rewindFocus(); screen.render(); } /** * Store a blessed box in currentBox var and adds keybindings. * * @param content - Text content * @param escapable=true - Is popup escapable with keys */ function createPopup(content: string | null, escapable = true) { if (content == null) { return; } currentBox = createBox(content); if (escapable) { currentBox.key(["enter", "escape"], function () { removePopup(); }); } screen.append(currentBox); screen.render(); currentBox.focus(); } /** * Handle popup creation event according to selected table cell. * * @param column - Column number to determine content type * @param content - Table cell content */ export function handlePopup(column: number, content: string | null) { switch (column) { case 0: createPopup(strings["protocols"][content]); break; case 1: createPopup(strings["states"][content]); break; case 2: createPopup(strings["queues"]["receiveQueue"]); break; case 3: createPopup(strings["queues"]["sendQueue"]); break; case 4: break; case 5: createPopup(getPortText(content)); break; case 6: createPopup("Wait for Whois...", false); whois(content).then(function (response: string) { removePopup(); createPopup(response); }); break; case 7: createPopup(getPortText(content)); break; case 8: createPopup(getUsersText(content)); break; } } /** * Determine if the content is longer than half of screen height. If so, the popup can shrink. * * @param content - Text content */ function canShrink(content: string): boolean { let maxShrinkSize = Math.floor((Math.floor(screen.lines.length / 2) - 1) / 2); let numberOfLines = content.split(/\r\n|\r|\n/).length; if (numberOfLines < maxShrinkSize) { return true; } else { return false; } } /** * Create a blessed Box object with given content. * * @param {string} content - Text content */ function createBox(content: string): Box { let height = "50%"; let scrollable = true; if (canShrink(content)) { height = "shrink"; scrollable = false; } return Box({ top: "center", left: "center", width: "shrink", height: height, scrollable: scrollable, alwaysScroll: true, keys: true, content: content.trim(), tags: true, border: { type: "line", }, style: { fg: "white", border: { fg: "#f0f0f0", }, }, }); } /** * Get popup text content for ports. * * @param port - Port number */ function getPortText(port: string | null): string { let assignment = strings["ports"][port]; if (assignment == undefined) { return "This port is not assigned"; } let text = "{bold}This port is assigned to:{/bold} " + assignment + "\n"; text += "Note that regardless of a port assignment, it can be used in any way."; return text; } /** * Get popup text content for users. * * @param {Object} users - Users object */ function getUsersText(users: any): string | null { if (users.text == "/") { return null; } var text: string = ""; var length: number = Object.keys(users).length - 1; for (let i = 0; i < length; i++) { if (length > 1) { text += "{bold} - - User " + (i + 1) + " - -{/bold}\n"; } text += "{bold}Name:{/bold} " + users[i].name + "\n"; text += "{bold}PID:{/bold} " + users[i].pid + "\n"; text += "{bold}Owner:{/bold} " + users[i].owner + "\n"; text += "{bold}Command:{/bold} " + users[i].cmdline.trim() + "\n"; if (i < length - 1) { text += "\n\n"; } } return text; } /** * Display loading popup. */ export function loadingPopup() { createPopup("Loading{blink}...{/blink}", false); }
PabloLec/neoss
src/utils/users.ts
<reponame>PabloLec/neoss<gh_stars>10-100 import { readdirSync, readFileSync, readlinkSync } from "fs"; import { execSync } from "child_process"; var socketMap: {}; /** * Fetch in-use sockets and query their users statistics. * * @returns Map of used sockets and their users */ export async function getUsedSockets(): Promise<{}> { socketMap = {}; var processes: string[] = []; var files: string[] = readdirSync("/proc/"); files.forEach((file: any) => { if (isNumeric(file)) { processes.push(file); } }); var procPromises: Promise<any>[] = []; processes.forEach((proc, i) => { procPromises.push(Promise.race([timeout(100), getProcSockets(proc)])); }); await Promise.allSettled(procPromises); return socketMap; } /** * Get users statistics for a given socket. * * @param proc - Socket inode */ async function getProcSockets(proc: string) { let fd = "/proc/" + proc + "/fd/"; try { var files = readdirSync(fd); } catch (EACCES) { return; } var sockets: string[] = []; files.forEach((file: string) => { try { var linkString = readlinkSync(fd + file); } catch (ENOENT) { return; } if (linkString && linkString.includes("socket")) { var match: RegExpMatchArray | null = linkString.match(/socket\:\[([0-9]+)\]/); if (match != null) { sockets.push(match[1]); } } }); sockets.forEach((socket) => { if (socket in socketMap) { socketMap[socket].push(proc); } else { socketMap[socket] = [proc]; } }); } /** * Get detailed information about given user. * * @param user - User PID * @returns - User name, owner and init command line */ export async function getUserData(user: string): Promise<string[]> { try { var status: string = readFileSync("/proc/" + user + "/status", "utf8"); } catch (ENOENT) { return ["error", "error", "error"]; } let lines = status.split(/\r\n|\r|\n/); let name = lines[0].trim().split(/\s+/)[1]; let uid = lines[9].trim().split(/\s+/)[1]; let owner = execSync("id -nu " + uid) + ""; let cmdline: string; try { let cmdlineFile: string = readFileSync("/proc/" + user + "/cmdline", "utf8"); cmdline = cmdlineFile.split("\0").join(" "); } catch (ENOENT) { cmdline = "Unable to retrieve cmdline. Process already terminated."; } return [name, owner.trim(), cmdline]; } /** * Check if file descriptor name is numeric to determine if it is related to a process. * * @param str - File name * @returns - Is numeric */ function isNumeric(str: string): boolean { return !isNaN(parseInt(str)); } /** * Timeout function to limit fs wait time. * * @param ms - Time to wait in ms * @returns - void */ function timeout(ms: number): Promise<void> { return new Promise((resolve: any) => setTimeout(resolve, ms)); }
PabloLec/neoss
src/ui/screen.ts
<gh_stars>10-100 #!/usr/bin/env node import { Screen } from "neo-blessed"; import Table from "../ui/table"; import { setDefaultScreen } from "../ui/popups"; var mainScreen: Screen; var table: Table; /** * Create main application blessed screen and table objects. */ export function initialize() { mainScreen = Screen({ smartCSR: true, }); mainScreen.title = "neoss"; mainScreen.key(["escape", "q", "C-c"], function () { return process.exit(0); }); setDefaultScreen(mainScreen); table = Table({ keys: true, interactive: true, tags: true, top: "0", left: "center", width: "100%", height: "shrink", border: { type: "line", }, style: { fg: "white", border: { fg: "white", }, focus: { bg: "blue", }, header: { fg: "black", bg: "white", }, }, }); } /** * Set new data as table content. */ export function setData(data: string[]) { mainScreen.append(table); table.setData({ headers: ["Protocol", "State", "Rx", "Tx", "Local Address", "Local Port", "Peer Address", "Peer Port", "Users"], data: data, }); } /** * Refresh screen with data currently stored in table for async results. */ export function refreshScreen() { table.setData(table.table); }
PabloLec/neoss
src/utils/sockets.ts
import { readFileSync } from "fs"; var sockets = {}; /** * Drive async workflow for socket file descriptors acquisition. * * @returns - Sockets map {inode:statistics,} */ export async function getSockets(): Promise<{}> { let promises: Promise<void>[] = []; promises.push(readProcFile("tcp")); promises.push(readProcFile("udp")); promises.push(readProcFile("tcp6")); promises.push(readProcFile("udp6")); await Promise.all(promises); return sockets; } /** * Parse file content data for relevant socket statistics. * * @param data - Raw file text content * @param type - Transport protocol and version number */ function parseSockets(data: string, type: string) { let lines = data.split(/\r\n|\r|\n/); lines.shift(); for (let line of lines) { if (!line) { continue; } let elements = line.trim().split(/\s+/); let inode = elements[9]; sockets[inode] = {}; sockets[inode].protocol = type.slice(0, 3); sockets[inode].state = formatState(elements[3]); [sockets[inode].receiveQueue, sockets[inode].sendQueue] = formatRxTx(elements[4]); if (type.includes("6")) { [sockets[inode].localAddress, sockets[inode].localPort] = formatIPv6(elements[1]); [sockets[inode].peerAddress, sockets[inode].peerPort] = formatIPv6(elements[2]); } else { [sockets[inode].localAddress, sockets[inode].localPort] = formatIPv4(elements[1]); [sockets[inode].peerAddress, sockets[inode].peerPort] = formatIPv4(elements[2]); } if (sockets[inode].localAddress == null || sockets[inode].peerAddress == null) { // Remove sockets with unkown addresses delete sockets[inode]; continue; } else if (sockets[inode].localAddress == sockets[inode].peerAddress || sockets[inode].peerAddress == "localhost") { // Remove loopback sockets delete sockets[inode]; continue; } sockets[inode].users = {}; sockets[inode].inode = inode; } } /** * Format unix hex representation of IPv4 to its regular expression. * * @param line - Raw hex representation * @returns - Formated address */ function formatIPv4(line: string): (string | null)[] { let lineMap = line.split(":"); let hexAddress = lineMap[0]; let hexPort = lineMap[1]; let hexArray = hexAddress .split(/(..)/g) .filter((s: any) => s) .map(hexToDecimal); hexArray.reverse(); let address: string | null; if (parseInt(hexArray.join("")) == 0) { // Catch undefined addresses address = null; } else { address = hexArray.join("."); } let port = hexToDecimal(hexPort) + ""; return [address, port]; } /** * Format unix hex representation of IPv6 to its regular expression. * * @param line - Raw hex representation * @returns - Formated address */ function formatIPv6(line: string): (string | null)[] { let lineMap = line.split(":"); let hexAddress = lineMap[0]; let hexPort = lineMap[1]; let hexArray = hexAddress.split(/(....)/g).filter((s: string) => s); hexArray.forEach(function (hex: string, i: number) { let splitHex = hex.split(/(..)/g).filter((s: any) => s); splitHex.reverse(); hexArray[i] = splitHex.join(""); }); for (var i = 0; i < hexArray.length; i += 2) { [hexArray[i], hexArray[i + 1]] = [hexArray[i + 1], hexArray[i]]; } let address: string | null; let sum = hexToDecimal(hexArray.join("")); if (sum == 0) { // Catch undefined addresses address = null; } else if (sum == 1) { // Shorten loopback address address = "::1"; } else if (hexArray.slice(0, 6).join("") == "00000000000000000000FFFF") { // Catch IPv4 expressed in IPv6 notation let ipV4Part = hexArray[6] + hexArray[7]; address = ipV4Part .split(/(..)/g) .filter((s: any) => s) .map(hexToDecimal) .join("."); } else { hexArray.forEach(function (hex: string, i: number) { // Notation shortening let hexInt = parseInt(hex, 16) + ""; hexArray[i] = hexInt == "0000" ? "" : hexArray[i]; }); address = hexArray.join(":"); } let port = hexToDecimal(hexPort) + ""; return [address, port]; } /** * Format receiveQueue and sendQueue hex representation to decimal. * * @param line - Raw hex representation * @returns - Decimal values */ function formatRxTx(line: string): string[] { let lineMap = line.split(":"); let rx = hexToDecimal(lineMap[0]) + ""; let tx = hexToDecimal(lineMap[1]) + ""; return [rx, tx]; } /** * Get a definition for socket state from hex value * * @param hex - Raw hex value * @returns - State definition */ function formatState(hex: string): string { let state = ""; switch (hex) { case "01": state = "ESTAB"; break; case "02": state = "SYN_SENT"; break; case "03": state = "SYN_RECV"; break; case "04": state = "FIN_WAIT1"; break; case "05": state = "FIN_WAIT2"; break; case "06": state = "TIME_WAIT"; break; case "07": state = "CLOSED"; break; case "08": state = "CLOSE_WAIT"; break; case "09": state = "LAST_ACK"; break; case "0A": state = "LISTEN"; break; case "0B": state = "CLOSING"; break; case "0C": state = "NEW_SYN_RECV"; break; } return state; } /** * Read process file content and initiate its parsing. * * @param file - File name (process inode) */ async function readProcFile(file: string) { let content = readFileSync("/proc/net/" + file, "utf8"); parseSockets(content, file); } /** * Convert a hex string representation to its decimal value. * * @param str - Hex string representation * @returns - Decimal value */ function hexToDecimal(str: string): number { return parseInt(Number("0x" + str) + "", 10); }
PabloLec/neoss
src/utils/getStats.ts
<filename>src/utils/getStats.ts import { reverse } from "dns"; import { setData, refreshScreen } from "../ui/screen"; import { getSockets } from "./sockets"; import { getUsedSockets, getUserData } from "./users"; import { sortBy } from "./helper"; import { loadingPopup, removePopup } from "../ui/popups"; var usedSockets: {}; var socketList: any[] = []; /** * Drive async workflow for full socket statistics acquisition. */ export async function getStats() { let socketListPromise: Promise<{}> = getSockets(); let usedSocketsPromise: Promise<{}> = getUsedSockets(); let usersPromises: Promise<void>[] = []; loadingPopup(); await Promise.all([socketListPromise, usedSocketsPromise]).then(function ([socketListResult, usedSocketsResult]) { usedSockets = usedSocketsResult; let i: number = 0; for (let socket in socketListResult) { socketList[i] = socketListResult[socket]; if (socket in usedSockets) { usersPromises.push(parseUsersData(socket, i)); } else { socketList[i].users.text = "/"; } i++; } }); await Promise.all(usersPromises); setData(sortBy(null, socketList)); removePopup(); reverseNSLookup(); } /** * Create user objects for raw string data. * * @param socket - Socket to parse user(s) from * @param i - Index in socket list */ async function parseUsersData(socket: string, i: number) { for (let j = 0; j < usedSockets[socket].length; j++) { socketList[i].users[j] = {}; socketList[i].users[j].pid = usedSockets[socketList[i].inode][j]; let userData: string[] = await getUserData(socketList[i].users[j].pid); socketList[i].users[j].name = userData[0]; socketList[i].users[j].owner = userData[1]; socketList[i].users[j].cmdline = userData[2]; } if (usedSockets[socketList[i].inode].length == 1) { socketList[i].users.text = socketList[i].users[0].name; } else { socketList[i].users.text = usedSockets[socketList[i].inode].length + " users"; } } /** * Query reverse lookups for all stored IPs. */ async function reverseNSLookup() { for (let i = 0; i < socketList.length; i++) { try { reverse(socketList[i].peerAddress, (err: Error | void | null, result: string[]) => { if (!err) { if (result.length == 0 || result[0].length == 0) { return; } socketList[i].peerAddress = result[0]; refreshScreen(); } }); } catch { continue; } } }
PabloLec/neoss
src/utils/helper.ts
var lastSort: number; var lastScroll: any; var ascending = false; /** * Try to retrieve previously selected line after table refresh. * * @param socket - Socket object to be retrieved * @param data - Refreshed table data to be parsed * @param currentIndex - Current selected line number, returned if no match * @returns Line number to be highlighted */ export function retrieveSocket(socket: any, data: string, currentIndex: number): number { if (socket == null) { return currentIndex; } let i = 0; while (i < data.length) { let l: any = data[i]; let s: any = socket; if (s.inode != "0" && s.inode == l.inode) { currentIndex = i; break; } else if ( s.localAddress == l.localAddress && s.localPort == l.localPort && s.peerAddress == l.peerAddress && s.peerPort == l.peerPort ) { currentIndex = i; break; } i++; } return currentIndex; } /** * Handle socket sort. * * @param column Currently selected column * @param data Table data * @returns Sorted data */ export function sortBy(column: number | null, data: string[]): string[] { if (column == null && lastSort == null) { return data; } else if (column == null) { column = lastSort; } else if (lastSort == column) { ascending = !ascending; } lastSort = column; const sort = (key: string, numeric = false) => { if (ascending && numeric) { data.sort((a: string, b: string) => (parseInt(a[key]) > parseInt(b[key]) ? 1 : -1)); } else if (!ascending && numeric) { data.sort((a: string, b: string) => (parseInt(a[key]) < parseInt(b[key]) ? 1 : -1)); } else if (key == "users" && ascending) { data.sort((a: string, b: string) => (a[key].text > b[key].text ? 1 : -1)); } else if (key == "users") { data.sort((a: string, b: string) => (a[key].text < b[key].text ? 1 : -1)); } else if (ascending) { data.sort((a: string, b: string) => (a[key] > b[key] ? 1 : -1)); } else { data.sort((a: string, b: string) => (a[key] < b[key] ? 1 : -1)); } }; switch (column) { case 0: sort("protocol"); break; case 1: sort("state"); break; case 2: sort("receiveQueue", true); break; case 3: sort("sendQueue", true); break; case 4: sort("localAddress"); break; case 5: sort("localPort", true); break; case 6: sort("peerAddress"); break; case 7: sort("peerPort", true); break; case 8: sort("users"); break; } return data; } /** * Get lines index range to be displayed after scroll. * * @param row - Currently selected line index * @param screenLines - Complete array of table lines * @returns - Lines index range to be displayed */ export function getScroll(row: number, screenLines: number): number[] { if (lastScroll === undefined) { lastScroll = [0, screenLines - 1]; } let newScroll = lastScroll; let diff: number; if (row >= lastScroll[0] && row < lastScroll[1]) { newScroll = lastScroll; } else if (row < lastScroll[0]) { diff = lastScroll[0] - row; newScroll = [lastScroll[0] - diff, lastScroll[1] - diff]; } else if (row >= lastScroll[1]) { diff = row - lastScroll[1] + 1; newScroll = [lastScroll[0] + diff, lastScroll[1] + diff]; } lastScroll = newScroll; return newScroll; }
PabloLec/neoss
src/main.ts
#!/usr/bin/env node import { initialize } from "./ui/screen"; import { getStats } from "./utils/getStats"; initialize(); getStats();
PabloLec/neoss
src/utils/whois.ts
import whoisJson = require("whois-json"); /** * Perform a whois on given domain or IP. * * @param domain - Address to be considered * @returns - Formated text for popup content */ export async function whois(domain: any): Promise<string> { // TODO: Parse reserved IP adresses let domainName = domain.split("."); if (domainName.some(isNaN)) { domainName = domainName.slice(-2).join("."); } else { domainName = domain; } let data = await whoisJson(domainName); data = toString(data); if (data.includes("no entries")) { return "No entries found."; } return data; } /** * Format json key:value pairs to text for popup content. * * @param data - Raw whois object * @returns - Text to be displayed */ function toString(data: any): string { let text: string = ""; for (const key in data) { text += `${key}: ${data[key]}\n`; } return text; }
Nauss/battlesnake
src/utils.ts
import { Coord, Moves } from './types' export const check = ({ position, direction, checkFunction, }: { position: Coord direction: string checkFunction: (position: Coord) => boolean }): boolean => { let actualPosition = { ...position } switch (direction) { case 'up': { actualPosition.y += 1 break } case 'down': { actualPosition.y -= 1 break } case 'left': { actualPosition.x -= 1 break } case 'right': { actualPosition.x += 1 break } } if (checkBound(actualPosition)) return checkFunction(actualPosition) return false } export const checkBound = (position: Coord): boolean => position.y < global.board.height && position.y >= 0 && position.x >= 0 && position.x < global.board.width export const removePossible = (moves: Moves, move: string) => { const index = moves.indexOf(move) if (index !== -1) moves.splice(index, 1) } export const forEachMove = (moves: Moves, func: (move: string) => void) => { for (let index = moves.length - 1; index >= 0; index--) { func(moves[index]) } } // export const checkUp = ({ // gameState, // position, // checkFunction, // }: { // gameState: GameState // position: Coord // checkFunction: (position: Coord) => boolean // }) => { // return check({ gameState, position, checkFunction, direction: 'up' }) // } // export const checkDown = ({ // gameState, // position, // checkFunction, // }: { // gameState: GameState // position: Coord // checkFunction: (position: Coord) => boolean // }) => { // return check({ // gameState, // position, // checkFunction, // direction: 'down', // }) // } // export const checkLeft = ({ // gameState, // position, // checkFunction, // }: { // gameState: GameState // position: Coord // checkFunction: (position: Coord) => boolean // }) => { // return check({ // gameState, // position, // checkFunction, // direction: 'left', // }) // } // export const checkRight = ({ // gameState, // position, // checkFunction, // }: { // gameState: GameState // position: Coord // checkFunction: (position: Coord) => boolean // }) => { // return check({ // gameState, // position, // checkFunction, // direction: 'right', // }) // }
Nauss/battlesnake
src/index.ts
<reponame>Nauss/battlesnake import express, { Request, Response } from 'express' import { info, start, move, end } from './logic' const app = express() app.use(express.json()) const port = process.env.PORT || 5143 app.get('/', (req: Request, res: Response) => { res.send(info()) }) app.post('/start', (req: Request, res: Response) => { const { board: { width, height }, } = req.body global.board = { width, height } res.send(start(req.body)) }) app.post('/move', (req: Request, res: Response) => { res.send(move(req.body)) }) app.post('/end', (req: Request, res: Response) => { res.send(end(req.body)) }) // Start the Express server app.listen(port, () => { console.log(`Starting Battlesnake Server at http://0.0.0.0:${port}...`) })
Nauss/battlesnake
src/logic.ts
<reponame>Nauss/battlesnake import { avoidSelf, avoidWalls } from './basic' import { InfoResponse, GameState, MoveResponse, Game, Moves } from './types' export function info(): InfoResponse { console.log('INFO') const response: InfoResponse = { apiversion: '1', author: '', color: '#0bd2e0', head: 'pixel', tail: 'pixel', } return response } export function start(gameState: GameState): void { console.log(`${gameState.game.id} START`) } export function end(gameState: GameState): void { console.log(`${gameState.game.id} END\n`) } export function move(gameState: GameState): MoveResponse { let moves: Moves = ['up', 'down', 'left', 'right'] // Step 0: Don't let your Battlesnake move back on it's own neck avoidSelf(gameState, moves) // TODO: Step 1 - Don't hit walls. avoidWalls(gameState, moves) // TODO: Step 2 - Don't hit yourself. // Use information in gameState to prevent your Battlesnake from colliding with itself. // const mybody = gameState.you.body // TODO: Step 3 - Don't collide with others. // Use information in gameState to prevent your Battlesnake from colliding with others. // TODO: Step 4 - Find food. // Use information in gameState to seek out and find food. // Finally, choose a move from the available safe moves. // TODO: Step 5 - Select a move to make based on strategy, rather than random. const response: MoveResponse = { move: moves[Math.floor(Math.random() * moves.length)], } console.log(`${gameState.game.id} MOVE ${gameState.turn}: ${response.move}`) return response }
Nauss/battlesnake
src/types.d.ts
<gh_stars>0 // See https://docs.battlesnake.com/references/api for all details and examples. export interface InfoResponse { apiversion: string author?: string color?: string head?: string tail?: string version?: string } export interface MoveResponse { move: string shout?: string } export interface Game { id: string ruleset: { name: string; version: string } timeout: number } export interface Coord { x: number y: number } export interface Battlesnake { id: string name: string health: number body: Coord[] latency: string head: Coord length: number // Used in non-standard game modes shout: string squad: string } export interface Board { height: number width: number food: Coord[] snakes: Battlesnake[] // Used in non-standard game modes hazards: Coord[] } export interface GameState { game: Game turn: number board: Board you: Battlesnake } type GlobalBoard = { width: number; height: number } declare global { var board: GlobalBoard } export type Moves = string[]
Nauss/battlesnake
src/basic.ts
<reponame>Nauss/battlesnake<filename>src/basic.ts import { Coord, GameState, Moves } from './types' import { check, forEachMove, removePossible } from './utils' export const avoidSelf = (gameState: GameState, moves: Moves) => { const { you: { body: [head, ...rest], }, } = gameState // Don't move on self const isSelf = (position: Coord) => { console.log({ rest, position }) return rest.some(({ x, y }) => position.x === x && position.y === y) } forEachMove(moves, (move: string) => { if ( check({ position: head, direction: move, checkFunction: isSelf, }) ) removePossible(moves, move) }) } export const avoidWalls = (gameState: GameState, moves: Moves) => { const { you: { head }, board: { width, height }, } = gameState if (head.x === 0) { removePossible(moves, 'left') } else if (head.x === width - 1) { removePossible(moves, 'right') } if (head.y === 0) { removePossible(moves, 'down') } else if (head.y === height - 1) { removePossible(moves, 'up') } }
fregante/webext-pattern-to-regex
index.ts
// Copied from https://github.com/mozilla/gecko-dev/blob/073cc24f53d0cf31403121d768812146e597cc9d/toolkit/components/extensions/schemas/manifest.json#L487-L491 export const patternValidationRegex = /^(https?|wss?|file|ftp|\*):\/\/(\*|\*\.[^*/]+|[^*/]+)\/.*$|^file:\/\/\/.*$|^resource:\/\/(\*|\*\.[^*/]+|[^*/]+)\/.*$|^about:/; const isFirefox = typeof navigator === 'object' && navigator.userAgent.includes('Firefox/'); export const allStarsRegex = isFirefox ? /^(https?|wss?):[/][/][^/]+([/].*)?$/ : /^https?:[/][/][^/]+([/].*)?$/; export const allUrlsRegex = /^(https?|file|ftp):[/]+/; function getRawRegex(matchPattern: string): string { if (!patternValidationRegex.test(matchPattern)) { throw new Error(matchPattern + ' is an invalid pattern, it must match ' + String(patternValidationRegex)); } let [, protocol, host, pathname] = matchPattern.split(/(^[^:]+:[/][/])([^/]+)?/); protocol = protocol .replace('*', isFirefox ? '(https?|wss?)' : 'https?') // Protocol wildcard .replace(/[/]/g, '[/]'); // Escape slashes host = (host ?? '') // Undefined for file:/// .replace(/^[*][.]/, '([^/]+.)*') // Initial wildcard .replace(/^[*]$/, '[^/]+') // Only wildcard .replace(/[.]/g, '[.]') // Escape dots .replace(/[*]$/g, '[^.]+'); // Last wildcard pathname = pathname .replace(/[/]/g, '[/]') // Escape slashes .replace(/[.]/g, '[.]') // Escape dots .replace(/[*]/g, '.*'); // Any wildcard return '^' + protocol + host + '(' + pathname + ')?$'; } export function patternToRegex(...matchPatterns: readonly string[]): RegExp { // No pattern, match nothing https://stackoverflow.com/q/14115522/288906 if (matchPatterns.length === 0) { return /$./; } if (matchPatterns.includes('<all_urls>')) { return allUrlsRegex; } if (matchPatterns.includes('*://*/*')) { return allStarsRegex; } return new RegExp(matchPatterns.map(x => getRawRegex(x)).join('|')); }
Intility/cypress-msal
src/command.ts
/// <reference types="cypress" /> import { CacheKVStore } from "@azure/msal-node" Cypress.Commands.add('login', () => { return cy.task<CacheKVStore>('login').then(response => { Object.entries(response).forEach(([key, value]) => { let cacheKey = key // msal-node internal cache ends the keys with double dash // msal-browser does not, so we need to remove them if (cacheKey.endsWith('--')) { cacheKey = cacheKey.replace('--', '') } sessionStorage.setItem(cacheKey, JSON.stringify(value)) }) }) }) declare global { namespace Cypress { interface Chainable { /** * Custom command to log in using msal test user * @example cy.login() */ login(): Chainable<any> } } }
Intility/cypress-msal
src/index.ts
import { PublicClientApplication, Configuration, DeviceCodeRequest } from '@azure/msal-node' export type RequestsType = { scopes: string[] } async function acquireTokens(requests: RequestsType[], pca: PublicClientApplication) { // check if account is logged in const allAccounts = await pca.getTokenCache().getAllAccounts() if (allAccounts.length < 1) { throw new Error('No accounts after device login.') } // acquire tokens for each request for (let request of requests) { const silentRequest = { ...request, account: allAccounts[0] } await pca.acquireTokenSilent(silentRequest) } } export default function generateLogin(publicClientConfig: Configuration, requests: RequestsType[]) { return async function login() { const pca: PublicClientApplication = new PublicClientApplication(publicClientConfig) try { // ensure cached valid tokens. Will throw if not logged in await acquireTokens(requests, pca) } catch (e: any) { // can't authenticate to keyvault, don't try to initialize login if ( e?.message?.includes('Azure CLI could not be found.') || e?.message?.includes( "Please run 'az login' from a command prompt to authenticate before using this credential." ) ) { throw e } let deviceCodeRequest: DeviceCodeRequest = { ...requests[0], deviceCodeCallback: response => console.log('device code token', response) } // Login with device code and fills the cache with first access token await pca.acquireTokenByDeviceCode(deviceCodeRequest) // get access token for the rest of the scopes await acquireTokens(requests.slice(1), pca) } // return msal cache return pca.getTokenCache().getKVStore() } }
anrgct/ext-saladict
src/content/components/MenuBar/FloatBox.tsx
<gh_stars>0 import React, { FC, Ref, useState, useCallback } from 'react' import { ResizeReporter } from 'react-resize-reporter/scroll' export interface FloatBoxProps { list?: Array<{ key: string; content: React.ReactNode }> /** Box container */ ref?: Ref<HTMLDivElement> /** When a item is selected */ onSelect: (key: string) => any /** When a item is focused */ onFocus?: (e: React.FocusEvent<HTMLButtonElement>) => any /** When a item is blur */ onBlur?: (e: React.FocusEvent<HTMLButtonElement>) => any /** When mouse over on panel */ onMouseOver?: (e: React.MouseEvent<HTMLDivElement>) => any /** When mouse out on panel */ onMouseOut?: (e: React.MouseEvent<HTMLDivElement>) => any /** When ArrowUp key if pressed on the first item */ onArrowUpFirst?: (container: HTMLDivElement) => any /** When ArrowDown key if pressed on the last item */ onArrowDownLast?: (container: HTMLDivElement) => any /** When the panel is about to close */ onClose?: (container: HTMLDivElement) => any /** When box height is changed */ onHeightChanged?: (height: number) => any } /** * A white box */ export const FloatBox: FC<FloatBoxProps> = React.forwardRef( (props: FloatBoxProps, containerRef: React.Ref<HTMLDivElement>) => { const [height, _setHeight] = useState(0) const [width, _setWidth] = useState(0) const updateHeight = useCallback( (newWidth: number, newHeight: number) => { _setWidth(newWidth) _setHeight(newHeight) if (props.onHeightChanged && newHeight !== height) { props.onHeightChanged(newHeight + 20) // plus paddings } }, [props.onHeightChanged] ) return ( <div className="menuBar-FloatBoxContainer" style={{ width, height }} onMouseOver={props.onMouseOver} onMouseOut={props.onMouseOut} > <div className="menuBar-FloatBoxMeasure"> <ResizeReporter reportInit onSizeChanged={updateHeight} /> {!props.list ? ( <div className="lds-ellipsis"> <div></div> <div></div> <div></div> <div></div> </div> ) : ( <div ref={containerRef} className="menuBar-FloatBox"> {props.list.map(item => ( <button key={item.key} className="menuBar-FloatBoxBtn" onFocus={props.onFocus} onBlur={props.onBlur} onClick={e => props.onSelect(e.currentTarget.dataset.key!)} onKeyDown={e => { if (e.key === 'ArrowDown') { e.preventDefault() e.stopPropagation() const $nextLi = e.currentTarget.nextSibling if ($nextLi) { ;($nextLi as HTMLButtonElement).focus() } else if (props.onArrowDownLast) { props.onArrowDownLast( e.currentTarget.parentElement as HTMLDivElement ) } } else if (e.key === 'ArrowUp') { e.preventDefault() e.stopPropagation() const $prevLi = e.currentTarget.previousSibling if ($prevLi) { ;($prevLi as HTMLButtonElement).focus() } else if (props.onArrowUpFirst) { props.onArrowUpFirst( e.currentTarget.parentElement as HTMLDivElement ) } } else if (e.key === 'Escape') { // prevent the dict panel being closed e.preventDefault() e.stopPropagation() if (props.onClose) { props.onClose( e.currentTarget.parentElement as HTMLDivElement ) } } }} data-key={item.key} > {item.content} </button> ))} </div> )} </div> </div> ) } )
anrgct/ext-saladict
src/background/audio-manager.ts
<reponame>anrgct/ext-saladict import { timeout } from '@/_helpers/promise-more' /** * To make sure only one audio plays at a time */ export class AudioManager { private static instance: AudioManager static getInstance() { return AudioManager.instance || (AudioManager.instance = new AudioManager()) } // singleton // eslint-disable-next-line no-useless-constructor private constructor() {} private audio?: HTMLAudioElement reset() { if (this.audio) { this.audio.pause() this.audio.currentTime = 0 this.audio.src = '' this.audio.onended = null } } load(src: string): HTMLAudioElement { this.reset() return (this.audio = new Audio(src)) } async play(src?: string): Promise<void> { if (!src) { this.reset() return } const audio = this.load(src) const onEnd = new Promise(resolve => { audio.onended = resolve }) await audio .play() .then(() => timeout(onEnd, 4000)) .catch(() => {}) } }
anrgct/ext-saladict
src/components/dictionaries/zdic/View.tsx
<reponame>anrgct/ext-saladict import React, { FC } from 'react' import { ZdicResult } from './engine' import { ViewPorps } from '@/components/dictionaries/helpers' import EntryBox from '@/components/EntryBox' export const DictZdic: FC<ViewPorps<ZdicResult>> = ({ result }) => ( <div> {result.map(entry => ( <EntryBox title={entry.title} key={entry.title}> <div dangerouslySetInnerHTML={{ __html: entry.content }} /> </EntryBox> ))} </div> ) export default DictZdic
anrgct/ext-saladict
src/options/components/Entries/Notebook/WebdavModal.tsx
<gh_stars>0 /* eslint-disable no-throw-literal */ import React, { FC, useState, useRef } from 'react' import { Form, Input, Modal, Button, message as antdMsg, notification } from 'antd' import { FormInstance } from 'antd/lib/form' import { ExclamationCircleOutlined } from '@ant-design/icons' import { Service, SyncConfig } from '@/background/sync-manager/services/webdav' import { removeSyncConfig } from '@/background/sync-manager/helpers' import { message } from '@/_helpers/browser-api' import { useTranslate } from '@/_helpers/i18n' import { InputNumberGroup } from '@/options/components/InputNumberGroup' export interface WebdavModalProps { syncConfig?: SyncConfig show: boolean onClose: () => void } type ServiceResponse = undefined | { error: string } export const WebdavModal: FC<WebdavModalProps> = props => { const { t } = useTranslate(['options', 'common']) const [serviceChecking, setServiceChecking] = useState(false) const formRef = useRef<FormInstance>(null) return ( <Modal visible={props.show} title={t('syncService.webdav.title')} onOk={submitForm} onCancel={closeModal} destroyOnClose footer={[ <Button key="delete" type="danger" onClick={deleteService}> {t('common:delete')} </Button>, <Button key="save" type="primary" disabled={false} loading={serviceChecking} onClick={submitForm} > {t('common:save')} </Button>, <Button key="cancel" onClick={closeModal}> {t('common:cancel')} </Button> ]} > <Form ref={formRef} initialValues={props.syncConfig || { duration: 15 }} labelCol={{ span: 5 }} wrapperCol={{ span: 18 }} onFinish={saveService} > <p> {t('syncService.webdav.description')} <a href="http://help.jianguoyun.com/?p=2064" target="_blank" rel="noopener noreferrer" > {t('syncService.webdav.jianguo')} </a> </p> <Form.Item name="url" label={t('syncService.webdav.url')} hasFeedback rules={[ { type: 'url', message: t('form.url_error'), required: true } ]} > <Input /> </Form.Item> <Form.Item name="user" label={t('syncService.webdav.user')}> <Input /> </Form.Item> <Form.Item name="passwd" label={t('syncService.webdav.passwd')}> <Input type="password" /> </Form.Item> <Form.Item name="duration" label={t('syncService.webdav.duration')} extra={t('syncService.webdav.duration_help')} rules={[ { type: 'number', message: t('form.number_error'), required: true } ]} > <InputNumberGroup suffix={t('common:unit.mins')} /> </Form.Item> </Form> </Modal> ) function submitForm() { if (formRef.current) { formRef.current.submit() } } function closeModal() { if (formRef.current && formRef.current.isFieldsTouched()) { Modal.confirm({ title: t('syncService.close_confirm'), icon: <ExclamationCircleOutlined />, okType: 'danger', onOk: props.onClose }) } else { props.onClose() } } function deleteService() { Modal.confirm({ title: t('syncService.delete_confirm'), onOk: () => tryTo(async () => { await removeSyncConfig(Service.id) props.onClose() }) }) } async function saveService() { if (!formRef.current) { if (process.env.DEBUG) { console.error(new Error('Missing form ref when saving service')) } notification.error({ message: 'Error', description: t('syncService.webdav.err_internal') }) return } setServiceChecking(true) const values = formRef.current.getFieldsValue() if (values.url && !values.url.endsWith('/')) { values.url += '/' } try { const initRes = await message.send<'SYNC_SERVICE_INIT', ServiceResponse>({ type: 'SYNC_SERVICE_INIT', payload: { serviceID: Service.id, config: values } }) const initError = initRes?.error if (initError) { if (initError !== 'exist') { throw initError } else if (confirm(t('syncService.webdav.err_exist'))) { const downloadRes = await message.send< 'SYNC_SERVICE_DOWNLOAD', ServiceResponse >({ type: 'SYNC_SERVICE_DOWNLOAD', payload: { serviceID: Service.id, noCache: true } }) if (downloadRes?.error) { throw downloadRes?.error } } } const uploadRes = await message.send< 'SYNC_SERVICE_UPLOAD', ServiceResponse >({ type: 'SYNC_SERVICE_UPLOAD', payload: { op: 'ADD', serviceID: Service.id, force: true } }) if (uploadRes?.error) { throw uploadRes?.error } props.onClose() } catch (error) { const text = typeof error === 'string' ? error : String(error) const description = /^(network|unauthorized|mkcol|parse)$/.test(text) ? t('syncService.webdav.err_' + text) : t('syncService.webdav.err_unknown', { error: text }) notification.error({ message: 'Error', description }) } setServiceChecking(false) } async function tryTo(action: () => any): Promise<void> { try { await action() antdMsg.destroy() antdMsg.success(t('msg_updated')) } catch (error) { notification.error({ message: 'Error', description: error.message }) } } }
anrgct/ext-saladict
test/specs/background/initialization.spec.ts
<gh_stars>0 import { message, storage } from '@/_helpers/browser-api' import { getDefaultConfig } from '@/app-config' import getDefaultProfile from '@/app-config/profiles' import { timer } from '@/_helpers/promise-more' import '@/background/types' import { browser } from '../../helper' window.appConfig = getDefaultConfig() window.activeProfile = getDefaultProfile() window.fetch = jest.fn(() => Promise.resolve({ ok: true, json: () => '' }) ) as any jest.mock('@/app-config/merge-config', () => { const { getDefaultConfig } = require('@/app-config') return { mergeConfig: jest.fn(config => Promise.resolve(config || getDefaultConfig()) ) } }) jest.mock('@/app-config/merge-profile', () => { const { getDefaultProfile } = require('@/app-config/profiles') return { mergeProfile: jest.fn(profile => Promise.resolve(profile || getDefaultProfile()) ) } }) jest.mock('@/background/context-menus', () => { return { init: jest.fn(() => Promise.resolve()) } }) jest.mock('@/background/pdf-sniffer', () => { return { init: jest.fn() } }) jest.mock('@/background/sync-manager', () => { return { startSyncServiceInterval: jest.fn() } }) jest.mock('@/background/server', () => { return { openQSPanel: jest.fn() } }) jest.mock('@/_helpers/check-update', () => { return jest.fn().mockReturnValue(Promise.resolve()) }) jest.doMock('@/_helpers/browser-api', () => { return { message, storage, openURL: jest.fn(() => Promise.resolve()) } }) describe('Initialization', () => { let initMenus: jest.Mock let initPdf: jest.Mock beforeAll(() => { browser.runtime.sendMessage.callsFake(() => Promise.resolve({})) browser.tabs.sendMessage.callsFake(() => Promise.resolve({})) }) beforeEach(() => { browser.flush() jest.resetModules() const contextMenus = require('@/background/context-menus') const pdfSniffer = require('@/background/pdf-sniffer') initMenus = contextMenus.init initPdf = pdfSniffer.init browser.storage.sync.get.callsFake(() => Promise.resolve({})) browser.storage.sync.set.callsFake(() => Promise.resolve()) browser.storage.sync.clear.callsFake(() => Promise.resolve()) browser.storage.local.get.callsFake(() => Promise.resolve({})) browser.storage.local.set.callsFake(() => Promise.resolve()) browser.storage.local.clear.callsFake(() => Promise.resolve()) require('@/background/initialization') }) it('should properly set up', async () => { await timer(0) expect(browser.runtime.onInstalled.addListener.calledOnce).toBeTruthy() expect(browser.runtime.onStartup.addListener.calledOnce).toBeTruthy() expect(browser.notifications.onClicked.addListener.calledOnce).toBeTruthy() expect( browser.notifications.onButtonClicked.addListener.calledOnce ).toBeTruthy() expect(initMenus).toHaveBeenCalledTimes(0) expect(initPdf).toHaveBeenCalledTimes(0) }) describe('onStartup', () => { let checkUpdate: jest.Mock beforeEach(() => { checkUpdate = require('@/_helpers/check-update') }) it('should not check update if last check was just now', async () => { browser.storage.local.get.onFirstCall().returns( Promise.resolve({ lastCheckUpdate: Date.now() }) ) browser.runtime.onStartup.dispatch() await timer(0) expect(checkUpdate).toHaveBeenCalledTimes(0) }) }) })
anrgct/ext-saladict
src/background/sync-manager/__mocks__/helpers.ts
import { empty, Observable } from 'rxjs' const emptyPromise = (): Promise<any> => Promise.resolve() export const setSyncConfig = jest.fn(emptyPromise) export const getSyncConfig = jest.fn(emptyPromise) export const createSyncConfigStream = jest.fn((): Observable<any> => empty()) export const setMeta = jest.fn(emptyPromise) export const getMeta = jest.fn(emptyPromise) export const deleteMeta = jest.fn(emptyPromise) export const setNotebook = jest.fn(emptyPromise) export const getNotebook = jest.fn(emptyPromise)
anrgct/ext-saladict
src/background/windows-manager.ts
<gh_stars>0 import { message, storage } from '@/_helpers/browser-api' import { Word } from '@/_helpers/record-manager' import { isFirefox } from '@/_helpers/saladict' interface WinRect { width: number height: number left: number top: number } const safeUpdateWindow: typeof browser.windows.update = (...args) => browser.windows.update(...args).catch(console.warn as (m: any) => undefined) /** sometimes the top property does not include title bar in Chrome */ const titlebarOffset = async ( type: browser.windows.CreateType ): Promise<number> => { if (isFirefox) return 0 let top = 0 try { const initWin = await browser.windows.create({ top: 0, left: -10, height: window.screen.availHeight, width: 1, focused: false, type }) if (initWin && initWin.id != null) { const testWin = await browser.windows.get(initWin.id) if (testWin) { top = testWin.top || 0 await browser.windows.remove(initWin.id) } } } catch (e) { console.warn(e) } return top } /** * Manipulate main window */ export class MainWindowsManager { /** Main window snapshot */ snapshot: browser.windows.Window | null = null private _titlebar: number | undefined async correctTop(originTop?: number) { if (!originTop) return originTop const offset = this._titlebar == null ? (this._titlebar = await titlebarOffset('normal')) : this._titlebar return originTop - offset } async focus(): Promise<void> { if (this.snapshot && this.snapshot.id != null) { await safeUpdateWindow(this.snapshot.id, { focused: true }) } } async takeSnapshot(): Promise<browser.windows.Window | null> { this.snapshot = null try { const win = await browser.windows.getLastFocused({ windowTypes: ['normal'] }) if (win.focused && win.type === 'normal' && win.state !== 'minimized') { this.snapshot = win } else if (isFirefox) { // Firefox does not support windowTypes in getLastFocused const wins = (await browser.windows.getAll()).filter( win => win.focused && win.type === 'normal' && win.state !== 'minimized' ) if (wins.length === 1) { this.snapshot = wins[0] } else { const focusedWins = wins.filter(win => win.focused) if (focusedWins.length === 1) { this.snapshot = focusedWins[0] } } } } catch (e) { console.warn(e) } return this.snapshot } destroySnapshot(): void { this.snapshot = null } async makeRoomForSidebar( side: 'left' | 'right', sidebarSnapshot: browser.windows.Window | null ): Promise<void> { const mainWin = this.snapshot if (!mainWin || mainWin.id == null) { return } const sidebarWidth = (sidebarSnapshot && sidebarSnapshot.width) || window.appConfig.panelWidth const updateInfo = mainWin.top != null && mainWin.left != null && mainWin.width != null && mainWin.height != null ? { top: await this.correctTop(mainWin.top), left: side === 'right' ? mainWin.left : mainWin.left + sidebarWidth, width: mainWin.width - sidebarWidth, height: mainWin.height, state: 'normal' as 'normal' } : { top: 0, left: side === 'right' ? 0 : sidebarWidth, width: window.screen.availWidth - sidebarWidth, height: window.screen.availHeight, state: 'normal' as 'normal' } if (side === 'right') { // fix a chrome bug by moving 1 extra pixal then to 0 await safeUpdateWindow(mainWin.id, { ...updateInfo, left: updateInfo.left + 1 }) } await safeUpdateWindow(mainWin.id, updateInfo) } async restoreSnapshot(): Promise<void> { if (this.snapshot && this.snapshot.id != null) { await safeUpdateWindow( this.snapshot.id, this.snapshot.state === 'normal' ? { top: await this.correctTop(this.snapshot.top), left: this.snapshot.left, width: this.snapshot.width, height: this.snapshot.height } : { state: this.snapshot.state } ) } } } /** * Manipulate Standalone Quick Search Panel */ export class QsPanelManager { private qsPanelId: number | null = null private snapshot: browser.windows.Window | null = null private isSidebar: boolean = false private mainWindowsManager = new MainWindowsManager() private _titlebar: number | undefined async correctTop(originTop?: number) { if (!originTop) return originTop const offset = this._titlebar == null ? (this._titlebar = await titlebarOffset('popup')) : this._titlebar return originTop - offset } async create(preload?: Word): Promise<void> { this.isSidebar = false let wordString = '' try { if (!preload) { if (window.appConfig.qsPreload === 'selection') { const tab = ( await browser.tabs.query({ active: true, lastFocusedWindow: true }) )[0] if (tab && tab.id) { preload = await message.send<'PRELOAD_SELECTION'>(tab.id, { type: 'PRELOAD_SELECTION' }) } } } if (preload) { wordString = '&word=' + encodeURIComponent(JSON.stringify(preload)) } } catch (e) {} await this.mainWindowsManager.takeSnapshot() const qsPanelRect = window.appConfig.qssaSidebar ? await this.getSidebarRect(window.appConfig.qssaSidebar) : (window.appConfig.qssaRectMemo && (await this.getStorageRect())) || this.getDefaultRect() let qsPanelWin: browser.windows.Window | undefined try { qsPanelWin = await browser.windows.create({ ...qsPanelRect, type: 'popup', url: browser.runtime.getURL( `quick-search.html?sidebar=${window.appConfig.qssaSidebar}${wordString}` ) }) } catch (err) { browser.notifications.create({ type: 'basic', iconUrl: browser.runtime.getURL(`assets/icon-128.png`), title: `Saladict`, message: err.message, priority: 2, eventTime: Date.now() + 5000 }) } if (qsPanelWin && qsPanelWin.id) { if (isFirefox) { // Firefox needs an extra push safeUpdateWindow(qsPanelWin.id, qsPanelRect) } this.qsPanelId = qsPanelWin.id if (window.appConfig.qssaSidebar) { this.isSidebar = true await this.mainWindowsManager.makeRoomForSidebar( window.appConfig.qssaSidebar, qsPanelWin ) } if (!window.appConfig.qsFocus) { await this.mainWindowsManager.focus() } // notify all tabs ;(await browser.tabs.query({})).forEach(tab => { if (tab.id && tab.windowId !== this.qsPanelId) { message.send(tab.id, { type: 'QS_PANEL_CHANGED', payload: this.qsPanelId != null }) } }) } } async getWin(): Promise<browser.windows.Window | null> { if (!this.qsPanelId) { return null } return browser.windows.get(this.qsPanelId).catch(() => null) } async destroy(): Promise<void> { ;(await browser.tabs.query({})).forEach(tab => { if (tab.id && tab.windowId !== this.qsPanelId) { message.send(tab.id, { type: 'QS_PANEL_CHANGED', payload: false }) } }) this.qsPanelId = null this.isSidebar = false this.destroySnapshot() await this.mainWindowsManager.restoreSnapshot() this.mainWindowsManager.destroySnapshot() } isQsPanel(winId?: number): boolean { return winId != null && winId === this.qsPanelId } async hasCreated(): Promise<boolean> { const win = await this.getWin() if (!win) { this.qsPanelId = null } return !!win } async focus(): Promise<void> { if (this.qsPanelId != null) { await safeUpdateWindow(this.qsPanelId, { focused: true }) const [tab] = await browser.tabs.query({ windowId: this.qsPanelId }) if (tab && tab.id) { await message.send(tab.id, { type: 'QS_PANEL_FOCUSED' }) } } } async takeSnapshot(): Promise<void> { if (this.qsPanelId != null) { this.snapshot = await browser.windows .get(this.qsPanelId) .catch(() => null) } } destroySnapshot(): void { this.snapshot = null } async restoreSnapshot(): Promise<void> { // restore main window first so that it will be at the bottom await this.mainWindowsManager.restoreSnapshot() if (this.snapshot != null && this.snapshot.id != null) { await safeUpdateWindow(this.snapshot.id, { top: await this.correctTop(this.snapshot.top), left: this.snapshot.left, width: this.snapshot.width, height: this.snapshot.height }) } else if (this.qsPanelId != null) { await safeUpdateWindow(this.qsPanelId, { focused: true, ...this.getDefaultRect() }) } this.destroySnapshot() } async moveToSidebar(side: 'left' | 'right'): Promise<void> { if (this.qsPanelId != null) { await this.takeSnapshot() await safeUpdateWindow(this.qsPanelId, await this.getSidebarRect(side)) await this.mainWindowsManager.makeRoomForSidebar(side, this.snapshot) } } async toggleSidebar(side: 'left' | 'right'): Promise<void> { if (!(await this.hasCreated())) { return } if (this.isSidebar) { await this.restoreSnapshot() } else { await this.moveToSidebar(side) } this.isSidebar = !this.isSidebar } getDefaultRect(): WinRect { const { qsLocation, qssaHeight } = window.appConfig let qsPanelLeft = 10 let qsPanelTop = 30 const qsPanelWidth = window.appConfig.panelWidth const qsPanelHeight = window.appConfig.qssaHeight switch (qsLocation) { case 'CENTER': qsPanelLeft = (window.screen.availWidth - qsPanelWidth) / 2 qsPanelTop = (window.screen.availHeight - qssaHeight) / 2 break case 'TOP': qsPanelLeft = (window.screen.availWidth - qsPanelWidth) / 2 qsPanelTop = 30 break case 'RIGHT': qsPanelLeft = window.screen.availWidth - qsPanelWidth - 30 qsPanelTop = (window.screen.availHeight - qssaHeight) / 2 break case 'BOTTOM': qsPanelLeft = (window.screen.availWidth - qsPanelWidth) / 2 qsPanelTop = window.screen.availHeight - qsPanelHeight - 10 break case 'LEFT': qsPanelLeft = 10 qsPanelTop = (window.screen.availHeight - qssaHeight) / 2 break case 'TOP_LEFT': qsPanelLeft = 10 qsPanelTop = 30 break case 'TOP_RIGHT': qsPanelLeft = window.screen.availWidth - qsPanelWidth - 30 qsPanelTop = 30 break case 'BOTTOM_LEFT': qsPanelLeft = 10 qsPanelTop = window.screen.availHeight - qsPanelHeight - 10 break case 'BOTTOM_RIGHT': qsPanelLeft = window.screen.availWidth - qsPanelWidth - 30 qsPanelTop = window.screen.availHeight - qsPanelHeight - 10 break } // coords must be integer // plus offset of other screen return { top: Math.round(qsPanelTop + (window.screen['availTop'] || 0)), left: Math.round(qsPanelLeft + (window.screen['availLeft'] || 0)), width: Math.round(qsPanelWidth), height: Math.round(qsPanelHeight) } } /** get saved panel rect */ async getStorageRect(): Promise<WinRect | null> { const { qssaRect } = await storage.local.get<{ qssaRect: WinRect }>( 'qssaRect' ) if (!qssaRect) return null return { ...qssaRect, top: (await this.correctTop(qssaRect.top)) || 0 } } async getSidebarRect(side: 'left' | 'right'): Promise<WinRect> { const panelWidth = (this.snapshot && this.snapshot.width) || window.appConfig.panelWidth const mainWin = this.mainWindowsManager.snapshot return mainWin && mainWin.state === 'normal' && mainWin.top != null && mainWin.left != null && mainWin.width != null && mainWin.height != null ? // coords must be integer { top: Math.round( (await this.mainWindowsManager.correctTop(mainWin.top)) || 0 ), left: Math.round( side === 'right' ? Math.max(mainWin.width - panelWidth, panelWidth) : mainWin.left ), width: Math.round(panelWidth), height: Math.round(mainWin.height) } : { top: 0, left: Math.round( side === 'right' ? window.screen.availWidth - panelWidth : 0 ), width: Math.round(panelWidth), height: Math.round(window.screen.availHeight) } } }
anrgct/ext-saladict
src/options/index.tsx
import './env' import '@/selection' import React from 'react' import ReactDOM from 'react-dom' import { combineLatest } from 'rxjs' import { filter } from 'rxjs/operators' import { AntdRoot, switchAntdTheme } from '@/components/AntdRoot' import { config$$, profile$$, profileIDList$$, GlobalsContext } from './data' import { MainEntry } from './components/MainEntry' import './_style.scss' document.title = 'Saladict Options' let rendered = false const globals = {} as GlobalsContext // Wait all settings loaded so that // we don't have to worry about Form initial state. combineLatest(config$$, profile$$, profileIDList$$) .pipe(filter(arr => arr.every(Boolean))) .subscribe(async ([config, profile, profileIDList]) => { globals.config = config globals.profile = profile globals.profileIDList = profileIDList await switchAntdTheme(config.darkMode) if (!rendered) { globals.dirty = false ReactDOM.render( <AntdRoot> <GlobalsContext.Provider value={globals}> <MainEntry /> </GlobalsContext.Provider> </AntdRoot>, document.getElementById('root') ) rendered = true } })
anrgct/ext-saladict
src/components/Waveform/Waveform.tsx
import * as React from 'react' import classNames from 'classnames' import WaveSurfer from 'wavesurfer.js' import RegionsPlugin from 'wavesurfer.js/dist/plugin/wavesurfer.regions.min.js' import NumberEditor from 'react-number-editor' import { message, storage } from '@/_helpers/browser-api' import { isFirefox } from '@/_helpers/saladict' import { SoundTouch, SimpleFilter, getWebAudioNode } from 'soundtouchjs' interface AnyObject { [index: string]: any } interface WaveformProps { darkMode: boolean } interface WaveformState { blob?: Blob isPlaying: boolean speed: number loop: boolean /** use pitch stretcher */ pitchStretch: boolean } export class Waveform extends React.PureComponent< WaveformProps, WaveformState > { containerRef = React.createRef<HTMLDivElement>() wavesurfer: WaveSurfer | null | undefined region: AnyObject | null | undefined soundTouch: AnyObject | null | undefined soundTouchNode: AnyObject | null | undefined /** Sync Wavesurfer & SoundTouch position */ shouldSTSync: boolean = false /** play when file is loaded */ playOnLoad = true src?: string state: WaveformState = { isPlaying: false, speed: 1, loop: false, pitchStretch: !isFirefox } initSoundTouch = (wavesurfer: WaveSurfer) => { const buffer = wavesurfer.backend.buffer const bufferLength = buffer.length const lChannel = buffer.getChannelData(0) const rChannel = buffer.numberOfChannels > 1 ? buffer.getChannelData(1) : lChannel let seekingDiff = 0 const source = { extract: (target, numFrames, position) => { if (this.shouldSTSync) { // get the new diff seekingDiff = ~~(wavesurfer.backend.getPlayedPercents() * bufferLength) - position this.shouldSTSync = false } position += seekingDiff for (let i = 0; i < numFrames; i++) { target[i * 2] = lChannel[i + position] target[i * 2 + 1] = rChannel[i + position] } return Math.min(numFrames, bufferLength - position) } } this.soundTouch = new SoundTouch(wavesurfer.backend.ac.sampleRate) this.soundTouchNode = getWebAudioNode( wavesurfer.backend.ac, new SimpleFilter(source, this.soundTouch) ) wavesurfer.backend.setFilter(this.soundTouchNode) } initWavesurfer = () => { const wavesurfer = WaveSurfer.create({ container: this.containerRef.current!, waveColor: '#f9690e', progressColor: '#B71C0C', plugins: [RegionsPlugin.create()] }) this.wavesurfer = wavesurfer wavesurfer.enableDragSelection({}) wavesurfer.on('region-created', region => { this.removeRegion() this.region = region }) wavesurfer.on('region-update-end', this.play) wavesurfer.on('region-out', this.onPlayEnd) wavesurfer.on('seek', () => { if (!this.isInRegion()) { this.removeRegion() } this.shouldSTSync = true }) wavesurfer.on('ready', this.onLoad) wavesurfer.on('finish', this.onPlayEnd) } onLoad = () => { if (this.playOnLoad) { this.play() } // reset state this.playOnLoad = true } play = () => { this.setState({ isPlaying: true }) if (this.wavesurfer) { if ( this.state.pitchStretch && this.soundTouchNode && this.wavesurfer.getFilters().length <= 0 ) { this.wavesurfer.backend.setFilter(this.soundTouchNode) } if (this.region && !this.isInRegion()) { this.wavesurfer.play(this.region.start) } else { this.wavesurfer.play() } } this.shouldSTSync = true } pause = () => { this.setState({ isPlaying: false }) if (this.soundTouchNode) { this.soundTouchNode.disconnect() } if (this.wavesurfer) { this.wavesurfer.pause() this.wavesurfer.backend.disconnectFilters() } } togglePlay = () => { this.state.isPlaying ? this.pause() : this.play() } onPlayEnd = () => { // could be region end this.state.loop ? this.play() : this.pause() } updateSpeed = (speed: number) => { this.setState({ speed }) if (speed < 0.1 || speed > 3) { return } if (this.wavesurfer) { this.wavesurfer.setPlaybackRate(speed) if (speed !== 1 && this.state.pitchStretch && !this.soundTouch) { this.initSoundTouch(this.wavesurfer) } if (this.soundTouch) { this.soundTouch.tempo = speed } } this.shouldSTSync = true } toggleLoop = (e: React.ChangeEvent<HTMLInputElement>) => { this.setState({ loop: e.currentTarget.checked }) if (e.currentTarget.checked && !this.state.isPlaying) { this.play() } } togglePitchStretch = (e: React.ChangeEvent<HTMLInputElement>) => { this.updatePitchStretch(e.currentTarget.checked) storage.local.set({ waveform_pitch: e.currentTarget.checked }) } updatePitchStretch = (flag: boolean) => { this.setState({ pitchStretch: flag }) if (flag) { if ( this.state.speed !== 1 && this.soundTouchNode && this.wavesurfer && this.wavesurfer.getFilters().length <= 0 ) { this.wavesurfer.backend.setFilter(this.soundTouchNode) this.shouldSTSync = true } } else { if (this.soundTouchNode) { this.soundTouchNode.disconnect() } if (this.wavesurfer) { this.wavesurfer.backend.disconnectFilters() } } } isInRegion = (region = this.region): boolean => { if (region && this.wavesurfer) { const curTime = this.wavesurfer.getCurrentTime() return curTime >= region.start && curTime <= region.end } return false } removeRegion = () => { if (this.region) { this.region.remove() } this.region = null } reset = () => { this.removeRegion() this.updateSpeed(1) if (this.wavesurfer) { this.wavesurfer.pause() this.wavesurfer.empty() this.wavesurfer.backend.disconnectFilters() } if (this.soundTouch) { this.soundTouch.clear() this.soundTouch.tempo = 1 } if (this.soundTouchNode) { this.soundTouchNode.disconnect() } this.soundTouch = null this.soundTouchNode = null this.shouldSTSync = false } load = (src: string) => { if (src) { if (this.wavesurfer) { this.reset() } else { this.initWavesurfer() } if (this.wavesurfer) { this.wavesurfer.load(src) // https://github.com/katspaugh/wavesurfer.js/issues/1657 if ( this.wavesurfer.backend.ac.state === 'suspended' && this.playOnLoad ) { // fallback new Audio(src).play() } } } else { this.reset() } } async componentDidMount() { message.self.addListener('PLAY_AUDIO', async ({ payload: src }) => { this.load(src) }) message.self .send<'LAST_PLAY_AUDIO'>({ type: 'LAST_PLAY_AUDIO' }) .then(response => { if ( response && response.src && response.timestamp - Date.now() < 10000 ) { this.load(response.src) } else { this.playOnLoad = false this.load( // Nothing to play `https://fanyi.sogou.com/reventondc/synthesis?text=Nothing%20to%20play&speed=1&lang=en&from=translateweb` ) } }) storage.local.get('waveform_pitch').then(({ waveform_pitch }) => { if (waveform_pitch != null) { this.updatePitchStretch(Boolean(waveform_pitch)) } }) } componentWillUnmount() { this.reset() if (this.wavesurfer) { this.wavesurfer.destroy() this.wavesurfer = null } } render() { return ( <div className={classNames('saladict-waveformWrap', 'saladict-theme', { darkMode: this.props.darkMode })} > <div ref={this.containerRef} /> <div className="saladict-waveformCtrl"> <button type="button" className="saladict-waveformPlay" title="Play/Pause" onClick={this.togglePlay} > <div className={`saladict-waveformPlay_FG${ this.state.isPlaying ? ' isPlaying' : '' }`} /> </button> <NumberEditor className="saladict-waveformSpeed" title="Speed" value={this.state.speed} min={0.1} // too low could cause error max={3} step={0.005} decimals={3} onValueChange={this.updateSpeed} /> <label className="saladict-waveformBtn_label" title="Loop"> {this.state.loop ? ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" fill="var(--color-font)" > <path d="M23.242 388.417l162.59 120.596v-74.925h300.281l-.297-240.358-89.555-.239-.44 150.801H185.832l.81-75.934-163.4 120.06z" /> <path d="M490.884 120.747L328.294.15l.001 74.925H28.013l.297 240.358 89.555.239.44-150.801h209.99l-.81 75.934 163.4-120.06z" /> </svg> ) : ( <svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg" fill="var(--color-divider)" > <path d="M 23.242 388.417 L 23.243 388.417 L 23.242 388.418 Z M 23.243 388.418 L 186.642 268.358 L 185.832 344.292 L 283.967 344.292 L 331.712 434.088 L 185.832 434.088 L 185.832 509.013 Z M 395.821 344.292 L 396.261 193.491 L 485.816 193.73 L 486.113 434.088 L 388.064 434.088 L 340.319 344.292 Z" /> <path d="M 490.884 120.747 L 490.883 120.746 L 490.885 120.745 Z M 490.883 120.746 L 327.485 240.805 L 328.295 164.871 L 244.267 164.871 L 196.521 75.075 L 328.295 75.075 L 328.294 0.15 Z M 118.305 164.871 L 117.865 315.672 L 28.31 315.433 L 28.013 75.075 L 141.077 75.075 L 188.823 164.871 Z" /> <rect x="525.825" y="9.264" width="45.879" height="644.398" transform="matrix(0.882947, -0.469472, 0.469472, 0.882947, -403.998657, 225.106232)" /> </svg> )} <input type="checkbox" checked={this.state.loop} onChange={this.toggleLoop} /> </label> {!isFirefox && ( // @TOFIX SoundTouch bug with Firefox <label className="saladict-waveformPitch saladict-waveformBtn_label" title="Pitch Stretch" > <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 467.987 467.987" fill={ this.state.pitchStretch ? 'var(--color-font)' : 'var(--color-divider)' } > <path d="M70.01 146.717h47.924V321.27H70.01zM210.032 146.717h47.924V321.27h-47.924zM350.053 146.717h47.924V321.27h-47.924zM0 196.717h47.924v74.553H0zM280.042 196.717h47.924v74.553h-47.924zM420.063 196.717h47.924v74.553h-47.924zM140.021 96.717h47.924V371.27h-47.924z" /> </svg> <input type="checkbox" checked={this.state.pitchStretch} onChange={this.togglePitchStretch} /> </label> )} </div> </div> ) } } export default Waveform
anrgct/ext-saladict
src/components/dictionaries/urban/View.tsx
<filename>src/components/dictionaries/urban/View.tsx import React, { FC } from 'react' import Speaker from '@/components/Speaker' import { UrbanResult } from './engine' import { ViewPorps } from '@/components/dictionaries/helpers' export const DictUrban: FC<ViewPorps<UrbanResult>> = ({ result }) => ( <ul className="dictUrban-List"> {result.map(def => ( <li key={def.meaning} className="dictUrban-Item"> <h2 className="dictUrban-Title"> {def.title} <Speaker src={def.pron} /> </h2> {def.meaning && ( <p className="dictUrban-Meaning" dangerouslySetInnerHTML={{ __html: def.meaning }} /> )} {def.example && ( <p className="dictUrban-Example" dangerouslySetInnerHTML={{ __html: def.example }} /> )} {def.gif && ( <figure className="dictUrban-Gif"> <img src={def.gif.src} alt={def.gif.attr} /> <figcaption>{def.gif.attr}</figcaption> </figure> )} {def.tags && ( <ul className="dictUrban-Tags"> {def.tags.map(tag => ( <a key={tag} className="dictUrban-TagItem" href={`https://www.urbandictionary.com/tags.php?tag=${tag}`} rel="nofollow noopener noreferrer" > #{tag}{' '} </a> ))} </ul> )} <footer className="dictUrban-Footer"> {def.contributor && ( <span className="dictUrban-Contributor">{def.contributor}</span> )} {def.thumbsUp && ( <span className="dictUrban-Thumbs"> <svg className="dictUrban-IconThumbsUp" width="0.9em" height="0.9em" fill="#666" viewBox="0 0 561 561" > <path d="M0 535.5h102v-306H0v306zM561 255c0-28.05-22.95-51-51-51H349.35l25.5-117.3v-7.65c0-10.2-5.1-20.4-10.2-28.05L336.6 25.5 168.3 193.8c-10.2 7.65-15.3 20.4-15.3 35.7v255c0 28.05 22.95 51 51 51h229.5c20.4 0 38.25-12.75 45.9-30.6l76.5-181.05c2.55-5.1 2.55-12.75 2.55-17.85v-51H561c0 2.55 0 0 0 0z" /> </svg> {def.thumbsUp} </span> )} {def.thumbsDown && ( <span className="dictUrban-Thumbs"> <svg className="dictUrban-IconThumbsDown" width="0.95em" height="0.95em" fill="#666" viewBox="0 0 561 561" > <path d="M357 25.5H127.5c-20.4 0-38.25 12.75-45.9 30.6L5.1 237.15C2.55 242.25 0 247.35 0 255v51c0 28.05 22.95 51 51 51h160.65l-25.5 117.3v7.65c0 10.2 5.1 20.4 10.2 28.05l28.05 25.5 168.3-168.3c10.2-10.2 15.3-22.95 15.3-35.7v-255c0-28.05-22.95-51-51-51zm102 0v306h102v-306H459z" /> </svg> {def.thumbsDown} </span> )} </footer> </li> ))} </ul> ) export default DictUrban
anrgct/ext-saladict
src/content/components/MenuBar/Profiles.tsx
import React, { FC } from 'react' import { TFunction } from 'i18next' import CSSTransition from 'react-transition-group/CSSTransition' import { useObservable, useObservableCallback, useObservableState, identity } from 'observable-hooks' import { merge } from 'rxjs' import { hover, hoverWithDelay, focusBlur } from '@/_helpers/observables' import { getProfileName } from '@/_helpers/profile-manager' import { isOptionsPage } from '@/_helpers/saladict' import { FloatBox } from './FloatBox' import { OptionsBtn } from './MenubarBtns' import { message } from '@/_helpers/browser-api' import { useTranslate } from '@/_helpers/i18n' export interface ProfilesProps { t: TFunction profiles: Array<{ id: string; name: string }> activeProfileId: string onSelectProfile: (id: string) => void onHeightChanged: (height: number) => void } /** * Pick and choose profiles */ export const Profiles: FC<ProfilesProps> = props => { const { t } = useTranslate(['content', 'common']) const [onHoverBtn, onHoverBtn$] = useObservableCallback< boolean, React.MouseEvent<Element> >(hoverWithDelay) const [onHoverBox, onHoverBox$] = useObservableCallback< boolean, React.MouseEvent<Element> >(hover) const [onFocusBlur, focusBlur$] = useObservableCallback(focusBlur) const [showHideProfiles, showHideProfiles$] = useObservableCallback<boolean>( identity ) const isOnBtn = useObservableState(onHoverBtn$, false) const isOnBox = useObservableState( useObservable(() => merge(onHoverBox$, focusBlur$, showHideProfiles$)), false ) const isShowProfiles = isOnBtn || isOnBox const listItem = props.profiles.map(p => { return { key: p.id, content: ( <span className={`menuBar-ProfileItem${ p.id === props.activeProfileId ? ' isActive' : '' }`} > {getProfileName(p.name, t)} </span> ) } }) return ( <div className="menuBar-ProfileContainer"> <OptionsBtn t={t} disabled={isOptionsPage()} onKeyDown={e => { if (e.key === 'ArrowDown') { e.preventDefault() e.stopPropagation() showHideProfiles(true) } }} onMouseOver={onHoverBtn} onMouseOut={onHoverBtn} onClick={() => message.send({ type: 'OPEN_URL', payload: { url: 'options.html', self: true } }) } /> {!isOptionsPage() && ( <CSSTransition classNames="menuBar-Profiles" in={isShowProfiles} timeout={100} mountOnEnter={true} unmountOnExit={true} onExited={() => props.onHeightChanged(0)} > {() => ( <div className="menuBar-ProfileBox"> <FloatBox list={listItem} onFocus={onFocusBlur} onBlur={onFocusBlur} onMouseOver={onHoverBox} onMouseOut={onHoverBox} onArrowUpFirst={container => (container.lastElementChild as HTMLButtonElement).focus() } onArrowDownLast={container => (container.firstElementChild as HTMLButtonElement).focus() } onSelect={props.onSelectProfile} onHeightChanged={props.onHeightChanged} /> </div> )} </CSSTransition> )} </div> ) }
anrgct/ext-saladict
src/components/dictionaries/etymonline/View.tsx
<gh_stars>1-10 import React, { FC } from 'react' import { EtymonlineResult } from './engine' import { ViewPorps } from '@/components/dictionaries/helpers' export const DictEtymonline: FC<ViewPorps<EtymonlineResult>> = ({ result }) => ( <ul className="dictEtymonline-List"> {result.map(item => ( <li key={item.title} className="dictEtymonline-Item"> <h2 className="dictEtymonline-Title"> {item.href ? ( <a href={item.href} target="_blank" rel="nofollow noopener noreferrer" > {item.title} </a> ) : ( item.title )} </h2> <p className="dictEtymonline-Def" dangerouslySetInnerHTML={{ __html: item.def }} /> {item.chart ? ( <img src={item.chart} alt={'Origin of ' + item.title} /> ) : null} </li> ))} </ul> ) export default DictEtymonline
anrgct/ext-saladict
src/options/components/SortableList/index.tsx
<filename>src/options/components/SortableList/index.tsx import React from 'react' import { SortableContainer, SortableHandle, SortableElement, SortEnd as _SortEnd } from 'react-sortable-hoc' import { List, Radio, Button, Card } from 'antd' import { PlusOutlined, SwapOutlined, EditOutlined, CloseOutlined } from '@ant-design/icons' import { RadioChangeEvent } from 'antd/lib/radio' import { Omit } from '@/typings/helpers' import { useTranslate } from '@/_helpers/i18n' import './_style.scss' export type SortEnd = _SortEnd export type SortableListItem = { value: string; title: React.ReactNode } export interface SortableListItemProps { indexCopy: number selected?: string item: SortableListItem disableEdit?: (index: number, item: SortableListItem) => boolean onEdit?: (index: number, item: SortableListItem) => void onDelete?: (index: number, item: SortableListItem) => void } export interface SortableListProps extends Omit<SortableListItemProps, 'item' | 'indexCopy'> { /** List title */ title: React.ReactNode description?: React.ReactNode list: SortableListItem[] /** List Item can be selected */ selected?: string /** show add button */ isShowAdd?: boolean onAdd?: () => void /** Title being selected */ onSelect?: (e: RadioChangeEvent) => void onSortEnd?: (end: SortEnd) => void } const DragHandle = React.memo( SortableHandle(() => { const { t } = useTranslate('common') return ( <SwapOutlined rotate={90} title={t('sort')} style={{ cursor: 'move' }} /> ) }) ) const ProfileListItem = SortableElement( ({ selected, item, disableEdit, onEdit, onDelete, indexCopy }: SortableListItemProps) => { const { t } = useTranslate('options') return ( <List.Item> <div className="sortable-list-item"> {selected == null ? ( item.title ) : ( <Radio value={item.value}>{item.title}</Radio> )} <div> <DragHandle /> <Button className="sortable-list-item-btn" title={t('common:edit')} shape="circle" size="small" icon={<EditOutlined />} disabled={disableEdit != null && disableEdit(indexCopy, item)} onClick={onEdit && (() => onEdit(indexCopy, item))} /> <Button title={t('common:delete')} className="sortable-list-item-btn" shape="circle" size="small" icon={<CloseOutlined />} disabled={selected != null && item.value === selected} onClick={onDelete && (() => onDelete(indexCopy, item))} /> </div> </div> </List.Item> ) } ) const SortableListContainer = SortableContainer((props: SortableListProps) => ( <List size="large" dataSource={props.list} renderItem={(item: any, index: number) => ( <ProfileListItem {...props} item={item} index={index} indexCopy={index} /> )} /> )) export function SortableList(props: SortableListProps) { const { t } = useTranslate('common') return ( <Card title={props.title} extra={ <Button type="dashed" size="small" onClick={props.onAdd}> <PlusOutlined /> {t('add')} </Button> } > {props.description} <Radio.Group className="sortable-list-radio-group" value={props.selected} onChange={props.onSelect} > <SortableListContainer useDragHandle {...props} /> </Radio.Group> {(props.isShowAdd == null || props.isShowAdd) && ( <Button type="dashed" style={{ width: '100%' }} onClick={props.onAdd}> <PlusOutlined /> {t('add')} </Button> )} </Card> ) } /** * Changes the contents of an array by moving an element to a different position */ export function arrayMove<T extends any[]>( arr: T, from: number, to: number ): T { arr.splice(to < 0 ? arr.length + to : to, 0, arr.splice(from, 1)[0]) return arr }
anrgct/ext-saladict
src/content/components/MenuBar/Suggest.tsx
import React, { FC } from 'react' import { useObservable, useObservableState } from 'observable-hooks' import { from } from 'rxjs' import { map, filter, distinctUntilChanged, switchMap, debounceTime, startWith } from 'rxjs/operators' import { message } from '@/_helpers/browser-api' import { FloatBox, FloatBoxProps } from './FloatBox' export interface SuggestItem { explain: string entry: string } export type SuggestProps = { /** Search box text */ text: string } & Pick< FloatBoxProps, | 'ref' | 'onFocus' | 'onBlur' | 'onSelect' | 'onArrowUpFirst' | 'onClose' | 'onHeightChanged' > /** * Suggest panel offering similar words. */ export const Suggest: FC<SuggestProps> = React.forwardRef( (props: SuggestProps, ref: React.Ref<HTMLDivElement>) => { return useObservableState( useObservable( inputs$ => inputs$.pipe( map(([text]) => text), filter<string>(Boolean), distinctUntilChanged(), debounceTime(750), switchMap(text => from( message .send<'GET_SUGGESTS'>({ type: 'GET_SUGGESTS', payload: text }) .catch(() => [] as readonly SuggestItem[]) ).pipe( map(suggests => ( <FloatBox ref={ref} list={suggests.map(s => ({ key: s.entry, content: ( <> <span className="menuBar-SuggestsEntry"> {s.entry} </span> <span className="menuBar-SuggestsExplain"> {s.explain} </span> </> ) }))} {...props} /> )), startWith(<FloatBox {...props} />) ) ), startWith(<FloatBox {...props} />) ), [props.text] ) )! } )
anrgct/ext-saladict
src/components/dictionaries/baidu/engine.ts
<gh_stars>0 import { MachineTranslateResult, SearchFunction, MachineTranslatePayload, GetSrcPageFunction, getMTArgs } from '../helpers' import memoizeOne from 'memoize-one' import { Baidu } from '@opentranslate/baidu' import { BaiduLanguage } from './config' export const getTranslator = memoizeOne( () => new Baidu({ env: 'ext', config: process.env.BAIDU_APPID && process.env.BAIDU_KEY ? { appid: process.env.BAIDU_APPID, key: process.env.BAIDU_KEY } : undefined }) ) export const getSrcPage: GetSrcPageFunction = (text, config, profile) => { const lang = profile.dicts.all.baidu.options.tl === 'default' ? config.langCode === 'zh-CN' ? 'zh' : config.langCode === 'zh-TW' ? 'cht' : 'en' : profile.dicts.all.baidu.options.tl return `https://fanyi.baidu.com/#auto/${lang}/${text}` } export type BaiduResult = MachineTranslateResult<'baidu'> export const search: SearchFunction< BaiduResult, MachineTranslatePayload<BaiduLanguage> > = async (rawText, config, profile, payload) => { const translator = getTranslator() const { sl, tl, text } = await getMTArgs( translator, rawText, profile.dicts.all.baidu, config, payload ) const appid = config.dictAuth.baidu.appid const key = config.dictAuth.baidu.key const translatorConfig = appid && key ? { appid, key } : undefined try { const result = await translator.translate(text, sl, tl, translatorConfig) return { result: { id: 'baidu', sl: result.from, tl: result.to, langcodes: translator.getSupportLanguages(), searchText: result.origin, trans: result.trans }, audio: { py: result.trans.tts, us: result.trans.tts } } } catch (e) { return { result: { id: 'baidu', sl, tl, langcodes: translator.getSupportLanguages(), searchText: { paragraphs: [''] }, trans: { paragraphs: [''] } } } } }
anrgct/ext-saladict
src/content/components/SaladBowl/SaladBowl.tsx
<filename>src/content/components/SaladBowl/SaladBowl.tsx import React, { FC } from 'react' import { useSubscription, useObservableCallback } from 'observable-hooks' import { hoverWithDelay } from '@/_helpers/observables' import { SALADICT_EXTERNAL } from '@/_helpers/saladict' export interface SaladBowlProps { /** Viewport based coordinate. */ readonly x: number /** Viewport based coordinate. */ readonly y: number /** Play animation. */ readonly withAnimation: boolean /** React on hover. */ readonly enableHover: boolean /** When bowl is activated via mouse. */ readonly onActive: () => void readonly onHover: (isHover: boolean) => void } /** * Cute little icon that pops up near the selection. */ export const SaladBowl: FC<SaladBowlProps> = props => { const [onMouseOverOut, mouseOverOut$] = useObservableCallback< boolean, React.MouseEvent<HTMLDivElement> >(hoverWithDelay) useSubscription(mouseOverOut$, active => { props.onHover(active) if (active) { props.onActive() } }) return ( <div role="img" className={ `saladbowl ${SALADICT_EXTERNAL}` + (props.withAnimation ? ' isAnimate' : '') + (props.enableHover ? ' enableHover' : '') } style={{ transform: `translate(${props.x}px, ${props.y}px)` }} onMouseOver={props.enableHover ? onMouseOverOut : undefined} onMouseOut={onMouseOverOut} onClick={() => props.onActive()} > {/* prettier-ignore */} <svg viewBox='0 0 612 612' width='30' height='30'> <g className='saladbowl-leaf'> <path fill='#6bbc57' d='M 577.557 184.258 C 560.417 140.85 519.54 59.214 519.54 59.214 L 519.543 59.204 C 519.543 59.204 436.903 97.626 396.441 120.878 C 366.171 138.274 354.981 169.755 352.221 177.621 C 349.001 186.851 339.891 228.811 358.341 268.481 C 382.271 319.921 409.201 374.521 409.201 374.521 L 409.201 374.531 C 409.201 374.531 464.511 348.701 515.291 323.401 C 554.451 303.891 573.591 265.441 576.821 256.221 C 579.571 248.356 590.398 216.746 577.574 184.271 Z'/> <path fill='#bde9b7' d='M 501.052 102.162 L 507.518 104.425 L 426.69 335.38 L 420.224 333.117 Z'/> </g> <g className='saladbowl-orange'> <circle fill='#ffb30d' cx='299.756' cy='198.246' r='178.613'/> <circle fill='#fce29c' cx='299.756' cy='198.246' r='155.24'/> <path fill='#fcc329' d='M 299.756 189.873 L 341.269 113.475 C 349.169 82.543 324.349 58.588 299.749 57.891 C 275.149 57.201 248.229 82.781 256.489 113.481 L 299.749 189.881 Z M 307.026 194.757 L 393.974 194.757 C 424.928 187.083 434.124 153.681 422.994 131.737 C 411.864 109.795 376.534 98.357 353.5 120.27 L 307.025 194.757 Z M 308.79 203.444 L 354.885 277.168 C 377.925 299.268 410.995 289.438 423.701 268.368 C 436.411 247.298 427.381 211.276 396.591 203.362 L 308.801 203.442 Z M 300.208 206.618 L 259.628 283.516 C 252.098 314.543 277.214 338.193 301.815 338.591 C 326.415 338.991 353.022 313.081 344.392 282.491 L 300.208 206.631 Z M 292.058 203.3 L 205.108 203.415 C 174.163 211.277 165.014 244.54 176.172 266.468 C 187.33 288.396 226.052 300.541 249.056 278.598 L 292.056 203.301 Z M 292.465 194.83 L 246.497 121.024 C 223.494 98.884 190.409 108.658 177.667 129.706 C 164.925 150.753 173.893 186.791 204.669 194.756 L 292.459 194.829 Z'/> </g> <g className='saladbowl-tomato'> <path fill='#a63131' d='M 71.014 337.344 C 147.291 422.594 278.234 429.866 363.482 353.589 L 87.258 44.87 C 2.01 121.15 -5.262 252.092 71.014 337.342 Z'/> <path fill='#bc5757' d='M 101.447 310.115 C 162.685 378.555 267.811 384.393 336.251 323.155 L 114.49 75.31 C 46.047 136.55 40.21 241.674 101.447 310.115 Z'/> <path fill='#f1d4af' d='M 186.412 237.54 L 151.659 245.444 C 139.989 251.384 139.339 265.51 145.779 273.27 C 152.219 281.028 167.379 282.39 174.599 271.538 L 186.399 237.54 Z M 242.062 269.832 L 223.366 300.175 C 219.439 312.658 229.066 323.018 239.116 323.85 C 249.168 324.685 260.756 314.815 258.061 302.065 L 242.061 269.832 Z M 160.202 178.317 L 130.357 158.837 C 117.98 154.585 107.375 163.939 106.277 173.965 C 105.183 183.99 114.747 195.833 127.563 193.471 L 160.203 178.321 Z'/> </g> <g className='saladbowl-bowl'> <path fill='#2d97b7' d='M 30.857 311.46 C 30.857 429.87 105.371 530.8 209.867 569.52 L 209.867 589.2 L 400.987 589.2 L 400.987 568.9 C 503.595 530.114 576.887 431.202 578.31 314.907 L 589.196 295.97 L 22.804 295.97 L 30.867 309.998 C 30.865 310.488 30.857 310.971 30.857 311.458 Z'/> <path fill='#fff' d='M 540.565 321.42 C 540.585 322.587 540.595 323.755 540.595 324.927 C 540.595 405.941 497.513 476.884 433.015 516.122 L 437.178 523.317 C 504.152 482.64 548.895 409.009 548.895 324.927 C 548.895 323.755 548.885 322.587 548.865 321.419 Z M 399.885 532.68 C 388.298 537.31 376.237 541.002 363.793 543.654 L 363.793 544.45 L 364.971 551.893 C 378.481 549.049 391.551 545.018 404.081 539.935 Z'/> </g> </svg> </div> ) }
anrgct/ext-saladict
src/background/clipboard-manager.ts
export function copyTextToClipboard(text: string): void { const copyFrom = document.createElement('textarea') copyFrom.textContent = text document.body.appendChild(copyFrom) copyFrom.select() document.execCommand('copy') copyFrom.blur() document.body.removeChild(copyFrom) } export function getTextFromClipboard(): string { if (process.env.NODE_ENV === 'development') { return 'clipboard content' } else { let el = document.getElementById( 'saladict-paste' ) as HTMLTextAreaElement | null if (!el) { el = document.createElement('textarea') el.id = 'saladict-paste' document.body.appendChild(el) } el.value = '' el.focus() document.execCommand('paste') return el.value || '' } }
anrgct/ext-saladict
src/_helpers/__mocks__/browser-api.ts
<gh_stars>1-10 /** * @file Wraps some of the extension apis */ import { Observable, fromEventPattern } from 'rxjs' import { map } from 'rxjs/operators' import { Message } from '@/typings/message' /* --------------------------------------- *\ * #Types \* --------------------------------------- */ export type StorageArea = 'all' | 'local' | 'sync' export type StorageListenerCb = ( changes: browser.storage.StorageChange, areaName: string ) => void type onMessageEvent = ( message: Message, sender: browser.runtime.MessageSender, sendResponse: Function ) => Promise<any> | boolean | void /* --------------------------------------- *\ * #Globals \* --------------------------------------- */ const noop = () => { /* do nothing */ } // share the listener so that it can be manipulated manually declare global { interface Window { __messageListeners__: Map< onMessageEvent, Map<Message['type'], onMessageEvent> > __messageSelfListeners__: Map< onMessageEvent, Map<Message['type'], onMessageEvent> > __storageListeners__: Map<StorageListenerCb, Map<string, StorageListenerCb>> } } /** * key: {function} user's callback function * values: {Map} listeners, key: message type, values: generated or user's callback functions */ window.__messageListeners__ = window.__messageListeners__ || new Map() /** * For self page messaging * key: {function} user's callback function * values: {Map} listeners, key: message type, values: generated or user's callback functions */ window.__messageSelfListeners__ = window.__messageSelfListeners__ || new Map() /** * key: {function} user's callback function * values: {Map} listeners, key: message type, values: generated or user's callback functions */ window.__storageListeners__ = window.__storageListeners__ || new Map() const messageListeners = window.__messageListeners__ const messageSelfListeners = window.__messageSelfListeners__ const storageListeners = window.__storageListeners__ /* --------------------------------------- *\ * #Exports \* --------------------------------------- */ export const storage = { sync: { clear: _storageClear(), remove: _storageRemove(), get: _storageGet(), set: _storageSet(), /** Only for sync area */ addListener: _storageAddListener('sync'), /** Only for sync area */ removeListener: _storageRemoveListener('sync'), createStream: noop, dispatch: _dispatchStorageEvent('sync') }, local: { clear: _storageClear(), remove: _storageRemove(), get: _storageGet(), set: _storageSet(), /** Only for local area */ addListener: _storageAddListener('local'), /** Only for local area */ removeListener: _storageRemoveListener('local'), createStream: noop, dispatch: _dispatchStorageEvent('local') }, /** Clear all area */ clear: _storageClear(), addListener: _storageAddListener('all'), removeListener: _storageRemoveListener('all'), createStream: noop as ReturnType<typeof _storageCreateStream>, dispatch: dispatchStorageEvent } storage.sync.createStream = _storageCreateStream('sync') storage.local.createStream = _storageCreateStream('local') storage.createStream = _storageCreateStream('all') /** * Wraps in-app runtime.sendMessage and tabs.sendMessage * Does not warp cross extension messaging! */ export const message = { send: _messageSend(false), addListener: _messageAddListener(false), removeListener: _messageRemoveListener(false), createStream: noop, dispatch: _dispatchMessageEvent(false), self: { initClient: jest.fn(() => Promise.resolve()), initServer: jest.fn(noop), send: _messageSend(true), addListener: _messageAddListener(true), removeListener: _messageRemoveListener(true), createStream: noop, dispatch: _dispatchMessageEvent(true) } } message.createStream = _messageCreateStream(false) message.self.createStream = _messageCreateStream(true) /** * Open a url on new tab or highlight a existing tab if already opened */ export const openURL = jest.fn(() => Promise.resolve()) export default { openURL, storage, message } /* --------------------------------------- *\ * #Storage \* --------------------------------------- */ function _storageClear() { return jest.fn(storageClear) function storageClear(): Promise<void> { return Promise.resolve() } } function _storageRemove() { return jest.fn(storageRemove) function storageRemove(keys: string | string[]): Promise<void> { return Promise.resolve() } } function _storageGet() { return jest.fn(storageGet) function storageGet<T = any>(key?: string | string[] | null): Promise<T> function storageGet<T extends Object>(key: T | any): Promise<T> function storageGet<T = any>(...args): Promise<T> { return Promise.resolve() as any } } function _storageSet() { return jest.fn(storageSet) function storageSet(keys: any): Promise<void> { return Promise.resolve() as any } } function _storageAddListener(area: string) { return jest.fn(storageAddListener) function storageAddListener(cb: StorageListenerCb): void function storageAddListener(key: string, cb: StorageListenerCb): void function storageAddListener(...args): void { let key: string let cb: StorageListenerCb if (typeof args[0] === 'function') { key = '' cb = args[0] } else if (typeof args[0] === 'string' && typeof args[1] === 'function') { key = args[0] cb = args[1] } else { throw new Error('wrong arguments type') } let listeners = storageListeners.get(cb) if (!listeners) { listeners = new Map() storageListeners.set(cb, listeners) } const listenerKey = area + key let listener = listeners.get(listenerKey) if (!listener) { listener = (changes, areaName) => { if ((area === 'all' || areaName === area) && (!key || changes[key])) { cb(changes, areaName) } } listeners.set(listenerKey, listener) } } } function _storageRemoveListener(area: string) { return jest.fn(storageRemoveListener) function storageRemoveListener(key: string, cb: StorageListenerCb): void function storageRemoveListener(cb: StorageListenerCb): void function storageRemoveListener(...args): void { let key: string let cb: StorageListenerCb if (typeof args[0] === 'function') { key = '' cb = args[0] } else if (typeof args[0] === 'string' && typeof args[1] === 'function') { key = args[0] cb = args[1] } else { throw new Error('wrong arguments type') } const listeners = storageListeners.get(cb) if (listeners) { if (key) { // remove 'cb' listeners with 'key' under 'storageArea' const listenerKey = area + key const listener = listeners.get(listenerKey) if (listener) { listeners.delete(listenerKey) if (listeners.size <= 0) { storageListeners.delete(cb) } } } else { // remove all 'cb' listeners under 'storageArea' storageListeners.delete(cb) } } } } function _storageCreateStream(area: string) { return jest.fn(storageCreateStream) function storageCreateStream(key: string) { const obj = area === 'all' ? storage : storage[area] return fromEventPattern( handler => obj.addListener(key, handler as StorageListenerCb), handler => obj.removeListener(key, handler as StorageListenerCb) ).pipe(map((args: any) => (Array.isArray(args) ? args[0][key] : args[key]))) } } interface DispatchStorageEventOptions { /** message key */ key?: string newValue?: any oldValue?: any } interface DispatchStorageEventOptionsGeneral extends DispatchStorageEventOptions { area?: StorageArea | '' } function _dispatchStorageEvent(area: 'sync' | 'local') { const _fn = dispatchStorageEvent return function dispatchStorageEvent(options: DispatchStorageEventOptions) { return _fn(Object.assign(options, { area })) } } export function dispatchStorageEvent( options: DispatchStorageEventOptionsGeneral ): void { storageListeners.forEach(m => { m.forEach((cb, key) => { if (!options.key || options.key === key) { if (!options.area || options.area === 'all') { cb({ newValue: options.newValue, oldValue: options.oldValue }, 'sync') cb( { newValue: options.newValue, oldValue: options.oldValue }, 'local' ) } else { cb( { newValue: options.newValue, oldValue: options.oldValue }, options.area ) } } }) }) } /* --------------------------------------- *\ * #Message \* --------------------------------------- */ function _messageSend(self: boolean) { return jest.fn(self ? messageSendSelf : messageSend) function messageSend(tabId: number, message: Message): Promise<any> function messageSend(message: Message): Promise<any> function messageSend(...args): Promise<any> { return Promise.resolve() } function messageSendSelf(message: Message): Promise<any> { return Promise.resolve() } } function _messageAddListener(self: boolean) { return jest.fn<void, [Message['type'], onMessageEvent] | [onMessageEvent]>( messageAddListener as any ) function messageAddListener( messageType: Message['type'], cb: onMessageEvent ): void function messageAddListener(cb: onMessageEvent): void function messageAddListener(...args): void { const allListeners = self ? messageSelfListeners : messageListeners const messageType = args.length === 1 ? undefined : args[0] const cb = args.length === 1 ? args[0] : args[1] let listeners = allListeners.get(cb) if (!listeners) { listeners = new Map() allListeners.set(cb, listeners) } let listener = listeners.get(messageType || '__DEFAULT_MSGTYPE__') if (!listener) { listener = ((message, sender, sendResponse) => { if (message && (self ? window.pageId === 'PAGE_INFO' : !'PAGE_INFO')) { if (messageType == null || message.type === messageType) { return cb(message, sender, sendResponse) } } }) as onMessageEvent listeners.set(messageType, listener) } } } function _messageRemoveListener(self: boolean) { return jest.fn<void, [Message['type'], onMessageEvent] | [onMessageEvent]>( messageRemoveListener as any ) function messageRemoveListener( messageType: Message['type'], cb: onMessageEvent ): void function messageRemoveListener(cb: onMessageEvent): void function messageRemoveListener(...args): void { const allListeners = self ? messageSelfListeners : messageListeners const messageType = args.length === 1 ? undefined : args[0] const cb = args.length === 1 ? args[0] : args[1] const listeners = allListeners.get(cb) if (listeners) { if (messageType) { const listener = listeners.get(messageType) if (listener) { listeners.delete(messageType) if (listeners.size <= 0) { allListeners.delete(cb) } } } else { // delete all cb related callbacks allListeners.delete(cb) } } } } function _messageCreateStream(self: boolean) { return jest.fn(messageCreateStream) function messageCreateStream<T>( messageType?: Message['type'] ): Observable<T> { const obj = self ? message.self : message const pattern$ = messageType ? fromEventPattern( handler => obj.addListener(messageType, handler as onMessageEvent), handler => obj.removeListener(messageType, handler as onMessageEvent) ) : fromEventPattern( handler => obj.addListener(handler as onMessageEvent), handler => obj.removeListener(handler as onMessageEvent) ) return pattern$.pipe(map(args => (Array.isArray(args) ? args[0] : args))) } } interface DispatchMessageEventOptions { message: Message sender?: browser.runtime.MessageSender sendResponse?: Function } interface DispatchMessageEventOptionsGeneral extends DispatchMessageEventOptions { self?: boolean } function _dispatchMessageEvent(self: boolean) { const _fn = dispatchMessageEvent return function dispatchMessageEvent(options: DispatchMessageEventOptions) { return _fn(Object.assign(options, { self })) } } export function dispatchMessageEvent( options: DispatchMessageEventOptionsGeneral ) { const listeners = options.self ? messageSelfListeners : messageListeners listeners.forEach(m => { m.forEach((cb, type) => { if (options.message.type === type) { cb(options.message, options.sender || {}, options.sendResponse || noop) } }) }) }
anrgct/ext-saladict
src/selection/index.ts
import { getText, getSentence, getTextFromSelection, getSentenceFromSelection } from 'get-selection-more' import { message } from '@/_helpers/browser-api' import { createConfigStream } from '@/_helpers/config-manager' import { isInDictPanel } from '@/_helpers/saladict' import { share, map, switchMap } from 'rxjs/operators' import { postMessageHandler, sendMessage, sendEmptyMessage } from './message' import { isEscapeKey, whenKeyPressed, isBlacklisted, newSelectionWord } from './helper' import { createIntantCaptureStream } from './instant-capture' import { createQuickSearchStream } from './quick-search' import { createSelectTextStream } from './select-text' // Firefox somehow loads it two times if (!window.__SALADICT_SELECTION_LOADED__) { window.__SALADICT_SELECTION_LOADED__ = true const config$$ = createConfigStream().pipe( map(config => (isBlacklisted(config) ? null : config)), share() ) /** * Send selection to standalone page * Beware that this is run on every frame. */ message.addListener('PRELOAD_SELECTION', () => { const text = getText() if (text) { return newSelectionWord({ text, context: getSentence() }) } }) /** * Manualy emit selection * Beware that this is run on every frame. */ message.createStream('EMIT_SELECTION').subscribe(async () => { const selection = window.getSelection() if (selection) { const text = getTextFromSelection(selection) const rect = selection.getRangeAt(0).getBoundingClientRect() if (text) { sendMessage({ mouseX: rect.right, mouseY: rect.top, instant: true, self: isInDictPanel(selection.anchorNode), word: await newSelectionWord({ text, context: getSentenceFromSelection(selection) }), dbClick: false, altKey: false, shiftKey: false, ctrlKey: false, metaKey: false, force: false }) } } }) /** Pass through message from iframes */ window.addEventListener('message', postMessageHandler) /** * Escape key pressed */ whenKeyPressed(isEscapeKey).subscribe(() => message.self.send({ type: 'ESCAPE_KEY' }) ) config$$.pipe(switchMap(createQuickSearchStream)).subscribe(() => { message.self.send({ type: 'TRIPLE_CTRL' }) }) config$$.pipe(switchMap(createSelectTextStream)).subscribe(async result => { if (result.word) { sendMessage({ dbClick: false, altKey: false, shiftKey: false, ctrlKey: false, metaKey: false, self: false, instant: false, force: false, ...result, word: await newSelectionWord(result.word) }) } else { sendEmptyMessage(result.self) } }) config$$ .pipe(switchMap(createIntantCaptureStream)) .subscribe(async ({ word, event, self }) => { sendMessage({ word: await newSelectionWord(word), altKey: event.altKey, shiftKey: event.shiftKey, ctrlKey: event.ctrlKey, metaKey: event.metaKey, dbClick: false, force: false, instant: true, mouseX: event.clientX, mouseY: event.clientY, self }) }) }
anrgct/ext-saladict
src/options/components/EntrySideBar/index.tsx
<filename>src/options/components/EntrySideBar/index.tsx import React, { FC, useContext } from 'react' import { Layout, Menu, Affix, Modal } from 'antd' import { SettingOutlined, TagsOutlined, DashboardOutlined, ProfileOutlined, SelectOutlined, BookOutlined, SoundOutlined, FilePdfOutlined, DatabaseOutlined, LayoutOutlined, FlagOutlined, ExceptionOutlined, SwapOutlined, LockOutlined, ExclamationCircleOutlined, KeyOutlined } from '@ant-design/icons' import { useObservableState } from 'observable-hooks' import { debounceTime, scan, distinctUntilChanged } from 'rxjs/operators' import { useTranslate } from '@/_helpers/i18n' import { GlobalsContext } from '@/options/data' import './_style.scss' export interface EntrySideBarProps { entry: string onChange: (entry: string) => void } export const EntrySideBar: FC<EntrySideBarProps> = props => { const { t } = useTranslate('options') const globals = useContext(GlobalsContext) // trigger affix rerendering on collapse state changes to update width const [affixKey, onCollapse] = useObservableState<number, boolean>(event$ => event$.pipe( distinctUntilChanged(), // onCollapse will be triggered on initial collapsed state debounceTime(500), // wait for transition scan(id => (id + 1) % 10000, 0) // unique id ) ) return ( <Affix key={affixKey}> <Layout> <Layout.Sider className="entry-sidebar fancy-scrollbar" width={180} breakpoint="lg" collapsible trigger={null} onCollapse={onCollapse} > <Menu mode="inline" selectedKeys={[props.entry]} onSelect={({ key }) => { const switchTab = () => { props.onChange(key) ;(globals as GlobalsContext).dirty = false } if (globals.dirty) { Modal.confirm({ title: t('unsave_confirm'), icon: <ExclamationCircleOutlined />, okType: 'danger', onOk: switchTab }) } else { switchTab() } }} > <Menu.Item key="General"> <SettingOutlined /> <span>{t('nav.General')}</span> </Menu.Item> <Menu.Item key="Notebook"> <TagsOutlined /> <span>{t('nav.Notebook')}</span> </Menu.Item> <Menu.Item key="Profiles"> <DashboardOutlined /> <span>{t('nav.Profiles')}</span> </Menu.Item> <Menu.Item key="DictPanel"> <ProfileOutlined /> <span>{t('nav.DictPanel')}</span> </Menu.Item> <Menu.Item key="SearchModes"> <SelectOutlined /> <span>{t('nav.SearchModes')}</span> </Menu.Item> <Menu.Item key="Dictionaries"> <BookOutlined /> <span>{t('nav.Dictionaries')}</span> </Menu.Item> <Menu.Item key="DictAuths"> <KeyOutlined /> <span>{t('nav.DictAuths')}</span> </Menu.Item> <Menu.Item key="Popup"> <LayoutOutlined /> <span>{t('nav.Popup')}</span> </Menu.Item> <Menu.Item key="QuickSearch"> <FlagOutlined /> <span>{t('nav.QuickSearch')}</span> </Menu.Item> <Menu.Item key="Pronunciation"> <SoundOutlined /> <span>{t('nav.Pronunciation')}</span> </Menu.Item> <Menu.Item key="PDF"> <FilePdfOutlined /> <span>{t('nav.PDF')}</span> </Menu.Item> <Menu.Item key="ContextMenus"> <DatabaseOutlined /> <span>{t('nav.ContextMenus')}</span> </Menu.Item> <Menu.Item key="BlackWhiteList"> <ExceptionOutlined /> <span>{t('nav.BlackWhiteList')}</span> </Menu.Item> <Menu.Item key="ImportExport"> <SwapOutlined /> <span>{t('nav.ImportExport')}</span> </Menu.Item> <Menu.Item key="Privacy"> <LockOutlined /> <span>{t('nav.Privacy')}</span> </Menu.Item> </Menu> </Layout.Sider> </Layout> </Affix> ) } export const EntrySideBarMemo = React.memo(EntrySideBar)
anrgct/ext-saladict
src/options/components/Header/HeadInfo/index.tsx
import React, { FC } from 'react' import CSSTransition from 'react-transition-group/CSSTransition' import { of } from 'rxjs' import { switchMap, delay } from 'rxjs/operators' import { useObservableState, useObservableCallback } from 'observable-hooks' import { Tooltip } from 'antd' import { WarningOutlined } from '@ant-design/icons' import acknowledgement from '@/options/acknowledgement' import { useTranslate } from '@/_helpers/i18n' import { hover } from '@/_helpers/observables' import './_style.scss' export const HeadInfo: FC = () => { const { t } = useTranslate('options') const [onMouseOverOut, mouseOverOut$] = useObservableCallback< boolean, React.MouseEvent >(event$ => hover(event$).pipe( switchMap(isEnter => of(isEnter).pipe(delay(isEnter ? 500 : 400))) ) ) const isShowAck = useObservableState(mouseOverOut$) return ( <ul className="head-info"> {process.env.DEBUG || process.env.SDAPP_VETTED ? null : ( <li className="head-info-bubble-wrap"> <Tooltip placement="bottom" title={decodeURI( '%E6%AD%A4%E6%89%A9%E5%B1%95%E5%B7%B2%E8%A2%AB%E5%86%8D%E6%AC%A1%E6%89%93%E5%8C%85%EF%BC%8C%E5%8F%AF%E8%83%BD%E5%B7%B2%E8%A2%AB%E5%8A%A0%E5%85%A5%E6%81%B6%E6%84%8F%E4%BB%A3%E7%A0%81%EF%BC%8C%E8%AF%B7%E5%89%8D%E5%BE%80%E3%80%8C%E6%B2%99%E6%8B%89%E6%9F%A5%E8%AF%8D%E3%80%8D%E5%AE%98%E6%96%B9%E5%BB%BA%E8%AE%AE%E7%9A%84%E5%B9%B3%E5%8F%B0%E5%AE%89%E8%A3%85' )} > <span style={{ color: '#fff' }}> <WarningOutlined />{' '} {decodeURI('%E6%BD%9C%E5%9C%A8%E5%A8%81%E8%83%81')} </span> </Tooltip> </li> )} <li className="head-info-bubble-wrap head-info-unin"> <a href="https://github.com/crimx/ext-saladict/wiki#acknowledgement" onMouseOver={onMouseOverOut} onMouseOut={onMouseOverOut} onClick={preventDefault} > {t('headInfo.acknowledgement.title')} </a> <CSSTransition classNames="head-info-fade" in={isShowAck} timeout={500} mountOnEnter unmountOnExit > {() => ( <div className="head-info-bubble" onMouseOver={onMouseOverOut} onMouseOut={onMouseOverOut} > <ol> {acknowledgement.map((ack, i) => ( <li key={i}> <a href={ack.href} rel="nofollow noopener noreferrer" target="_blank" > {ack.name} </a>{' '} {t(`headInfo.acknowledgement.${ack.locale}`)} </li> ))} </ol> </div> )} </CSSTransition> </li> <li> <a href="https://saladict.crimx.com/manual.html" target="_blank" rel="nofollow noopener noreferrer" > {t('headInfo.instructions')} </a> </li> <li> <a href="https://saladict.crimx.com/support.html" target="_blank" rel="nofollow noopener noreferrer" > 💪{t('headInfo.donate')} </a> </li> <li> <a href="https://github.com/crimx/ext-saladict/issues" target="_blank" rel="nofollow noopener noreferrer" > {t('headInfo.report_issue')} </a> </li> </ul> ) } export const HeadInfoMemo = React.memo(HeadInfo) function preventDefault(e: React.MouseEvent<HTMLElement>) { e.preventDefault() }
anrgct/ext-saladict
src/options/components/Header/index.tsx
import React, { FC, useMemo } from 'react' import { Layout } from 'antd' import { useObservableState, useObservableGetState } from 'observable-hooks' import { useTranslate } from '@/_helpers/i18n' import { getProfileName } from '@/_helpers/profile-manager' import { profile$$, profileIDList$$ } from '@/options/data' import { HeadInfoMemo } from './HeadInfo' import './_style.scss' export interface HeaderProps { openProfilesTab: (entry: 'Profiles') => void } export const Header: FC<HeaderProps> = props => { const { t, ready } = useTranslate(['options', 'common']) const profileId = useObservableGetState(profile$$, 'id')! const profileIDList = useObservableState(profileIDList$$)! const profileName = useMemo( () => ready ? `「 ${getProfileName( profileIDList.find(({ id }) => id === profileId)?.name || '', t )} 」` : '', [profileId, profileIDList, ready] ) return ( <Layout.Header> <div className="options-header"> <h1>{t('title')}</h1> <a href="/?menuselected=Profiles" onClick={e => { e.preventDefault() e.stopPropagation() props.openProfilesTab('Profiles') }} > {profileName} </a> <HeadInfoMemo /> </div> </Layout.Header> ) } export const HeaderMemo = React.memo(Header)
anrgct/ext-saladict
src/content/components/WordEditor/WordEditor.portal.tsx
import React, { FC } from 'react' import { ShadowPortal, defaultTimeout } from '@/components/ShadowPortal' import { WordEditor, WordEditorProps } from './WordEditor' export interface WordEditorPortalProps extends WordEditorProps { show: boolean withAnimation: boolean } export const WordEditorPortal: FC<WordEditorPortalProps> = props => { const { withAnimation, show, ...restProps } = props return ( <ShadowPortal id="saladict-wordeditor-root" head={<style>{require('./WordEditor.shadow.scss').toString()}</style>} in={show} timeout={withAnimation ? defaultTimeout : 0} > {() => <WordEditor {...restProps} />} </ShadowPortal> ) } export default WordEditorPortal
anrgct/ext-saladict
test/specs/components/dictionaries/naver/engine.spec.ts
<gh_stars>1-10 import { retry } from '../helpers' import { search } from '@/components/dictionaries/naver/engine' import { getDefaultConfig } from '@/app-config' import { getDefaultProfile, ProfileMutable } from '@/app-config/profiles' describe('Dict/Naver/engine', () => { it('should search zh dict', () => { return retry(() => search('爱', getDefaultConfig(), getDefaultProfile(), { isPDF: false }).then(searchResult => { expect(searchResult.result.lang).toBe('zh') expect(typeof searchResult.result.entry).toBe('string') }) ) }) it('should search ja dict', () => { const profile = getDefaultProfile() as ProfileMutable profile.dicts.all.naver.options.hanAsJa = true return retry(() => search('愛', getDefaultConfig(), profile, { isPDF: false }).then( searchResult => { expect(searchResult.result.lang).toBe('ja') expect(typeof searchResult.result.entry).toBe('string') } ) ) }) })
anrgct/ext-saladict
test/specs/background/sync-manager/services/webdav.spec.ts
<reponame>anrgct/ext-saladict import * as helpersMock from '@/background/sync-manager/__mocks__/helpers' import { NotebookFile } from '@/background/sync-manager/interface' import { Service, SyncConfig, SyncMeta } from '@/background/sync-manager/services/webdav' import { Word, newWord } from '@/_helpers/record-manager' jest.mock('@/background/sync-manager/helpers') const helpers: typeof helpersMock = require('@/background/sync-manager/helpers') const fetchArgs = { checkServer(config: SyncConfig) { return [ config.url, { method: 'PROPFIND', headers: { Authorization: 'Basic ' + window.btoa(`${config.user}:${config.passwd}`), 'Content-Type': 'application/xml; charset="utf-8"', Depth: '1' } } ] }, createDir(config: SyncConfig) { return [ config.url + 'Saladict', { method: 'MKCOL', headers: { Authorization: 'Basic ' + window.btoa(`${config.user}:${config.passwd}`) } } ] }, upload(config: SyncConfig, body: any = '') { return [ config.url + 'Saladict/notebook.json', { method: 'PUT', headers: { Authorization: 'Basic ' + window.btoa(`${config.user}:${config.passwd}`) }, body } ] }, download(config: SyncConfig, headers: { [index: string]: string } = {}) { return [ config.url + 'Saladict/notebook.json', { method: 'GET', headers: { Authorization: 'Basic ' + window.btoa(`${config.user}:${config.passwd}`), ...headers } } ] } } function mockFetch( config: SyncConfig, route: Partial< { [k in keyof typeof fetchArgs]: ( url: string, rqInit?: RequestInit ) => Response } > ) { const urltokey: { [key: string]: keyof typeof fetchArgs } = Object.keys( fetchArgs ).reduce((o, k) => { const args = fetchArgs[k](config) o[args[0] + ((args[1] && args[1].method) || '')] = k return o }, {}) window.fetch = jest.fn( (url: string, init?: RequestInit): Promise<Response> => { const key = urltokey[url + ((init && init.method) || '')] const handler = key && route[key] if (handler) { return Promise.resolve(handler(url, init)) } return Promise.resolve(new Response()) } ) as any } describe('Sync service WebDAV', () => { beforeEach(() => { jest.clearAllMocks() window.fetch = null as any }) it('upload: should success', async () => { const config: SyncConfig = { url: 'https://example.com/dav/', user: 'user', passwd: '<PASSWORD>', duration: 0 } const fetchInit = { upload: jest.fn(() => new Response()) } mockFetch(config, fetchInit) const words = [getWord(), getWord({ text: 'word' })] helpers.getNotebook.mockImplementationOnce(() => Promise.resolve(words)) const service = new Service() service.config = config await service.add({ force: true }) expect(fetchInit.upload).toHaveBeenCalledTimes(1) expect(fetchInit.upload).lastCalledWith( ...fetchArgs.upload( config, expect.stringContaining(JSON.stringify(words)) ) ) }) describe('download', () => { it('should save file on first download', async () => { const config: SyncConfig = { url: 'https://example.com/dav/', user: 'user', passwd: '<PASSWORD>', duration: 0 } const words = [ getWord({ ...newWord({ text: 'test' }), date: Date.now() }) ] const timestamp = Date.now() const file: NotebookFile = { timestamp, words } const etag = 'etag222' const fetchInit = { download: jest.fn( () => new Response(JSON.stringify(file), { headers: { etag } }) ) } mockFetch(config, fetchInit) const service = new Service() service.config = config await service.download({}) expect(helpers.setNotebook).lastCalledWith(words, true) expect(helpers.setMeta).lastCalledWith('webdav', { timestamp, etag }) expect(fetchInit.download).toHaveBeenCalledTimes(1) expect(fetchInit.download).lastCalledWith(...fetchArgs.download(config)) }) it('should save file if etag changed', async () => { const config: SyncConfig = { url: 'https://example.com/dav/', user: 'user', passwd: '<PASSWORD>', duration: 0 } const words = [ getWord({ ...newWord({ text: 'test' }), date: Date.now() }) ] const timestamp = Date.now() const file: NotebookFile = { timestamp, words } const etagOrigin = 'etag12345' const etag = 'etag222' const fetchInit = { download: jest.fn( () => new Response(JSON.stringify(file), { headers: { etag } }) ) } mockFetch(config, fetchInit) const service = new Service() service.config = config service.meta = { etag: etagOrigin } await service.download({}) expect(helpers.setNotebook).lastCalledWith(words, true) expect(helpers.setMeta).lastCalledWith('webdav', { timestamp, etag }) expect(fetchInit.download).toHaveBeenCalledTimes(1) expect(fetchInit.download).lastCalledWith( ...fetchArgs.download(config, { 'If-None-Match': etagOrigin, 'If-Modified-Since': etagOrigin }) ) }) it('should do nothing if 304 (same etag)', async () => { const config: SyncConfig = { url: 'https://example.com/dav/', user: 'user', passwd: '<PASSWORD>', duration: 0 } const etag = 'etag222' const fetchInit = { download: jest.fn( () => new Response(null, { status: 304, headers: { etag } }) ) } mockFetch(config, fetchInit) const service = new Service() service.config = config service.meta = { etag } await service.download({}) expect(helpers.setNotebook).toHaveBeenCalledTimes(0) expect(helpers.setMeta).toHaveBeenCalledTimes(0) expect(fetchInit.download).toHaveBeenCalledTimes(1) expect(fetchInit.download).lastCalledWith( ...fetchArgs.download(config, { 'If-None-Match': etag, 'If-Modified-Since': etag }) ) }) it('should do nothing if etags are different but timestamps are identical', async () => { const config: SyncConfig = { url: 'https://example.com/dav/', user: 'user', passwd: '<PASSWORD>', duration: 0 } const file: NotebookFile = { timestamp: Date.now(), words: [ { ...newWord({ text: 'test' }), date: Date.now() } ] } const etagOrigin = 'etag12345' const etag = 'etag222' const fetchInit = { download: jest.fn( () => new Response(JSON.stringify(file), { headers: { etag } }) ) } mockFetch(config, fetchInit) const service = new Service() service.config = config service.meta = { etag: etagOrigin, timestamp: file.timestamp } await service.download({}) expect(helpers.setNotebook).toHaveBeenCalledTimes(0) expect(helpers.setMeta).toHaveBeenCalledTimes(1) expect(fetchInit.download).toHaveBeenCalledTimes(1) expect(fetchInit.download).lastCalledWith( ...fetchArgs.download(config, { 'If-None-Match': etagOrigin, 'If-Modified-Since': etagOrigin }) ) }) it('should do nothing if etags are different but timestamps are identical', async () => { const config: SyncConfig = { url: 'https://example.com/dav/', user: 'user', passwd: '<PASSWORD>', duration: 0 } const file: NotebookFile = { timestamp: Date.now(), words: [ getWord({ ...newWord({ text: 'test' }), date: Date.now() }) ] } const etagOrigin = 'etag12345' const etag = 'etag222' const fetchInit = { download: jest.fn( () => new Response(JSON.stringify(file), { headers: { etag } }) ) } mockFetch(config, fetchInit) const service = new Service() service.config = config service.meta = { etag: etagOrigin, timestamp: file.timestamp } await service.download({}) expect(helpers.setNotebook).toHaveBeenCalledTimes(0) expect(helpers.setMeta).toHaveBeenCalledTimes(1) expect(fetchInit.download).toHaveBeenCalledTimes(1) expect(fetchInit.download).lastCalledWith( ...fetchArgs.download(config, { 'If-None-Match': etagOrigin, 'If-Modified-Since': etagOrigin }) ) }) it('should do nothing if words are corrupted', async () => { const config: SyncConfig = { url: 'https://example.com/dav/', user: 'user', passwd: '<PASSWORD>', duration: 0 } const file: NotebookFile = { timestamp: Date.now(), words: ['corrupted format'] as any } const etag = 'etag222' const fetchInit = { download: jest.fn( () => new Response(JSON.stringify(file), { headers: { etag } }) ) } mockFetch(config, fetchInit) const service = new Service() service.config = config try { await service.download({}) } catch (e) { expect(e).toBe('format') } expect(helpers.setNotebook).toHaveBeenCalledTimes(0) expect(helpers.setMeta).toHaveBeenCalledTimes(0) expect(fetchInit.download).toHaveBeenCalledTimes(1) expect(fetchInit.download).lastCalledWith(...fetchArgs.download(config)) }) it('should do nothing if network failed', async () => { const config: SyncConfig = { url: 'https://example.com/dav/', user: 'user', passwd: '<PASSWORD>', duration: 0 } const fetchInit = { download: jest.fn( () => new Response(null, { status: 404 }) ) } mockFetch(config, fetchInit) const service = new Service() service.config = config try { await service.download({}) } catch (e) { expect(e).toBe('network') } expect(helpers.setNotebook).toHaveBeenCalledTimes(0) expect(helpers.setMeta).toHaveBeenCalledTimes(0) expect(fetchInit.download).toHaveBeenCalledTimes(1) expect(fetchInit.download).lastCalledWith(...fetchArgs.download(config)) }) }) describe('initServer', () => { it('should create dir and upload files on first init', async () => { const config: SyncConfig = { url: 'https://example.com/dav/', user: 'user', passwd: '<PASSWORD>', duration: 0 } const file: NotebookFile = { timestamp: Date.now(), words: [ { ...newWord({ text: 'test' }), date: Date.now() } ] } const fileText = JSON.stringify(file) const etag = 'etag222' const fetchInit = { checkServer: jest.fn(() => new Response(genXML())), upload: jest.fn(() => new Response()), download: jest.fn( () => new Response(fileText, { headers: { etag } }) ), createDir: jest.fn(() => new Response()) } mockFetch(config, fetchInit) const service = new Service() service.config = config service.download = jest.fn(() => Promise.resolve()) await service.init(config) expect(service.download).toHaveBeenCalledTimes(0) expect(fetchInit.checkServer).toHaveBeenCalledTimes(1) expect(fetchInit.checkServer).lastCalledWith( ...fetchArgs.checkServer(config) ) expect(fetchInit.createDir).toHaveBeenCalledTimes(1) expect(fetchInit.createDir).lastCalledWith(...fetchArgs.createDir(config)) expect(fetchInit.upload).toHaveBeenCalledTimes(0) expect(fetchInit.download).toHaveBeenCalledTimes(0) expect(helpers.setMeta).toHaveBeenCalledTimes(1) expect(helpers.setNotebook).toHaveBeenCalledTimes(0) }) it('should do nothing if local files are older', async () => { const config: SyncConfig = { url: 'https://example.com/dav/', user: 'user', passwd: '<PASSWORD>', duration: 0 } const file: NotebookFile = { timestamp: Date.now(), words: [ { ...newWord({ text: 'test' }), date: Date.now() } ] } const fileText = JSON.stringify(file) const etagLocal = 'etag12345' const etag = 'etag222' const fetchInit = { checkServer: jest.fn(() => new Response(genXML(true))), upload: jest.fn(() => new Response()), download: jest.fn( () => new Response(fileText, { headers: { etag } }) ), createDir: jest.fn(() => new Response()) } helpers.getMeta.mockImplementationOnce( (): Promise<SyncMeta> => Promise.resolve({ timestamp: file.timestamp - 100, etag: etagLocal }) ) mockFetch(config, fetchInit) const service = new Service() service.config = config service.download = jest.fn(() => Promise.resolve()) await service.init(config) expect(service.download).toHaveBeenCalledTimes(0) expect(fetchInit.checkServer).toHaveBeenCalledTimes(1) expect(fetchInit.checkServer).lastCalledWith( ...fetchArgs.checkServer(config) ) // @upstream JSDOM missing namespace selector support // expect(fetchInit.createDir).toHaveBeenCalledTimes(0) expect(fetchInit.upload).toHaveBeenCalledTimes(0) expect(fetchInit.download).toHaveBeenCalledTimes(0) expect(helpers.setMeta).toHaveBeenCalledTimes(1) expect(helpers.setNotebook).toHaveBeenCalledTimes(0) }) it('should reject with "network" if netword errored', async () => { const config: SyncConfig = { url: 'https://example.com/dav/', user: 'user', passwd: '<PASSWORD>', duration: 0 } const fetchInit = { checkServer: jest.fn(() => new Response(null, { status: 404 })), upload: jest.fn(() => new Response()), download: jest.fn(() => new Response()), createDir: jest.fn(() => new Response()) } mockFetch(config, fetchInit) const service = new Service() service.config = config service.download = jest.fn(() => Promise.resolve()) try { await service.init(config) } catch (e) { expect(e).toBe('network') } expect(service.download).toHaveBeenCalledTimes(0) expect(fetchInit.checkServer).toHaveBeenCalledTimes(1) expect(fetchInit.checkServer).lastCalledWith( ...fetchArgs.checkServer(config) ) // @upstream JSDOM missing namespace selector support // expect(fetchInit.createDir).toHaveBeenCalledTimes(0) expect(fetchInit.upload).toHaveBeenCalledTimes(0) expect(fetchInit.download).toHaveBeenCalledTimes(0) expect(helpers.setMeta).toHaveBeenCalledTimes(0) expect(helpers.setNotebook).toHaveBeenCalledTimes(0) }) it('should reject with "mkcol" if cannot create dir', async () => { const config: SyncConfig = { url: 'https://example.com/dav/', user: 'user', passwd: '<PASSWORD>', duration: 0 } const fetchInit = { checkServer: jest.fn(() => new Response(genXML(true))), upload: jest.fn(() => new Response()), download: jest.fn(() => new Response()), createDir: jest.fn(() => new Response(null, { status: 504 })) } mockFetch(config, fetchInit) const service = new Service() service.config = config service.download = jest.fn(() => Promise.resolve()) try { await service.init(config) } catch (e) { expect(e).toBe('mkcol') } expect(service.download).toHaveBeenCalledTimes(0) expect(fetchInit.checkServer).toHaveBeenCalledTimes(1) expect(fetchInit.checkServer).lastCalledWith( ...fetchArgs.checkServer(config) ) expect(fetchInit.createDir).toHaveBeenCalledTimes(1) expect(fetchInit.createDir).lastCalledWith(...fetchArgs.createDir(config)) expect(fetchInit.upload).toHaveBeenCalledTimes(0) expect(fetchInit.download).toHaveBeenCalledTimes(0) expect(helpers.setMeta).toHaveBeenCalledTimes(0) expect(helpers.setNotebook).toHaveBeenCalledTimes(0) }) // @upstream JSDOM missing namespace selector support // it('should reject with "exist" if local has a newer file', async () => { // const config: SyncConfig = { // url: 'https://example.com/dav/', // user: 'user', // passwd: '<PASSWORD>', // duration: 0, // } // const file: NotebookFile = { // timestamp: Date.now(), // words: [ // { // ...newWord({ text: 'test' }), // date: Date.now(), // } // ], // } // const fileText = JSON.stringify(file) // const etagLocal = 'etag12345' // const etag = 'etag222' // const fetchInit = { // checkServer: jest.fn(() => new Response(genXML(true))), // upload: jest.fn(() => new Response()), // download: jest.fn(() => new Response( // fileText, // { // headers: { // etag, // } // } // )), // createDir: jest.fn(() => new Response()) // } // helpers.getMeta.mockImplementationOnce((): Promise<Meta> => Promise.resolve({ // timestamp: file.timestamp + 100, // etag: etagLocal // })) // mockFetch(config, fetchInit) // c{ onsor t} err = await initServer(config) // exerrort(err).toBe('exist') // expect(fetchInit.checkServer).toHaveBeenCalledTimes(1) // expect(fetchInit.checkServer).lastCalledWith(...fetchArgs.checkServer(config)) // // @upstream JSDOM missing namespace selector support // // expect(fetchInit.createDir).toHaveBeenCalledTimes(0) // expect(fetchInit.upload).toHaveBeenCalledTimes(0) // expect(fetchInit.download).toHaveBeenCalledTimes(0) // expect(helpers.setMeta).toHaveBeenCalledTimes(0) // expect(helpers.setNotebook).toHaveBeenCalledTimes(0) // }) }) }) function genXML(withDir?: boolean): string { const dir = `<d:response> <d:href>/dav/Saladict/</d:href> <d:propstat> <d:prop> <d:getlastmodified>Mon, 31 Oct 2018 07:31:21 GMT</d:getlastmodified> <d:getcontentlength>0</d:getcontentlength> <d:owner><EMAIL></d:owner> <d:current-user-privilege-set> <d:privilege> <d:read /> </d:privilege> <d:privilege> <d:write /> </d:privilege> <d:privilege> <d:all /> </d:privilege> <d:privilege> <d:read_acl /> </d:privilege> <d:privilege> <d:write_acl /> </d:privilege> </d:current-user-privilege-set> <d:getcontenttype>httpd/unix-directory</d:getcontenttype> <d:displayname>Saladict</d:displayname> <d:resourcetype> <d:collection /> </d:resourcetype> </d:prop> <d:status>HTTP/1.1 200 OK</d:status> </d:propstat> </d:response>` return `<?xml version="1.0" encoding="UTF-8" standalone="no"?> <d:multistatus xmlns:d="DAV:" xmlns:s="http://ns.example.com"> <d:response> <d:href>/dav/</d:href> <d:propstat> <d:prop> <d:getlastmodified>Mon, 31 Oct 2018 07:31:21 GMT</d:getlastmodified> <d:getcontentlength>0</d:getcontentlength> <d:owner><EMAIL></d:owner> <d:current-user-privilege-set> <d:privilege> <d:read /> </d:privilege> </d:current-user-privilege-set> <d:getcontenttype>httpd/unix-directory</d:getcontenttype> <d:displayname>dav</d:displayname> <d:resourcetype> <d:collection /> </d:resourcetype> </d:prop> <d:status>HTTP/1.1 200 OK</d:status> </d:propstat> </d:response> ${withDir ? dir : ''} </d:multistatus>` } function getWord(word: Partial<Word> = {}): Word { return { date: Date.now(), text: '', context: '', title: '', url: '', favicon: '', trans: '', note: '', ...word } }
anrgct/ext-saladict
src/components/dictionaries/youdao/config.ts
<gh_stars>1-10 import { DictItem } from '@/app-config/dicts' export type YoudaoConfig = DictItem<{ basic: boolean collins: boolean discrimination: boolean sentence: boolean translation: boolean related: boolean }> export default (): YoudaoConfig => ({ lang: '11000000', selectionLang: { english: true, chinese: true, japanese: false, korean: false, french: false, spanish: false, deutsch: false, others: false, matchAll: false }, defaultUnfold: { english: true, chinese: true, japanese: true, korean: true, french: true, spanish: true, deutsch: true, others: true, matchAll: false }, preferredHeight: 265, selectionWC: { min: 1, max: 999999999999999 }, options: { basic: true, collins: true, discrimination: true, sentence: true, translation: true, related: true } })
anrgct/ext-saladict
src/components/dictionaries/jukuu/View.tsx
import React, { FC } from 'react' import { JukuuResult, JukuuPayload, JukuuLang } from './engine' import { ViewPorps } from '@/components/dictionaries/helpers' import { useTranslate } from '@/_helpers/i18n' export const DictJukuu: FC<ViewPorps<JukuuResult>> = props => { const { result, searchText } = props const { t } = useTranslate('dicts') return ( <> <select onChange={e => { if (e.target.value) { searchText<JukuuPayload>({ id: 'jukuu', payload: { lang: e.target.value as JukuuLang } }) } }} > <option value="zheng" selected={result.lang === 'zheng'}> {t('jukuu.options.lang-zheng')} </option> <option value="engjp" selected={result.lang === 'engjp'}> {t('jukuu.options.lang-engjp')} </option> <option value="zhjp" selected={result.lang === 'zhjp'}> {t('jukuu.options.lang-zhjp')} </option> </select> <ul className="dictJukuu-Sens"> {result.sens.map((sen, i) => ( <li key={i} className="dictJukuu-Sen"> <p dangerouslySetInnerHTML={{ __html: sen.trans }} /> <p className="dictJukuu-Ori">{sen.original}</p> <p className="dictJukuu-Src">{sen.src}</p> </li> ))} </ul> </> ) } export default DictJukuu
anrgct/ext-saladict
src/components/dictionaries/bing/engine.ts
<filename>src/components/dictionaries/bing/engine.ts import { fetchDirtyDOM } from '@/_helpers/fetch-dom' import { handleNoResult, handleNetWorkError, getText, getInnerHTML, SearchFunction, GetSrcPageFunction, DictSearchResult, getChsToChz } from '../helpers' import { DictConfigs } from '@/app-config' export const getSrcPage: GetSrcPageFunction = text => { return `https://cn.bing.com/dict/search?q=${text}` } const HOST = 'https://cn.bing.com' const DICT_LINK = 'https://cn.bing.com/dict/clientsearch?mkt=zh-CN&setLang=zh&form=BDVEHC&ClientVer=BDDTV3.5.1.4320&q=' /** Lexical result */ export interface BingResultLex { type: 'lex' title: string /** phonetic symbols */ phsym?: Array<{ /** Phonetic Alphabet, UK|US|PY */ lang: string /** pronunciation */ pron: string }> /** common definitions */ cdef?: Array<{ /** part of speech */ pos: string /** definition */ def: string }> /** infinitive */ infs?: string[] sentences?: Array<{ en?: string chs?: string source?: string mp3?: string }> } /** Alternate machine translation result */ export interface BingResultMachine { type: 'machine' /** machine translation */ mt: string } /** Alternate result */ export interface BingResultRelated { type: 'related' title: string defs: Array<{ title: string meanings: Array<{ href: string word: string def: string }> }> } export type BingResult = BingResultLex | BingResultMachine | BingResultRelated type BingConfig = DictConfigs['bing'] type BingSearchResultLex = DictSearchResult<BingResultLex> type BingSearchResultMachine = DictSearchResult<BingResultMachine> type BingSearchResultRelated = DictSearchResult<BingResultRelated> export const search: SearchFunction<BingResult> = ( text, config, profile, payload ) => { const bingConfig = profile.dicts.all.bing return fetchDirtyDOM( DICT_LINK + encodeURIComponent(text.replace(/\s+/g, ' ')) ) .catch(handleNetWorkError) .then(async doc => { const transform = await getChsToChz(config.langCode) if (doc.querySelector('.client_def_hd_hd')) { return handleLexResult(doc, bingConfig.options, transform) } if (doc.querySelector('.client_trans_head')) { return handleMachineResult(doc, transform) } if (bingConfig.options.related) { if (doc.querySelector('.client_do_you_mean_title_bar')) { return handleRelatedResult(doc, bingConfig, transform) } } return handleNoResult<DictSearchResult<BingResult>>() }) } function handleLexResult( doc: Document, options: BingConfig['options'], transform: null | ((text: string) => string) ): BingSearchResultLex | Promise<BingSearchResultLex> { const searchResult: DictSearchResult<BingResultLex> = { result: { type: 'lex', title: getText(doc, '.client_def_hd_hd', transform) } } // pronunciation if (options.phsym) { const $prons = Array.from(doc.querySelectorAll('.client_def_hd_pn_list')) if ($prons.length > 0) { searchResult.result.phsym = $prons.map(el => { let pron = '' const $audio = el.querySelector('.client_aud_o') if ($audio) { pron = (($audio.getAttribute('onclick') || '').match( /https.*\.mp3/ ) || [''])[0] } return { lang: getText(el, '.client_def_hd_pn'), pron } }) searchResult.audio = searchResult.result.phsym.reduce( (audio, { lang, pron }) => { if (/us|美/i.test(lang)) { audio['us'] = pron } else if (/uk|英/i.test(lang)) { audio['uk'] = pron } return audio }, {} ) } } // definitions if (options.cdef) { const $container = doc.querySelector('.client_def_container') if ($container) { const $defs = Array.from($container.querySelectorAll('.client_def_bar')) if ($defs.length > 0) { searchResult.result.cdef = $defs.map(el => ({ pos: getText(el, '.client_def_title_bar', transform), def: getText(el, '.client_def_list', transform) })) } } } // tense if (options.tense) { const $infs = Array.from(doc.querySelectorAll('.client_word_change_word')) if ($infs.length > 0) { searchResult.result.infs = $infs.map(el => (el.textContent || '').trim()) } } if (options.sentence > 0) { const $sens = doc.querySelectorAll('.client_sentence_list') const sentences: typeof searchResult.result.sentences = [] for ( let i = 0; i < $sens.length && sentences.length < options.sentence; i++ ) { const el = $sens[i] let mp3 = '' const $audio = el.querySelector('.client_aud_o') if ($audio) { mp3 = (($audio.getAttribute('onclick') || '').match(/https.*\.mp3/) || [ '' ])[0] } el.querySelectorAll('.client_sen_en_word').forEach($word => { $word.outerHTML = getText($word) }) el.querySelectorAll('.client_sen_cn_word').forEach($word => { $word.outerHTML = getText($word, transform) }) el.querySelectorAll('.client_sentence_search').forEach($word => { $word.outerHTML = `<span class="dictBing-SentenceItem_HL">${getText( $word )}</span>` }) sentences.push({ en: getInnerHTML(HOST, el, '.client_sen_en'), chs: getInnerHTML(HOST, el, { selector: '.client_sen_cn', transform }), source: getText(el, '.client_sentence_list_link'), mp3 }) } searchResult.result.sentences = sentences } if (Object.keys(searchResult.result).length > 2) { return searchResult } return handleNoResult() } function handleMachineResult( doc: Document, transform: null | ((text: string) => string) ): BingSearchResultMachine | Promise<BingSearchResultMachine> { const mt = getText(doc, '.client_sen_cn', transform) if (mt) { return { result: { type: 'machine', mt } } } return handleNoResult() } function handleRelatedResult( doc: Document, config: BingConfig, transform: null | ((text: string) => string) ): BingSearchResultRelated | Promise<BingSearchResultRelated> { const searchResult: DictSearchResult<BingResultRelated> = { result: { type: 'related', title: getText(doc, '.client_do_you_mean_title_bar', transform), defs: [] } } doc.querySelectorAll('.client_do_you_mean_area').forEach($area => { const $defsList = $area.querySelectorAll('.client_do_you_mean_list') if ($defsList.length > 0) { searchResult.result.defs.push({ title: getText($area, '.client_do_you_mean_title', transform), meanings: Array.from($defsList).map($list => { const word = getText( $list, '.client_do_you_mean_list_word', transform ) return { href: `https://cn.bing.com/dict/search?q=${word}`, word, def: getText($list, '.client_do_you_mean_list_def', transform) } }) }) } }) if (searchResult.result.defs.length > 0) { return searchResult } return handleNoResult() }
anrgct/ext-saladict
src/components/dictionaries/hjdict/View.tsx
<filename>src/components/dictionaries/hjdict/View.tsx import React, { FC } from 'react' import { HjdictResult, HjdictResultLex, HjdictResultRelated } from './engine' import { ViewPorps } from '@/components/dictionaries/helpers' import { useTranslate } from '@/_helpers/i18n' export const DictHjDict: FC<ViewPorps<HjdictResult>> = props => props.result.type === 'lex' ? ( <Lex {...props} /> ) : props.result.type === 'related' ? ( <Related {...props} /> ) : null export default DictHjDict function Lex(props: ViewPorps<HjdictResult>) { const { header, entries } = props.result as HjdictResultLex return ( <div className="dictHjdict-Entry" onClick={handleClick}> <LangSelect {...props} /> {header && ( <header className="word-details-header" dangerouslySetInnerHTML={{ __html: header }} /> )} {entries.map((entry, i) => ( <div dangerouslySetInnerHTML={{ __html: entry }} key={i} /> ))} </div> ) } function Related(props: ViewPorps<HjdictResult>) { const { content } = props.result as HjdictResultRelated return ( <div> <LangSelect {...props} /> <div className="dictHjdict-Entry" dangerouslySetInnerHTML={{ __html: content }} /> </div> ) } const langSelectList = ['w', 'jp/cj', 'jp/jc', 'kr', 'fr', 'de', 'es'] function LangSelect(props: ViewPorps<HjdictResult>) { const { langCode } = props.result const { t } = useTranslate('dicts') return ( <select value={langCode} onChange={e => props.searchText({ id: 'hjdict', payload: { langCode: e.target.value } }) } > {langSelectList.map(lang => ( <option key={lang} value={lang}> {t(`hjdict.options.chsas-${lang}`)} </option> ))} </select> ) } function handleClick(e: React.MouseEvent<HTMLElement>): void { const $tab = getWordDetailsTab(e.target) if ($tab) { if ($tab.classList.contains('word-details-tab-active')) { return } const container = e.currentTarget if (container) { const index = +($tab.dataset.categories || '0') const $panes = container.querySelectorAll('.word-details-pane') container.querySelectorAll('.word-details-tab').forEach(($tab, i) => { if (i === index) { $tab.classList.add('word-details-tab-active') $panes[i].classList.add('word-details-pane-active') } else { $tab.classList.remove('word-details-tab-active') $panes[i].classList.remove('word-details-pane-active') } }) } } } function getWordDetailsTab(target: any): HTMLElement | null { for (let el = target; el; el = el.parentElement) { if (el.classList && el.classList.contains('word-details-tab')) { return el } } return null }
anrgct/ext-saladict
src/components/dictionaries/etymonline/engine.ts
import { fetchDirtyDOM } from '@/_helpers/fetch-dom' import { DictConfigs } from '@/app-config' import { getText, getInnerHTML, getFullLink, handleNoResult, HTMLString, handleNetWorkError, SearchFunction, GetSrcPageFunction, DictSearchResult } from '../helpers' export const getSrcPage: GetSrcPageFunction = text => { return `http://www.etymonline.com/search?q=${text}` } const HOST = 'https://www.etymonline.com' type EtymonlineResultItem = { title: string def: HTMLString href?: string chart?: string } export type EtymonlineResult = EtymonlineResultItem[] type EtymonlineSearchResult = DictSearchResult<EtymonlineResult> export const search: SearchFunction<EtymonlineResult> = ( text, config, profile, payload ) => { const options = profile.dicts.all.etymonline.options text = encodeURIComponent(text.replace(/\s+/g, ' ')) // http to bypass the referer checking return fetchDirtyDOM('https://www.etymonline.com/word/' + text) .catch(() => fetchDirtyDOM('https://www.etymonline.com/search?q=' + text)) .catch(handleNetWorkError) .then(doc => handleDOM(doc, options)) } function handleDOM( doc: Document, options: DictConfigs['etymonline']['options'] ): EtymonlineSearchResult | Promise<EtymonlineSearchResult> { const result: EtymonlineResult = [] const $items = Array.from(doc.querySelectorAll('[class*="word--"]')) for (let i = 0; i < $items.length && result.length < options.resultnum; i++) { const $item = $items[i] const title = getText($item, '[class*="word__name--"]') if (!title) { continue } let def = '' const $def = $item.querySelector('[class*="word__defination--"]>*') if ($def) { $def.querySelectorAll('.crossreference').forEach($cf => { const word = getText($cf) const $a = document.createElement('a') $a.target = '_blank' $a.href = `https://www.etymonline.com/word/${word}` $a.textContent = word $cf.replaceWith($a) }) def = getInnerHTML(HOST, $def) } if (!def) { continue } const href = getFullLink(HOST, $item, 'href') let chart = '' if (options.chart) { const $chart = $item.querySelector<HTMLImageElement>( '[class*="chart--"] img' ) if ($chart) { chart = getFullLink(HOST, $chart, 'src') } } result.push({ href, title, def, chart }) } if (result.length > 0) { return { result } } return handleNoResult() }
anrgct/ext-saladict
src/options/helpers/upload.ts
<gh_stars>0 import { config$$, profile$$ } from '../data' import { withLatestFrom, switchMap, startWith, share } from 'rxjs/operators' import { from, Subject } from 'rxjs' import set from 'lodash/set' import { updateConfig } from '@/_helpers/config-manager' import { updateProfile } from '@/_helpers/profile-manager' const upload$ = new Subject<{ [path: string]: any }>() export const upload = (values: { [path: string]: any }) => upload$.next(values) export const uploadResult$$ = upload$.pipe( withLatestFrom(config$$, profile$$), switchMap(([values, config, profile]) => { const data: { config?: typeof config; profile?: typeof profile } = {} const paths = Object.keys(values) if (process.env.DEBUG) { if (paths.length <= 0) { console.warn('Saving empty fields.', values) } } for (const path of paths) { if (path.startsWith('config.')) { if (!data.config) { data.config = JSON.parse(JSON.stringify(config)) } set(data, path, values[path]) } else if (path.startsWith('profile.')) { if (!data.profile) { data.profile = JSON.parse(JSON.stringify(profile)) } set(data, path, values[path]) } else { console.error(new Error(`Saving unknown path: ${path}`)) } } const requests: Promise<void>[] = [] if (data.config) { requests.push(updateConfig(data.config)) } if (data.profile) { requests.push(updateProfile(data.profile)) } const pRequests = Promise.all(requests) .then(() => ({ loading: false })) .catch(error => ({ loading: false, error })) if (process.env.DEBUG) { console.log('saved setting', data) } return from(pRequests).pipe(startWith({ loading: true })) }), share<{ loading: boolean; error?: Error }>() )
anrgct/ext-saladict
src/components/WordPage/Header.tsx
import React, { FC } from 'react' import { TFunction } from 'i18next' import { Layout, Input, Dropdown, Menu, Button, Modal } from 'antd' import { ClickParam } from 'antd/lib/menu' import { DownOutlined } from '@ant-design/icons' import { DBArea } from '@/_helpers/record-manager' export interface WordPageProps { t: TFunction area: DBArea searchText: string totalCount: number selectedCount: number onSearchTextChanged: (text: string) => void onExport: (param: ClickParam) => void onDelete: (key: string) => void } export const Header: FC<WordPageProps> = props => { const { t } = props return ( <Layout.Header className="wordpage-Header"> <div className="wordpage-Title"> <h1 className="wordpage-Title_head"> {t(`title.${props.area}`)}{' '} <small className="wordpage-Title_small">({t('localonly')})</small> </h1> <div style={{ whiteSpace: 'nowrap' }}> {props.totalCount > 0 && ( <span className="wordpage-Wordcount"> {t(`wordCount.total`, { count: props.totalCount })} </span> )} {props.selectedCount > 0 && ( <span className="wordpage-Wordcount"> {t(`wordCount.selected`, { count: props.selectedCount })} </span> )} </div> </div> <div className="wordpage-BtnGroup"> <Input style={{ width: '15em' }} placeholder="Search" onChange={e => props.onSearchTextChanged(e.currentTarget.value)} value={props.searchText} /> <Dropdown overlay={ <Menu onClick={props.onExport}> {props.selectedCount > 0 && ( <Menu.Item key="selected">{t('export.selected')}</Menu.Item> )} <Menu.Item key="page">{t('export.page')}</Menu.Item> <Menu.Item key="all">{t('export.all')}</Menu.Item> </Menu> } > <Button style={{ marginLeft: 8 }}> {t('export.title')} <DownOutlined /> </Button> </Dropdown> <Dropdown overlay={ <Menu onClick={({ key }) => { if (key) { Modal.confirm({ title: t('delete'), content: t(`delete.${key}`) + t('delete.confirm'), okType: 'danger', onOk: () => props.onDelete(key) }) } }} > {props.selectedCount > 0 && ( <Menu.Item key="selected">{t('delete.selected')}</Menu.Item> )} <Menu.Item key="page">{t('delete.page')}</Menu.Item> <Menu.Item key="all">{t('delete.all')}</Menu.Item> </Menu> } > <Button type="danger" style={{ marginLeft: 8 }}> {t('delete.title')} <DownOutlined /> </Button> </Dropdown> </div> </Layout.Header> ) }
anrgct/ext-saladict
src/options/components/Entries/General.tsx
<reponame>anrgct/ext-saladict<gh_stars>0 import React, { FC } from 'react' import { Switch, Select } from 'antd' import { getConfigPath } from '@/options/helpers/path-joiner' import { SaladictForm } from '@/options/components/SaladictForm' export const General: FC = () => { return ( <SaladictForm items={[ { name: getConfigPath('active'), valuePropName: 'checked', children: <Switch /> }, { name: getConfigPath('animation'), valuePropName: 'checked', children: <Switch /> }, { name: getConfigPath('darkMode'), valuePropName: 'checked', children: <Switch /> }, { name: getConfigPath('langCode'), children: ( <Select> <Select.Option value="zh-CN">简体中文</Select.Option> <Select.Option value="zh-TW">繁體中文</Select.Option> <Select.Option value="en">English</Select.Option> </Select> ) } ]} /> ) }
anrgct/ext-saladict
src/background/context-menus.ts
import { message, openURL } from '@/_helpers/browser-api' import { AppConfig } from '@/app-config' import isEqual from 'lodash/isEqual' import { createConfigStream } from '@/_helpers/config-manager' import { isFirefox } from '@/_helpers/saladict' import './types' import { TFunction } from 'i18next' import { I18nManager } from './i18n-manager' import { combineLatest } from 'rxjs' import { concatMap, filter, distinctUntilChanged } from 'rxjs/operators' import { openPDF, extractPDFUrl } from './pdf-sniffer' import { copyTextToClipboard } from './clipboard-manager' interface CreateMenuOptions { type?: browser.contextMenus.ItemType id?: string parentId?: string title?: string contexts?: browser.contextMenus.ContextType[] } type ContextMenusClickInfo = Pick< browser.contextMenus.OnClickData, 'menuItemId' | 'selectionText' | 'linkUrl' | 'pageUrl' > export class ContextMenus { static async getInstance() { if (!ContextMenus.instance) { const instance = new ContextMenus() ContextMenus.instance = instance const i18nManager = await I18nManager.getInstance() const contextMenusChanged$ = createConfigStream().pipe( distinctUntilChanged( (config1, config2) => config1 && config2 && isEqual( config1.contextMenus.selected, config2.contextMenus.selected ) ), filter(config => !!config) ) combineLatest(contextMenusChanged$, i18nManager.getFixedT$('menus')) .pipe(concatMap(instance.setContextMenus)) .subscribe() } return ContextMenus.instance } static init = ContextMenus.getInstance static openGoogle() { browser.tabs.executeScript({ file: '/assets/google-page-trans.js' }) // browser.tabs.query({ active: true, currentWindow: true }) // .then(tabs => { // if (tabs.length > 0 && tabs[0].url) { // openURL(`https://translate.google.${cn ? 'cn' : 'com'}/translate?sl=auto&tl=${window.appConfig.langCode}&js=y&prev=_t&ie=UTF-8&u=${encodeURIComponent(tabs[0].url as string)}&edit-text=&act=url`) // } // }) } static openYoudao() { // FF policy if (isFirefox) return // inject youdao script, defaults to the active tab of the current window. browser.tabs .executeScript({ file: '/assets/fanyi.youdao.2.0/main.js' }) .then(result => { if (!result || ((result as any) !== 1 && result[0] !== 1)) { throw new Error() } }) .catch(async () => { // error msg browser.notifications.create({ type: 'basic', eventTime: Date.now() + 4000, iconUrl: browser.runtime.getURL(`assets/icon-128.png`), title: 'Saladict', message: (await I18nManager.getInstance()).i18n.t( 'menus:notification_youdao_err' ) }) }) } static openBaiduPage() { browser.tabs.query({ active: true, currentWindow: true }).then(tabs => { if (tabs.length > 0 && tabs[0].url) { const langCode = window.appConfig.langCode === 'zh-CN' ? 'zh' : window.appConfig.langCode === 'zh-TW' ? 'cht' : 'en' openURL( `https://fanyi.baidu.com/transpage?query=${encodeURIComponent( tabs[0].url as string )}&from=auto&to=${langCode}&source=url&render=1` ) } }) } static openSogouPage() { browser.tabs.query({ active: true, currentWindow: true }).then(tabs => { if (tabs.length > 0 && tabs[0].url) { const langCode = window.appConfig.langCode === 'zh-CN' ? 'zh-CHS' : 'en' openURL( `https://translate.sogoucdn.com/pcvtsnapshot?from=auto&to=${langCode}&tfr=translatepc&url=${encodeURIComponent( tabs[0].url as string )}&domainType=sogou` ) } }) } static openMicrosoftPage() { browser.tabs.query({ active: true, currentWindow: true }).then(tabs => { if (tabs.length > 0 && tabs[0].url) { const langCode = window.appConfig.langCode === 'zh-CN' ? 'zh-CHS' : window.appConfig.langCode === 'zh-TW' ? 'zh-CHT' : 'en' openURL( `https://www.microsofttranslator.com/bv.aspx?from=auto&to=${langCode}&r=true&a=${encodeURIComponent( tabs[0].url as string )}` ) } }) } static requestSelection() { browser.tabs.query({ active: true, currentWindow: true }).then(tabs => { if (tabs.length > 0 && tabs[0].id != null) { message.send(tabs[0].id as number, { type: 'EMIT_SELECTION' }) } }) } private handleContextMenusClick(info: ContextMenusClickInfo) { const menuItemId = String(info.menuItemId).replace(/_ba$/, '') const selectionText = info.selectionText || '' const linkUrl = info.linkUrl || '' switch (menuItemId) { case 'google_page_translate': ContextMenus.openGoogle() break case 'google_cn_page_translate': ContextMenus.openGoogle() break case 'youdao_page_translate': ContextMenus.openYoudao() break case 'baidu_page_translate': ContextMenus.openBaiduPage() break case 'sogou_page_translate': ContextMenus.openSogouPage() break case 'microsoft_page_translate': ContextMenus.openMicrosoftPage() break case 'view_as_pdf': openPDF(linkUrl, info.menuItemId !== 'view_as_pdf_ba') break case 'copy_pdf_url': { const url = extractPDFUrl(info.pageUrl) if (url) { copyTextToClipboard(url) } break } case 'saladict': ContextMenus.requestSelection() break case 'search_history': openURL(browser.runtime.getURL('history.html')) break case 'notebook': openURL(browser.runtime.getURL('notebook.html')) break default: { const item = window.appConfig.contextMenus.all[menuItemId] if (item) { const url = typeof item === 'string' ? item : item.url if (url) { openURL(url.replace('%s', encodeURIComponent(selectionText))) } } } break } } private static instance: ContextMenus // singleton private constructor() { browser.contextMenus.onClicked.addListener(payload => this.handleContextMenusClick(payload) ) message.addListener('CONTEXT_MENUS_CLICK', ({ payload }) => this.handleContextMenusClick(payload) ) } private async setContextMenus([{ contextMenus }, t]: [ AppConfig, TFunction ]): Promise<void> { if (!browser.extension.inIncognitoContext) { // In 'split' incognito mode, this will also remove the items on normal mode windows await browser.contextMenus.removeAll() } const ctx: browser.contextMenus.ContextType[] = [ 'audio', 'editable', 'frame', 'image', 'link', 'selection', 'page', 'video' ] // top level context menus item const containerCtx = new Set<browser.contextMenus.ContextType>([ 'selection' ]) const optionList: CreateMenuOptions[] = [] const browserActionItems: string[] = [] for (const id of contextMenus.selected) { if (isFirefox && id === 'youdao_page_translate') { // FF policy continue } let contexts: browser.contextMenus.ContextType[] switch (id) { case 'google_page_translate': case 'google_cn_page_translate': case 'youdao_page_translate': case 'sogou_page_translate': case 'baidu_page_translate': case 'microsoft_page_translate': // two for browser action contexts = ctx browserActionItems.push(id) break case 'view_as_pdf': containerCtx.add('link') containerCtx.add('page') contexts = ['link', 'page'] break case 'copy_pdf_url': containerCtx.add('page') contexts = ['page'] break default: contexts = ['selection'] break } optionList.push({ id, title: getTitle(id), contexts }) } if (optionList.length > 1) { if (browserActionItems.length > 0) { ctx.forEach(type => containerCtx.add(type)) } await createContextMenu({ id: 'saladict_container', title: t('saladict'), contexts: [...containerCtx] }) for (const opt of optionList) { opt.parentId = 'saladict_container' await createContextMenu(opt) } } else if (optionList.length > 0) { // only one item, no need for parent container await createContextMenu(optionList[0]) } await createContextMenu({ id: 'view_as_pdf_ba', title: t('view_as_pdf'), contexts: ['browser_action', 'page_action'] }) if (browserActionItems.length > 2) { await createContextMenu({ id: 'saladict_ba_container', title: t('page_translations'), contexts: ['browser_action', 'page_action'] }) for (const id of browserActionItems) { await createContextMenu({ id: id + '_ba', parentId: 'saladict_ba_container', title: getTitle(id), contexts: ['browser_action', 'page_action'] }) } } else if (browserActionItems.length > 0) { for (const id of browserActionItems) { await createContextMenu({ id: id + '_ba', title: getTitle(id), contexts: ['browser_action', 'page_action'] }) } } else { // Add only to browser action if not selected await createContextMenu({ id: 'google_cn_page_translate_ba', title: t('google_cn_page_translate'), contexts: ['browser_action', 'page_action'] }) await createContextMenu({ id: 'youdao_page_translate_ba', title: t('youdao_page_translate'), contexts: ['browser_action', 'page_action'] }) } await createContextMenu({ type: 'separator', id: Date.now().toString(), contexts: ['browser_action'] }) // search history await createContextMenu({ id: 'search_history', title: t('history_title'), contexts: ['browser_action'] }) // Manual await createContextMenu({ id: 'notebook', title: t('notebook_title'), contexts: ['browser_action'] }) function getTitle(id: string): string { const item = contextMenus.all[id] return !item || typeof item === 'string' ? t(id) : item.name } function createContextMenu( createProperties: CreateMenuOptions ): Promise<void> { return new Promise(resolve => { browser.contextMenus.create(createProperties, () => { if (browser.runtime.lastError) { console.error(browser.runtime.lastError) } resolve() }) }) } } }
anrgct/ext-saladict
src/components/dictionaries/macmillan/engine.ts
<gh_stars>0 import { fetchDirtyDOM } from '@/_helpers/fetch-dom' import { HTMLString, getInnerHTML, handleNoResult, handleNetWorkError, SearchFunction, GetSrcPageFunction, externalLink, DictSearchResult, removeChildren, getText, removeChild, getFullLink, getOuterHTML } from '../helpers' import { DictConfigs } from '@/app-config' export const getSrcPage: GetSrcPageFunction = text => { return `http://www.macmillandictionary.com/dictionary/british/${text .trim() .split(/\s+/) .join('-')}` } const HOST = 'http://www.macmillandictionary.com' export interface MacmillanResultLex { type: 'lex' title: string senses: HTMLString /** part of speech */ pos?: string /** syntax coding */ sc?: string phsym?: string pron?: string ratting?: number toggleables: HTMLString[] relatedEntries: Array<{ title: string href: string }> } export interface MacmillanResultRelated { type: 'related' list: Array<{ title: string href: string }> } export type MacmillanResult = MacmillanResultLex | MacmillanResultRelated type MacmillanSearchResult = DictSearchResult<MacmillanResult> export interface MacmillanPayload { href?: string } export const search: SearchFunction<MacmillanResult, MacmillanPayload> = ( text, config, profile, payload ) => { const options = profile.dicts.all.macmillan.options return fetchMacmillanDom( payload.href || 'http://www.macmillandictionary.com/dictionary/british/' + text.toLocaleLowerCase().replace(/[^A-Za-z0-9]+/g, '-') ) .catch(handleNetWorkError) .then(doc => checkResult(doc, options)) } async function checkResult( doc: Document, options: DictConfigs['macmillan']['options'] ): Promise<MacmillanSearchResult> { if (doc.querySelector('.senses')) { return handleDOM(doc) } else if (options.related) { const alternatives = [ ...doc.querySelectorAll<HTMLAnchorElement>('.display-list li a') ].map($a => ({ title: getText($a), href: getFullLink(HOST, $a, 'href') })) if (alternatives.length > 0) { return { result: { type: 'related', list: alternatives } } } } return handleNoResult() } function handleDOM( doc: Document ): MacmillanSearchResult | Promise<MacmillanSearchResult> { const $entry = doc.querySelector('#entryContent .left-content') if (!$entry) { return handleNoResult() } const result: MacmillanResultLex = { type: 'lex', title: getText($entry, '.big-title .BASE'), senses: '', toggleables: [], relatedEntries: [] } if (!result.title) { return handleNoResult() } $entry .querySelectorAll<HTMLAnchorElement>('a.moreButton') .forEach(externalLink) result.senses = getInnerHTML(HOST, $entry, '.senses') if (!result.senses) { return handleNoResult() } removeChild($entry, '.senses') result.pos = getText($entry, '.entry-pron-head .PART-OF-SPEECH') result.sc = getText($entry, '.entry-pron-head .SYNTAX-CODING') result.phsym = getText($entry, '.entry-pron-head .PRON') result.ratting = $entry.querySelectorAll('.entry-red-star').length $entry.querySelectorAll('.toggleable').forEach($toggleable => { result.toggleables.push(getOuterHTML(HOST, $toggleable)) }) doc .querySelectorAll<HTMLAnchorElement>('.related-entries-item a') .forEach($a => { const $pos = $a.querySelector('.PART-OF-SPEECH') if ($pos) { $pos.textContent = getText($pos).toUpperCase() } result.relatedEntries.push({ title: getText($a), href: getFullLink(HOST, $a, 'href') }) }) const audio: { uk?: string } = {} const $sound = $entry.querySelector<HTMLDivElement>( '.entry-pron-head .PRONS .sound' ) if ($sound && $sound.dataset.srcMp3) { result.pron = $sound.dataset.srcMp3 audio.uk = result.pron } return { result, audio } } async function fetchMacmillanDom(url: string): Promise<Document> { const doc = await fetchDirtyDOM(url) removeChildren(doc, '.visible-xs') return doc }
anrgct/ext-saladict
src/components/dictionaries/wikipedia/View.tsx
<filename>src/components/dictionaries/wikipedia/View.tsx import React, { FC, useState, ReactNode, useEffect } from 'react' import { WikipediaResult, WikipediaPayload, fetchLangList, LangList } from './engine' import { ViewPorps } from '@/components/dictionaries/helpers' import { message } from '@/_helpers/browser-api' import { useTranslate } from '@/_helpers/i18n' export const DictWikipedia: FC<ViewPorps<WikipediaResult>> = ({ result, searchText }) => { const [langList, setLangList] = useState<LangList>() const { t } = useTranslate('content') useEffect(() => { setLangList([]) }, [result.langSelector]) const handleSelectChanged = (e: React.ChangeEvent<HTMLSelectElement>) => { if (e.target.value) { searchText<WikipediaPayload>({ id: 'wikipedia', payload: { url: e.target.value } }) } } let langSelector: ReactNode = null if (langList && langList.length > 0) { langSelector = ( <select onChange={handleSelectChanged} defaultValue={''}> <option key="" value=""> {t('chooseLang')} </option> {langList.map(item => ( <option key={item.url} value={item.url}> {item.title} </option> ))} </select> ) } else if (result.langSelector) { langSelector = ( <button className="dictWikipedia-LangSelectorBtn" onClick={async () => { setLangList( await message.send< 'DICT_ENGINE_METHOD', ReturnType<typeof fetchLangList> >({ type: 'DICT_ENGINE_METHOD', payload: { id: 'wikipedia', method: 'fetchLangList', args: [result.langSelector] } }) ) }} > {t('fetchLangList')} </button> ) } return ( <> <h1 className="dictWikipedia-Title">{result.title}</h1> {langSelector} <div className="dictWikipedia-Content" onClick={handleEntryClick}> <div className="client-js" dangerouslySetInnerHTML={{ __html: result.content }} /> </div> </> ) } function handleEntryClick(e: React.MouseEvent<HTMLDivElement>) { if (!e.target['classList']) { return } let $header = e.target as HTMLElement if (!$header.classList.contains('section-heading')) { $header = $header.parentElement as HTMLElement if (!$header || !$header.classList.contains('section-heading')) { return } } e.stopPropagation() e.preventDefault() // Toggle titles $header.classList.toggle('open-block') const $content = $header.nextElementSibling if ($content) { const pressed = $header.classList.contains('open-block').toString() $content.classList.toggle('open-block') $content.setAttribute('aria-pressed', pressed) $content.setAttribute('aria-expanded', pressed) } const $arrow = $header.querySelector('.mw-ui-icon-mf-arrow') if ($arrow) { $arrow.classList.toggle('mf-mw-ui-icon-rotate-flip') } } export default DictWikipedia
anrgct/ext-saladict
src/options/__fake__/env.ts
<reponame>anrgct/ext-saladict<filename>src/options/__fake__/env.ts import { initConfig } from '@/_helpers/config-manager' import { initProfiles } from '@/_helpers/profile-manager' initConfig() initProfiles()
anrgct/ext-saladict
src/content/components/WordEditor/WordEditor.tsx
import React, { FC } from 'react' import classNames from 'classnames' import { Notes, NotesProps } from './Notes' import { SALADICT_EXTERNAL } from '@/_helpers/saladict' export interface WordEditorProps extends NotesProps { darkMode: boolean } export const WordEditor: FC<WordEditorProps> = props => { const { darkMode, ...restProps } = props return ( <div className={classNames(SALADICT_EXTERNAL, 'saladict-theme', { darkMode })} > <Notes {...restProps} /> </div> ) }
anrgct/ext-saladict
src/options/components/Entries/ContextMenus/EditeModal.tsx
<reponame>anrgct/ext-saladict import React, { FC, useMemo, useRef } from 'react' import { Input, Modal, Form } from 'antd' import { ExclamationCircleOutlined } from '@ant-design/icons' import { FormInstance } from 'antd/lib/form/Form' import { useObservableGetState, useSubscription } from 'observable-hooks' import { useTranslate } from '@/_helpers/i18n' import { config$$ } from '@/options/data' import { upload, uploadResult$$ } from '@/options/helpers/upload' export interface EditModalProps { menuID?: string | null onClose: () => void } export const EditModal: FC<EditModalProps> = ({ menuID, onClose }) => { const { t } = useTranslate(['options', 'dicts', 'common', 'langcode']) const formRef = useRef<FormInstance>(null) const allMenus = useObservableGetState(config$$, 'contextMenus', 'all')! const namePath = `config.contextMenus.all.${menuID}.name` const urlPath = `config.contextMenus.all.${menuID}.url` const initialValues = useMemo(() => { if (menuID) { const item = allMenus[menuID] if (typeof item === 'string') { return { [namePath]: t(`menus:${menuID}`), [urlPath]: item } } if (item) { return { [namePath]: item.name, [urlPath]: item.url } } } return { [namePath]: '', [urlPath]: '' } }, [allMenus, menuID]) useSubscription(uploadResult$$, result => { if (menuID && !result.loading && !result.error) { onClose() } }) return ( <Modal visible={!!menuID} zIndex={1001} title={t(`config.opt.contextMenus_edit`)} destroyOnClose onOk={submitForm} onCancel={closeModal} > <Form ref={formRef} initialValues={initialValues} onFinish={upload}> <Form.Item name={namePath} label={t('common:name')}> <Input /> </Form.Item> <Form.Item name={urlPath} label="URL"> <Input /> </Form.Item> </Form> </Modal> ) function submitForm() { if (formRef.current) { formRef.current.submit() } } function closeModal() { if (formRef.current && formRef.current.isFieldsTouched()) { Modal.confirm({ zIndex: 1002, title: t('syncService.close_confirm'), icon: <ExclamationCircleOutlined />, okType: 'danger', onOk: onClose }) } else { onClose() } } }
anrgct/ext-saladict
src/components/dictionaries/lexico/View.tsx
<reponame>anrgct/ext-saladict import React, { FC } from 'react' import { LexicoResult, LexicoResultLex, LexicoResultRelated } from './engine' import { ViewPorps } from '@/components/dictionaries/helpers' export const DictLexico: FC<ViewPorps<LexicoResult>> = ({ result }) => { switch (result.type) { case 'lex': return renderLex(result) case 'related': return renderRelated(result) default: return null } } function renderLex(result: LexicoResultLex) { return ( <div className="dictLexico-Lex" dangerouslySetInnerHTML={{ __html: result.entry }} onClick={onLexClick} /> ) } function renderRelated(result: LexicoResultRelated) { return ( <> <p>Did you mean:</p> <ul className="dictLexico-Related"> {result.list.map((item, i) => ( <li key={i}> <a rel="nofollow noopener noreferrer" target="_blank" href={item.href} > {item.text} </a> </li> ))} </ul> </> ) } export default DictLexico function onLexClick(e: React.MouseEvent): void { const $target = e.target as Element const $info = $target.classList?.contains('moreInfo') ? $target : $target.parentElement?.classList?.contains('moreInfo') ? $target.parentElement : null if ($info) { $info.classList.toggle('active') } }
anrgct/ext-saladict
src/content/components/DictPanel/DictPanelStandalone.container.tsx
<gh_stars>0 import React from 'react' import { connect } from 'react-redux' import { DictPanelStandalone, DictPanelStandaloneProps } from './DictPanelStandalone' import { StoreState } from '@/content/redux/modules' import { MenuBarContainer } from '../MenuBar/MenuBar.container' import { MtaBoxContainer } from '../MtaBox/MtaBox.container' import { DictListContainer } from '../DictList/DictList.container' import { WaveformBoxContainer } from '../WaveformBox/WaveformBox.container' const menuBar = <MenuBarContainer /> const mtaBox = <MtaBoxContainer /> const dictList = <DictListContainer /> const waveformBox = <WaveformBoxContainer /> type OwnProps = 'height' | 'width' const mapStateToProps = ( state: StoreState, ownProps: Pick<DictPanelStandaloneProps, OwnProps> ): DictPanelStandaloneProps => { return { withAnimation: state.config.animation, darkMode: state.config.darkMode, panelCSS: state.config.panelCSS, fontSize: state.config.fontSize, menuBar, mtaBox, dictList, waveformBox, width: ownProps.width, height: ownProps.height } } export const DictPanelStandaloneContainer = connect(mapStateToProps)( DictPanelStandalone ) export default DictPanelStandaloneContainer
anrgct/ext-saladict
src/background/database.ts
import Dexie from 'dexie' import { isContainChinese, isContainEnglish } from '@/_helpers/lang-check' import { Word, DBArea } from '@/_helpers/record-manager' import { syncServiceUpload } from './sync-manager' import { Message, MessageResponse } from '@/typings/message' export class SaladictDB extends Dexie { // @ts-ignore notebook: Dexie.Table<Word, number> // @ts-ignore history: Dexie.Table<Word, number> // @ts-ignore syncmeta: Dexie.Table<{ id: string; json: string }, string> constructor() { super('SaladictWords') this.version(1).stores({ notebook: 'date,text,context,url', history: 'date,text,context,url', syncmeta: 'id' }) // The following lines are needed if your typescript // is compiled using babel instead of tsc: this.notebook = this.table('notebook') this.history = this.table('history') this.syncmeta = this.table('syncmeta') } } export const db = new SaladictDB() /* ----------------------------------------------- *\ Apis \* ----------------------------------------------- */ export function getSyncMeta(serviceID: string) { return db.syncmeta .where('id') .equals(serviceID) .first(record => record && record.json) .catch(e => { if (process.env.DEBUG) { console.error(e) } }) } export function setSyncMeta(serviceID: string, text: string) { return db.syncmeta.put({ id: serviceID, json: text }) } export function deleteSyncMeta(serviceID: string) { return db.syncmeta.delete(serviceID).catch(e => { if (process.env.DEBUG) { console.error(e) } }) } export function isInNotebook(word: Message<'IS_IN_NOTEBOOK'>['payload']) { return db.notebook .where('text') .equalsIgnoreCase(word.text) .count() .then(count => count > 0) } export function saveWord({ area, word, fromSync }: Message<'SAVE_WORD'>['payload']) { if (!fromSync && area === 'notebook') { syncServiceUpload({ op: 'ADD', words: [word] }).catch(() => {}) } return db[area].put(word) } export function saveWords({ area, words, fromSync }: { area: DBArea words: Word[] fromSync?: boolean // sync services }) { if (process.env.DEBUG) { if (words.length !== new Set(words.map(w => w.date)).size) { console.error('save Words: duplicate records') } } if (!fromSync && area === 'notebook') { syncServiceUpload({ op: 'ADD', words }).catch(() => { /* nothing */ }) } return db[area].bulkPut(words) } export function deleteWords({ area, dates }: Message<'DELETE_WORDS'>['payload']) { if (area === 'notebook') { syncServiceUpload({ op: 'DELETE', dates }).catch(() => { /* nothing */ }) } return Array.isArray(dates) ? db[area].bulkDelete(dates) : db[area].clear() } export function getWordsByText({ area, text }: Message<'GET_WORDS_BY_TEXT'>['payload']) { return db[area] .where('text') .equalsIgnoreCase(text) .toArray() } export async function getWords({ area, itemsPerPage, pageNum, filters = {}, sortField = 'date', sortOrder = 'descend', searchText }: Message<'GET_WORDS'>['payload']): Promise<MessageResponse<'GET_WORDS'>> { const collection = db[area].orderBy( sortField ? Array.isArray(sortField) ? sortField.map(str => String(str)) : String(sortField) : 'date' ) if (!sortOrder || sortOrder === 'descend') { collection.reverse() } const shouldFilter = Array.isArray(filters.text) && filters.text.length > 0 if (shouldFilter || searchText) { const validLangs = shouldFilter ? (filters.text as string[]).reduce((o, l) => { o[l] = true return o }, {}) : {} const ls = searchText ? searchText.toLocaleLowerCase() : '' collection.filter(record => { const rText = shouldFilter ? (validLangs['en'] && isContainEnglish(record.text)) || (validLangs['ch'] && isContainChinese(record.text)) || (validLangs['word'] && !/\s/.test(record.text)) || (validLangs['phra'] && /\s/.test(record.text)) : true const rSearch = searchText ? Object.values(record).some( v => typeof v === 'string' && v.toLocaleLowerCase().indexOf(ls) !== -1 ) : true return rText && rSearch }) } const total = await collection.count() if (typeof itemsPerPage !== 'undefined' && typeof pageNum !== 'undefined') { collection.offset(itemsPerPage * (pageNum - 1)).limit(itemsPerPage) } const words = await collection.toArray() return { total, words } } db.open()
anrgct/ext-saladict
src/options/components/Entries/SearchModes/index.tsx
<reponame>anrgct/ext-saladict import React, { FC } from 'react' import { Switch, Checkbox, Slider } from 'antd' import { useTranslate } from '@/_helpers/i18n' import { getConfigPath, getProfilePath } from '@/options/helpers/path-joiner' import { SaladictForm } from '@/options/components/SaladictForm' import { supportedLangs } from '@/_helpers/lang-check' import { searchMode } from './searchMode' export const SearchModes: FC = () => { const { t } = useTranslate(['options', 'common']) return ( <SaladictForm items={[ { name: getConfigPath('noTypeField'), valuePropName: 'checked', children: <Switch /> }, { name: getConfigPath('touchMode'), valuePropName: 'checked', children: <Switch /> }, { key: getConfigPath('language'), className: 'saladict-form-danger-extra', items: supportedLangs.map(lang => ({ name: getConfigPath('language', lang), className: 'form-item-inline', valuePropName: 'checked', children: <Checkbox>{t(`common:lang.${lang}`)}</Checkbox> })) }, { name: getProfilePath('stickyFold'), valuePropName: 'checked', children: <Switch /> }, { name: getConfigPath('doubleClickDelay'), children: ( <Slider tipFormatter={v => v + t('common:unit.ms')} min={100} max={2000} marks={{ 100: '0.1' + t('common:unit.s'), 2000: '2' + t('common:unit.s') }} /> ) }, searchMode('mode', t), searchMode('pinMode', t), searchMode('panelMode', t) ]} /> ) }
anrgct/ext-saladict
src/content/components/DictPanel/DictPanel.portal.tsx
import React, { FC, useRef, useState } from 'react' import { ShadowPortal, defaultTimeout } from '@/components/ShadowPortal' import { DictPanel, DictPanelProps } from './DictPanel' import { SALADICT_PANEL } from '@/_helpers/saladict' import { useUpdateEffect } from 'react-use' export interface DictPanelPortalProps extends DictPanelProps { show: boolean withAnimation: boolean panelCSS: string } export const DictPanelPortal: FC<DictPanelPortalProps> = props => { const { show: showProps, panelCSS, ...restProps } = props const showRef = useRef(showProps) const [show, setShow] = useState(showProps) useUpdateEffect(() => { setShow(showProps) }, [showProps]) // Restore if panel was hidden before snapshot, // otherwise ignore. useUpdateEffect(() => { if (props.takeCoordSnapshot) { showRef.current = show } else if (!showRef.current) { setShow(false) } }, [props.takeCoordSnapshot]) return ( <ShadowPortal id="saladict-dictpanel-root" head={<style>{require('./DictPanel.shadow.scss').toString()}</style>} shadowRootClassName={SALADICT_PANEL} panelCSS={panelCSS} in={show} timeout={props.withAnimation ? defaultTimeout : 0} > {() => <DictPanel {...restProps} />} </ShadowPortal> ) } export default DictPanelPortal
anrgct/ext-saladict
src/components/dictionaries/youdao/View.tsx
<reponame>anrgct/ext-saladict import React, { FC } from 'react' import Speaker from '@/components/Speaker' import StarRates from '@/components/StarRates' import { YoudaoResult, YoudaoResultLex, YoudaoResultRelated } from './engine' import { ViewPorps } from '@/components/dictionaries/helpers' import EntryBox from '@/components/EntryBox' export const DictYoudao: FC<ViewPorps<YoudaoResult>> = ({ result }) => { switch (result.type) { case 'lex': return renderLex(result) case 'related': return renderRelated(result) default: return null } } export default DictYoudao function renderLex(result: YoudaoResultLex) { return ( <> {result.title && ( <div className="dictYoudao-HeaderContainer"> <h1 className="dictYoudao-Title">{result.title}</h1> <span className="dictYoudao-Pattern">{result.pattern}</span> </div> )} {(result.stars > 0 || result.prons.length > 0) && ( <div className="dictYoudao-HeaderContainer"> {result.stars > 0 && ( <StarRates className="dictYoudao-Stars" rate={result.stars} /> )} {result.prons.map(({ phsym, url }) => ( <React.Fragment key={url}> {phsym} <Speaker src={url} /> </React.Fragment> ))} <span className="dictYoudao-Rank">{result.rank}</span> </div> )} {result.basic && ( <div className="dictYoudao-Basic" dangerouslySetInnerHTML={{ __html: result.basic }} /> )} {result.collins && ( <EntryBox title="柯林斯英汉双解"> <ul className="dictYoudao-Collins" dangerouslySetInnerHTML={{ __html: result.collins }} /> </EntryBox> )} {result.discrimination && ( <div className="dictYoudao-Discrimination"> <h1 className="dictYoudao-Discrimination_Title">词义辨析</h1> <div dangerouslySetInnerHTML={{ __html: result.discrimination }} /> </div> )} {result.sentence && ( <EntryBox title="权威例句"> <ol className="dictYoudao-Sentence" dangerouslySetInnerHTML={{ __html: result.sentence }} /> </EntryBox> )} {result.translation && ( <EntryBox title="机器翻译"> <div className="dictYoudao-Translation" dangerouslySetInnerHTML={{ __html: result.translation }} /> </EntryBox> )} </> ) } function renderRelated(result: YoudaoResultRelated) { return ( <div className="dictYoudao-Related" dangerouslySetInnerHTML={{ __html: result.list }} /> ) }
anrgct/ext-saladict
src/options/components/MatchPatternModal/index.tsx
import React, { FC, useContext, useRef } from 'react' import { useSubscription } from 'observable-hooks' import { Form, Modal, Button } from 'antd' import { FormInstance, Rule } from 'antd/lib/form' import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons' import { useTranslate, Trans } from '@/_helpers/i18n' import { matchPatternToRegExpStr } from '@/_helpers/matchPatternToRegExpStr' import { GlobalsContext } from '@/options/data' import { uploadResult$$, upload } from '@/options/helpers/upload' import { getConfigPath } from '@/options/helpers/path-joiner' import { PatternItem } from './ PatternItem' export interface MatchPatternModalProps { area: null | 'pdfWhitelist' | 'pdfBlacklist' | 'whitelist' | 'blacklist' onClose: () => void } export const MatchPatternModal: FC<MatchPatternModalProps> = ({ area, onClose }) => { const { t } = useTranslate(['options', 'common']) const globals = useContext(GlobalsContext) const formRef = useRef<FormInstance>(null) useSubscription(uploadResult$$, result => { // successfully saved if (area && !result.loading && !result.error) { onClose() } }) const title = area ? (area.startsWith('pdf') ? 'PDF ' : '') + t(area.endsWith('hitelist') ? 'common:whitelist' : 'common:blacklist') : t('nav.BlackWhiteList') async function validatePatterns(rule: Rule, value: [string, string]) { if (value[1]) { // url value[0] = matchPatternToRegExpStr(value[1]) if (!value[0]) { throw new Error(t('matchPattern.url_error')) } } else if (value[0]) { // regex try { RegExp(value[0]) } catch (e) { throw new Error(t('matchPattern.regex_error')) } } } return ( <Modal visible={!!area} title={title} destroyOnClose onOk={() => { if (formRef.current) { formRef.current.submit() } }} onCancel={() => { if (formRef.current && formRef.current.isFieldsTouched()) { Modal.confirm({ title: t('unsave_confirm'), icon: <ExclamationCircleOutlined />, okType: 'danger', onOk: onClose }) } else { onClose() } }} > <p> <Trans message={t('matchPattern.description')}> <a href="https://developer.mozilla.org/zh-CN/Add-ons/WebExtensions/Match_patterns#范例" target="_blank" rel="nofollow noopener noreferrer" > {t('matchPattern.url')} </a> <a href="https://deerchao.cn/tutorials/regex/regex.htm" target="_blank" rel="nofollow noopener noreferrer" > {t('matchPattern.regex')} </a> </Trans> </p> <Form ref={formRef} wrapperCol={{ span: 24 }} initialValues={area ? { patterns: globals.config[area] } : {}} onFinish={values => { if (area) { const patterns: [string, string][] | undefined = values.patterns upload({ [getConfigPath(area)]: (patterns || []).filter(p => p[0]) }) } }} > <Form.List name="patterns"> {(fields, { add }) => ( <div> {fields.map(field => ( <Form.Item key={field.key} {...field} validateTrigger={['onChange', 'onBlur']} hasFeedback rules={[{ validator: validatePatterns }]} > <PatternItem /> </Form.Item> ))} <Form.Item> <Button type="dashed" block onClick={() => add(['', ''])}> <PlusOutlined /> {t('common:add')} </Button> </Form.Item> </div> )} </Form.List> </Form> </Modal> ) }
anrgct/ext-saladict
src/content/components/MenuBar/MenuBar.container.tsx
import { connect } from 'react-redux' import { ExtractDispatchers, MapStateToProps, MapDispatchToPropsFunction } from 'react-retux' import { StoreState, StoreDispatch } from '@/content/redux/modules' import { updateActiveProfileID } from '@/_helpers/profile-manager' import { isStandalonePage, isPopupPage, isQuickSearchPage } from '@/_helpers/saladict' import { newWord } from '@/_helpers/record-manager' import { message } from '@/_helpers/browser-api' import { MenuBar, MenuBarProps } from './MenuBar' import { updateConfig } from '@/_helpers/config-manager' import { timer } from '@/_helpers/promise-more' import { objectKeys } from '@/typings/helpers' type Dispatchers = ExtractDispatchers< MenuBarProps, | 'searchText' | 'updateText' | 'addToNoteBook' | 'updateHistoryIndex' | 'togglePin' | 'toggleQSFocus' | 'onClose' | 'onSwitchSidebar' | 'onSelectProfile' | 'onDragAreaMouseDown' | 'onDragAreaTouchStart' | 'onHeightChanged' > const mapStateToProps: MapStateToProps< StoreState, MenuBarProps, Dispatchers > = state => ({ text: state.text, isInNotebook: state.isFav, shouldFocus: !state.isExpandMtaBox && // multiline search box must be folded (((state.isQSPanel || isQuickSearchPage()) && // is quick search panel state.config.qsFocus) || isPopupPage()), // or popup page enableSuggest: state.config.searchSuggests, histories: state.searchHistory, historyIndex: state.historyIndex, showedDictAuth: state.config.showedDictAuth, profiles: state.profiles, activeProfileId: state.activeProfile.id, isPinned: state.isPinned, isQSFocus: state.isQSFocus }) const mapDispatchToProps: MapDispatchToPropsFunction< StoreDispatch, MenuBarProps, Dispatchers > = dispatch => ({ searchText: text => { dispatch({ type: 'SEARCH_START', payload: { word: newWord({ text, title: 'Saladict', favicon: 'https://saladict.crimx.com/favicon.ico' }) } }) }, updateText: text => { dispatch({ type: 'UPDATE_TEXT', payload: text }) }, addToNoteBook: () => { dispatch({ type: 'ADD_TO_NOTEBOOK' }) }, updateHistoryIndex: index => { dispatch({ type: 'UPDATE_HISTORY_INDEX', payload: index }) dispatch({ type: 'SEARCH_START', payload: { noHistory: true } }) }, togglePin: () => { dispatch({ type: 'TOGGLE_PIN' }) }, toggleQSFocus: () => { dispatch({ type: 'TOGGLE_QS_FOCUS' }) }, onClose: () => { if (isStandalonePage()) { window.close() } else { dispatch({ type: 'CLOSE_PANEL' }) } }, onSwitchSidebar: (side: 'left' | 'right') => { message.send({ type: 'QS_SWITCH_SIDEBAR', payload: side }) }, onHeightChanged: (height: number) => { dispatch({ type: 'UPDATE_PANEL_HEIGHT', payload: { area: 'menubar', height: 30, floatHeight: height } }) }, onDragAreaMouseDown: event => { dispatch({ type: 'DRAG_START_COORD', payload: { x: event.clientX, y: event.clientY } }) }, onDragAreaTouchStart: event => { dispatch({ type: 'DRAG_START_COORD', payload: { x: event.changedTouches[0].clientX, y: event.changedTouches[0].clientY } }) }, onSelectProfile: id => { dispatch(async (dispatch, getState) => { const state = getState() const { showedDictAuth, dictAuth } = state.config // no jumping on popup page which breaks user flow if (!showedDictAuth && !isPopupPage()) { await updateConfig({ ...state.config, showedDictAuth: true }) if ( objectKeys(dictAuth).every(id => objectKeys(dictAuth[id]).every(k => !dictAuth[id]?.[k]) ) ) { message.send({ type: 'OPEN_URL', payload: { url: 'options.html?menuselected=DictAuths', self: true } }) return } } await updateActiveProfileID(id) await timer(10) dispatch({ type: 'SEARCH_START', payload: { word: state.searchHistory[state.historyIndex]?.text === state.text ? state.searchHistory[state.historyIndex] : newWord({ text: state.text, title: 'Saladict', favicon: 'https://saladict.crimx.com/favicon.ico' }) } }) }) } }) export const MenuBarContainer = connect( mapStateToProps, mapDispatchToProps )(MenuBar) export default MenuBarContainer
anrgct/ext-saladict
src/components/dictionaries/locales.ts
interface LocaleItem { en: string 'zh-CN': string 'zh-TW': string } interface LocaleObject { [name: string]: LocaleItem } export function getMachineLocales( name: LocaleItem, options: LocaleObject = {}, helps: LocaleObject = {} ): { name: LocaleItem options: LocaleObject helps: LocaleObject } { return { name, options: { keepLF: { en: 'Keep linebreaks', 'zh-CN': '保留换行', 'zh-TW': '保留換行' }, 'keepLF-none': { en: 'None', 'zh-CN': '不保留', 'zh-TW': '不保留' }, 'keepLF-all': { en: 'All', 'zh-CN': '全保留', 'zh-TW': '全保留' }, 'keepLF-pdf': { en: 'PDF', 'zh-CN': '保留 PDF 换行', 'zh-TW': '保留 PDF 換行' }, 'keepLF-webpage': { en: 'Webpage', 'zh-CN': '保留网页换行', 'zh-TW': '保留網頁換行' }, tl: { en: 'Target language', 'zh-CN': '目标语言', 'zh-TW': '目標語言' }, tl2: { en: 'Fallback target language', 'zh-CN': '第二目标语言', 'zh-TW': '第二目標語言' }, ...options }, helps: { tl2: { en: 'Fallback when detected languange and target language are identical', 'zh-CN': '如果检测的源语言与目标语言相同将自动切换第二目标语言', 'zh-TW': '如果檢測的源語言與目標語言相同將自動切換第二目標語言' }, ...helps } } }
anrgct/ext-saladict
src/selection/select-text.ts
import { empty, fromEvent, merge, timer, Observable } from 'rxjs' import { withLatestFrom, filter, map, mapTo, debounce, switchMap, scan, startWith, throttle, delay, distinctUntilChanged } from 'rxjs/operators' import { useObservable, useObservableCallback, identity, useSubscription } from 'observable-hooks' import { AppConfig } from '@/app-config' import { isInDictPanel, isInSaladictExternal, isFirefox } from '@/_helpers/saladict' import { getTextFromSelection, getSentenceFromSelection } from 'get-selection-more' import { checkSupportedLangs } from '@/_helpers/lang-check' import { Message } from '@/typings/message' import { isTypeField, newSelectionWord } from './helper' export function createSelectTextStream(config: AppConfig | null) { if (!config) { return empty() } return config.touchMode ? withTouchMode(config) : withoutTouchMode(config) } function withTouchMode(config: AppConfig) { const mousedown$ = merge( fromEvent<MouseEvent>(window, 'mousedown', { capture: true }).pipe( filter(e => e.button === 0) ), fromEvent<TouchEvent>(window, 'touchstart', { capture: true }).pipe( map(e => e.changedTouches[0]) ) ) const mouseup$ = merge( fromEvent<MouseEvent>(window, 'mouseup', { capture: true }).pipe( filter(e => e.button === 0) ), fromEvent<TouchEvent>(window, 'touchend', { capture: true }).pipe( map(e => e.changedTouches[0]) ) ) const clickPeriodCount$ = clickPeriodCountStream( mouseup$, config.doubleClickDelay ) const isMouseDown$ = merge( mapTo(true)(mousedown$), mapTo(false)(mouseup$), mapTo(false)(fromEvent(window, 'mouseout', { capture: true })), mapTo(false)(fromEvent(window, 'blur', { capture: true })) ) return fromEvent(document, 'selectionchange').pipe( withLatestFrom(isMouseDown$), debounce(([, isWithMouse]) => (isWithMouse ? mouseup$ : timer(400))), map(([, isWithMouse]) => [window.getSelection(), isWithMouse] as const), filter( (args): args is [Selection, boolean] => !!args[0] && !isInSaladictExternal(args[0].anchorNode) ), withLatestFrom(mouseup$, mousedown$, clickPeriodCount$), map(([[selection, isWithMouse], mouseup, mousedown, clickPeriodCount]) => { const self = isInDictPanel(selection.anchorNode || mousedown.target) if ( config.noTypeField && isTypeField(isWithMouse ? mousedown.target : selection.anchorNode) ) { return { self } } const text = getTextFromSelection(selection) if (!checkSupportedLangs(config.language, text)) { return { self } } if (isWithMouse) { return { word: { text, context: getSentenceFromSelection(selection) }, self, dbClick: clickPeriodCount >= 2, mouseX: mouseup.clientX, mouseY: mouseup.clientY, altKey: !!mouseup['altKey'], shiftKey: !!mouseup['shiftKey'], ctrlKey: !!mouseup['ctrlKey'], metaKey: !!mouseup['metaKey'] } } const rect = selection.getRangeAt(0).getBoundingClientRect() if ( rect.top === 0 && rect.left === 0 && rect.width === 0 && rect.height === 0 ) { // Selection is made inside textarea with keyborad. Ignore. return { self } } return { word: { text, context: getSentenceFromSelection(selection) }, self, dbClick: clickPeriodCount >= 2, mouseX: rect.right, mouseY: rect.top } }), throttle(result => { // Firefox will fire an extra selectionchange event // when selection is made inside dict panel and // continute search is triggered. // Need to skip this event otherwise the panel is // closed unexpectedly. if (isFirefox && result.self && result.word && result.word.text) { const { direct, double, holding } = config.panelMode if ( direct || (double && result.dbClick) || (holding.alt && result.altKey) || (holding.shift && result.shiftKey) || (holding.ctrl && result.ctrlKey) || (holding.meta && result.metaKey) ) { return timer(500) } } return timer(0) }) ) } function withoutTouchMode(config: AppConfig) { const mousedown$ = fromEvent<MouseEvent>(window, 'mousedown', { capture: true }).pipe(filter(e => e.button === 0)) const mouseup$ = fromEvent<MouseEvent>(window, 'mouseup', { capture: true }).pipe(filter(e => e.button === 0)) const clickPeriodCount$ = clickPeriodCountStream( mouseup$, config.doubleClickDelay ) return mouseup$.pipe( filter(e => !isInSaladictExternal(e.target)), // if user click on a selected text, // getSelection would reture the text before the highlight disappears // delay to wait for selection get cleared delay(10), withLatestFrom(mousedown$, clickPeriodCount$), // handle in-panel search separately // due to tricky shadow dom event retarget filter( ([mouseup, mousedown]) => !isInDictPanel(mouseup.target) && !isInDictPanel(mousedown.target) ), map(([mouseup, mousedown, clickPeriodCount]) => { if (config.noTypeField && isTypeField(mousedown.target)) { return { self: false } } const selection = window.getSelection() const text = getTextFromSelection(selection) if (!checkSupportedLangs(config.language, text)) { return { self: false } } return { word: { text, context: getSentenceFromSelection(selection) }, self: false, dbClick: clickPeriodCount >= 2, mouseX: mouseup.clientX, mouseY: mouseup.clientY, altKey: mouseup.altKey, shiftKey: mouseup.shiftKey, ctrlKey: mouseup.ctrlKey, metaKey: mouseup.metaKey } }), distinctUntilChanged((oldVal, newVal) => { // (Ignore this rule if it is a double click.) // Same selection. This could be caused by other widget on the page // that uses preventDefault which stops selection being cleared when clicked. // Ignore it so that the panel won't follow. return ( !newVal.dbClick && !!oldVal.word && !!newVal.word && oldVal.word.text === newVal.word.text && oldVal.word.context === newVal.word.context ) }) ) } export function useInPanelSelect( touchMode: AppConfig['touchMode'], language: AppConfig['language'], doubleClickDelay: AppConfig['doubleClickDelay'], newSelection: (payload: Message<'SELECTION'>['payload']) => void ) { const [onMouseUp, mouseUp$] = useObservableCallback<React.MouseEvent>( event$ => event$.pipe(filter(e => e.button === 0)) ) const config$ = useObservable(identity, [touchMode, language] as const) const clickPeriodCount$ = useObservable( inputs$ => inputs$.pipe( switchMap(([doubleClickDelay]) => clickPeriodCountStream(mouseUp$, doubleClickDelay) ) ), [doubleClickDelay] as const ) const output$ = useObservable(() => mouseUp$.pipe( withLatestFrom(config$), filter(([mouseup, [touchMode]]) => { if (touchMode) { return false } for ( let el = mouseup.target as HTMLElement | null; el; el = el.parentElement ) { if (el.tagName === 'A' || el.tagName === 'BUTTON') { return false } } return true }), map(([mouseup, [, language]]) => ({ mouseup: mouseup.nativeEvent, language })), delay(10), withLatestFrom(clickPeriodCount$), map(([{ mouseup, language }, clickPeriodCount]) => { const selection = window.getSelection() const text = getTextFromSelection(selection) return checkSupportedLangs(language, text) ? { word: { text, context: getSentenceFromSelection(selection) }, dbClick: clickPeriodCount >= 2, mouseX: mouseup.clientX, mouseY: mouseup.clientY, altKey: mouseup.altKey, shiftKey: mouseup.shiftKey, ctrlKey: mouseup.ctrlKey, metaKey: mouseup.metaKey, self: true, instant: false, force: false } : { word: null, self: true, mouseX: 0, mouseY: 0, dbClick: false, altKey: false, shiftKey: false, ctrlKey: false, metaKey: false, instant: false, force: false } }), distinctUntilChanged((oldVal, newVal) => { return ( !newVal.dbClick && !!oldVal.word && !!newVal.word && oldVal.word.text === newVal.word.text && oldVal.word.context === newVal.word.context ) }) ) ) useSubscription(output$, async result => { if (result.word) { result.word = await newSelectionWord(result.word) } newSelection(result as Message<'SELECTION'>['payload']) }) return onMouseUp } function clickPeriodCountStream( mouseup$: Observable<MouseEvent | Touch | React.MouseEvent>, doubleClickDelay: number ) { return mouseup$.pipe( switchMap(() => timer(doubleClickDelay).pipe(mapTo(false), startWith(true)) ), scan((sum: number, flag: boolean) => (flag ? sum + 1 : 0), 0) ) }
anrgct/ext-saladict
src/content/components/DictPanel/DictPanel.container.tsx
import React from 'react' import { connect } from 'react-redux' import { ExtractDispatchers, MapStateToProps, MapDispatchToProps } from 'react-retux' import { StoreState, StoreAction } from '@/content/redux/modules' import { DictPanelPortal, DictPanelPortalProps } from './DictPanel.portal' import { MenuBarContainer } from '../MenuBar/MenuBar.container' import { MtaBoxContainer } from '../MtaBox/MtaBox.container' import { DictListContainer } from '../DictList/DictList.container' import { WaveformBoxContainer } from '../WaveformBox/WaveformBox.container' const menuBar = <MenuBarContainer /> const mtaBox = <MtaBoxContainer /> const dictList = <DictListContainer /> const waveformBox = <WaveformBoxContainer /> type Dispatchers = ExtractDispatchers<DictPanelPortalProps, 'onDragEnd'> const mapStateToProps: MapStateToProps< StoreState, DictPanelPortalProps, Dispatchers > = state => ({ show: state.isShowDictPanel, coord: state.dictPanelCoord, takeCoordSnapshot: state.wordEditor.isShow, width: state.config.panelWidth, height: state.panelHeight, maxHeight: state.panelMaxHeight, fontSize: state.config.fontSize, withAnimation: state.config.animation, panelCSS: state.config.panelCSS, darkMode: state.config.darkMode, menuBar, mtaBox, dictList, waveformBox: state.activeProfile.waveform ? waveformBox : null, dragStartCoord: state.dragStartCoord }) const mapDispatchToProps: MapDispatchToProps< StoreAction, DictPanelPortalProps, Dispatchers > = dispatch => ({ onDragEnd: () => { dispatch({ type: 'DRAG_START_COORD', payload: null }) } }) export const DictPanelPortalContainer = connect( mapStateToProps, mapDispatchToProps )(DictPanelPortal) export default DictPanelPortalContainer
anrgct/ext-saladict
src/content/index.tsx
import React from 'react' import ReactDOM from 'react-dom' import { Provider as ProviderRedux } from 'react-redux' import SaladBowlContainer from './components/SaladBowl/SaladBowl.container' import DictPanelContainer from './components/DictPanel/DictPanel.container' import WordEditorContainer from './components/WordEditor/WordEditor.container' import createStore from './redux/create' import { I18nContextProvider } from '@/_helpers/i18n' // Only load on top frame if (window.parent === window && !window.__SALADICT_PANEL_LOADED__) { window.__SALADICT_PANEL_LOADED__ = true main() } async function main() { const store = createStore() const App = () => ( <ProviderRedux store={store}> <I18nContextProvider> <SaladBowlContainer /> <DictPanelContainer /> <WordEditorContainer /> </I18nContextProvider> </ProviderRedux> ) ReactDOM.render(<App />, document.createElement('div')) }
anrgct/ext-saladict
src/options/components/Entries/Dictionaries/EditModal.tsx
import React, { FC, useContext } from 'react' import { Switch, Select, Checkbox, Button, Modal } from 'antd' import { ExclamationCircleOutlined } from '@ant-design/icons' import { Rule } from 'antd/lib/form' import { DictID } from '@/app-config' import { useTranslate } from '@/_helpers/i18n' import { supportedLangs } from '@/_helpers/lang-check' import { getProfilePath } from '@/options/helpers/path-joiner' import { SaladictFormItem } from '@/options/components/SaladictForm' import { GlobalsContext } from '@/options/data' import { InputNumberGroup } from '@/options/components/InputNumberGroup' import { SaladictModalForm } from '@/options/components/SaladictModalForm' import { ChangeEntryContext } from '@/options/helpers/change-entry' import { Translator } from '@opentranslate/translator' export interface EditModalProps { dictID?: DictID | null onClose: () => void } export const EditModal: FC<EditModalProps> = ({ dictID, onClose }) => { const { t, i18n } = useTranslate(['options', 'dicts', 'common', 'langcode']) const globals = useContext(GlobalsContext) const changeEntry = useContext(ChangeEntryContext) const formItems: SaladictFormItem[] = [] const NUMBER_RULES: Rule[] = [ { type: 'number', message: t('form.number_error'), required: true } ] if (dictID) { formItems.push( { key: getProfilePath('dicts', 'all', dictID, 'selectionLang'), label: t('dict.selectionLang'), help: t('dict.selectionLang_help'), extra: t('config.language_extra'), className: 'saladict-form-danger-extra', items: supportedLangs.map(lang => ({ name: getProfilePath('dicts', 'all', dictID, 'selectionLang', lang), className: 'form-item-inline', valuePropName: 'checked', children: <Checkbox>{t(`common:lang.${lang}`)}</Checkbox> })) }, { key: getProfilePath('dicts', 'all', dictID, 'defaultUnfold'), label: t('dict.defaultUnfold'), help: t('dict.defaultUnfold_help'), extra: t('config.language_extra'), className: 'saladict-form-danger-extra', items: supportedLangs.map(lang => ({ name: getProfilePath('dicts', 'all', dictID, 'defaultUnfold', lang), className: 'form-item-inline', valuePropName: 'checked', children: <Checkbox>{t(`common:lang.${lang}`)}</Checkbox> })) }, { key: getProfilePath('dicts', 'all', dictID, 'selectionWC'), label: t('dict.selectionWC'), help: t('dict.selectionWC_help'), items: [ { name: getProfilePath('dicts', 'all', dictID, 'selectionWC', 'min'), label: null, style: { marginBottom: 5 }, rules: NUMBER_RULES, children: <InputNumberGroup suffix={t('common:min')} /> }, { name: getProfilePath('dicts', 'all', dictID, 'selectionWC', 'max'), label: null, style: { marginBottom: 5 }, rules: NUMBER_RULES, children: <InputNumberGroup suffix={t('common:max')} /> } ] }, { name: getProfilePath('dicts', 'all', dictID, 'preferredHeight'), label: t('dict.preferredHeight'), help: t('dict.preferredHeight_help'), rules: NUMBER_RULES, children: <InputNumberGroup suffix={t('common:max')} /> } ) // Dict Auth for Machine Translators if (globals.config.dictAuth[dictID]) { formItems.push({ key: dictID + '_auth', label: t('nav.DictAuths'), children: ( <Button href="./?menuselected=DictAuths" onClick={e => { e.preventDefault() e.stopPropagation() if (globals.dirty) { Modal.confirm({ title: t('unsave_confirm'), icon: <ExclamationCircleOutlined />, okType: 'danger', onOk: () => { ;(globals as GlobalsContext).dirty = false changeEntry('DictAuths') } }) } else { changeEntry('DictAuths') } }} > {t('dictAuth.manage')} </Button> ) }) } // custom options const options = globals.profile.dicts.all[dictID]['options'] if (options) { formItems.push( ...Object.keys(options).map(optKey => { // can be number | boolean | string(select) const value = options[optKey] const item: SaladictFormItem = { name: `profile.dicts.all.${dictID}.options.${optKey}`, label: t(`dicts:${dictID}.options.${optKey}`), help: i18n.exists(`dicts:${dictID}.helps.${optKey}`) ? t(`dicts:${dictID}.helps.${optKey}`) : null } switch (typeof value) { case 'number': item.rules = NUMBER_RULES item.children = ( <InputNumberGroup suffix={t(`dicts:${dictID}.options.${optKey}_unit`)} /> ) break case 'string': if (optKey === 'tl' || optKey === 'tl2') { const getTranslator: | undefined | (() => Translator) = require(`@/components/dictionaries/${dictID}/engine`) .getTranslator const langs = getTranslator ? getTranslator() .getSupportLanguages() .map(lang => (lang === 'auto' ? 'default' : lang)) : globals.profile.dicts.all[dictID]['options_sel'][optKey] item.children = ( <Select> {langs.map((option: string) => ( <Select.Option value={option} key={option}> {option === 'default' ? '' : option + ' '} {t(`langcode:${option}`)} </Select.Option> ))} </Select> ) } else { item.children = ( <Select> {globals.profile.dicts.all[dictID]['options_sel'][ optKey ].map((option: string) => ( <Select.Option value={option} key={option}> {t(`dicts:${dictID}.options.${optKey}-${option}`)} </Select.Option> ))} </Select> ) } break default: item.valuePropName = 'checked' item.children = <Switch /> } return item }) ) } } return ( <SaladictModalForm visible={!!dictID} title={t(`dicts:${dictID}.name`)} items={formItems} onClose={onClose} /> ) }
anrgct/ext-saladict
src/components/dictionaries/naver/engine.ts
<filename>src/components/dictionaries/naver/engine.ts import { fetchDirtyDOM } from '@/_helpers/fetch-dom' import { handleNoResult, handleNetWorkError, getInnerHTML, SearchFunction, GetSrcPageFunction, HTMLString, removeChildren, DictSearchResult, externalLink } from '../helpers' import { isContainJapanese, isContainKorean } from '@/_helpers/lang-check' export const getSrcPage: GetSrcPageFunction = text => { return isContainJapanese(text) ? `https://ja.dict.naver.com/search.nhn?range=all&q=${encodeURIComponent( text )}` : `https://zh.dict.naver.com/#/search?query=${encodeURIComponent(text)}` } /** Alternate machine translation result */ export interface NaverResult { lang: 'zh' | 'ja' entry: HTMLString } interface NaverPayload { lang?: 'zh' | 'ja' } type NaverSearchResult = DictSearchResult<NaverResult> export const search: SearchFunction<NaverResult, NaverPayload> = ( text, config, profile, payload ) => { const { options } = profile.dicts.all.naver if ( payload.lang === 'ja' || options.hanAsJa || isContainJapanese(text) || (options.korAsJa && isContainKorean(text)) ) { return jaDict(text) } return zhDict(text) } async function zhDict(text: string): Promise<NaverSearchResult> { try { var doc = await fetchDirtyDOM( `http://m.cndic.naver.com/search/all?sLn=zh_CN&fromNewVer&q=${encodeURIComponent( text )}` ) } catch (e) { return handleNetWorkError() } let $container = doc.querySelector('#ct') if (!$container) { return handleNoResult() } $container = $container.querySelector('#ct') || $container removeChildren($container, '.recent_searches') removeChildren($container, '.m_tab') removeChildren($container, '.con_clt') removeChildren($container, '.info_userent') removeChildren($container, '.go_register') removeChildren($container, '.section_banner') removeChildren($container, '.spi_area') removeChildren($container, '.word_otr.word_line') removeChildren($container, '.common_btn_wrap.my_vlive_pageBar') $container .querySelectorAll<HTMLAnchorElement>('a.more_d') .forEach(externalLink) return { result: { lang: 'zh', entry: getInnerHTML('http://m.cndic.naver.com', $container) } } } async function jaDict(text: string): Promise<NaverSearchResult> { try { var doc = await fetchDirtyDOM( `https://ja.dict.naver.com/search.nhn?range=all&q=${encodeURIComponent( text )}` ) } catch (e) { return handleNetWorkError() } const $container = doc.querySelector('#content') if (!$container) { return handleNoResult() } removeChildren($container, '.sorting') removeChildren($container, '.info_userent') removeChildren($container, '.view_ctrl') removeChildren($container, '.go_register') removeChildren($container, '.section_banner') removeChildren($container, '.conjugate') return { result: { lang: 'ja', entry: getInnerHTML('https://ja.dict.naver.com', $container) } } }
anrgct/ext-saladict
test/specs/components/dictionaries/googledict/requests.mock.ts
<gh_stars>1-10 import { MockRequest } from '@/components/dictionaries/helpers' export const mockSearchTexts = ['mouse', '爱', 'love'] export const mockRequest: MockRequest = mock => { mock .onGet(/google.+define.+mouse/) .reply(200, require('!raw-loader!./response/chs-mouse.html').default) mock .onGet(new RegExp(encodeURIComponent('爱'))) .reply(200, require('!raw-loader!./response/chs-爱.html').default) mock .onGet(/google.+define.+love/) .reply(200, require('!raw-loader!./response/en-love.html').default) }
anrgct/ext-saladict
src/_helpers/i18n.ts
import React, { useState, useLayoutEffect, FC, useContext, useRef, Fragment, PropsWithChildren } from 'react' import mapValues from 'lodash/mapValues' import i18n, { TFunction } from 'i18next' import { getConfig, addConfigListener } from '@/_helpers/config-manager' import zip from 'lodash/zip' export type LangCode = 'zh-CN' | 'zh-TW' | 'en' export type Namespace = | 'common' | 'content' | 'langcode' | 'menus' | 'options' | 'popup' | 'wordpage' | 'dicts' export interface RawLocale { 'zh-CN': string 'zh-TW': string en: string } export interface RawLocales { [message: string]: RawLocale } export interface RawDictLocales { name: RawLocale options?: RawLocales helps?: RawLocales } export interface DictLocales { name: string options?: { [message: string]: any } helps?: { [message: string]: any } } export async function i18nLoader() { const { langCode } = await getConfig() await i18n .use({ type: 'backend', init: () => {}, create: () => {}, read: async (lang: LangCode, ns: Namespace, cb: Function) => { try { if (ns === 'dicts') { const dictLocals = extractDictLocales(lang) cb(null, dictLocals) return dictLocals } const { locale } = await import( /* webpackInclude: /_locales\/[^/]+\/[^/]+\.ts$/ */ /* webpackMode: "lazy" */ `@/_locales/${lang}/${ns}.ts` ) cb(null, locale) return locale } catch (err) { cb(err) } } }) .init({ lng: langCode, fallbackLng: false, whitelist: ['en', 'zh-CN', 'zh-TW'], debug: process.env.NODE_ENV === 'development', saveMissing: false, load: 'currentOnly', ns: 'common', defaultNS: 'common', interpolation: { escapeValue: false // not needed for react as it escapes by default } }) addConfigListener(({ newConfig }) => { if (i18n.language !== newConfig.langCode) { i18n.changeLanguage(newConfig.langCode) } }) return i18n } const defaultT: i18n.TFunction = () => '' export const I18nContext = React.createContext<string | undefined>(undefined) if (process.env.DEBUG) { I18nContext.displayName = 'I18nContext' } export const I18nContextProvider: FC = ({ children }) => { const [lang, setLang] = useState<string | undefined>(undefined) useLayoutEffect(() => { const setLangCallback = () => { setLang(i18n.language) } if (!i18n.language) { i18nLoader().then(() => { setLang(i18n.language) i18n.on('languageChanged', setLangCallback) }) } return () => { i18n.off('languageChanged', setLangCallback) } }, []) return React.createElement(I18nContext.Provider, { value: lang }, children) } export interface UseTranslateResult { /** * fixedT with the first namespace as default. * It is a wrapper of the original fixedT, which * keeps the same reference even after namespaces are loaded */ t: i18n.TFunction i18n: i18n.i18n /** * Are namespaces loaded? * false not ready * otherwise it is a non-zero positive number * that changes everytime when new namespaces are loaded. */ ready: false | number } /** * Tailored for this project. * The official `useTranslation` is too heavy. * @param namespaces will not monitor namespace changes. */ export function useTranslate( namespaces?: Namespace | Namespace[] ): UseTranslateResult { const ticketRef = useRef(0) const innerTRef = useRef<TFunction>(defaultT) // keep the exposed t function always the same const tRef = useRef<TFunction>((...args: Parameters<TFunction>) => innerTRef.current(...args) ) const lang = useContext(I18nContext) const genResult = (t: TFunction | null, ready: boolean) => { if (t) { innerTRef.current = t } if (ready) { ticketRef.current = (ticketRef.current + 1) % 100000 } const result: UseTranslateResult = { t: tRef.current, i18n, ready: ready ? ticketRef.current : false } return result } const [result, setResult] = useState<UseTranslateResult>(() => { if (!lang) { return genResult(defaultT, false) } if (!namespaces) { return genResult(i18n.t, true) } if ( Array.isArray(namespaces) ? namespaces.every(ns => i18n.hasResourceBundle(lang, ns)) : i18n.hasResourceBundle(lang, namespaces) ) { return genResult(i18n.getFixedT(lang, namespaces), true) } return genResult(defaultT, false) }) useLayoutEffect(() => { let isEffectRunning = true if (lang) { if (namespaces) { if ( Array.isArray(namespaces) ? namespaces.every(ns => i18n.hasResourceBundle(lang, ns)) : i18n.hasResourceBundle(lang, namespaces) ) { setResult(genResult(i18n.getFixedT(lang, namespaces), true)) } else { // keep the old t while marking not ready setResult(genResult(null, false)) i18n.loadNamespaces(namespaces).then(() => { if (isEffectRunning) { setResult(genResult(i18n.getFixedT(lang, namespaces), true)) } }) } } else { setResult(genResult(i18n.t, true)) } } return () => { isEffectRunning = false } }, [lang]) return result } /** * <Trans message="a{b}c{d}e"> * <h1>b</h1> * <p>d</p> * </Trans> * ↓ * [ * "a", * <h1>b</h1>, * "c", * <p>d</p>, * "e" * ] */ export const Trans = React.memo<PropsWithChildren<{ message?: string }>>( ({ message, children }) => { if (!message) return null return React.createElement( Fragment, null, zip( message.split(/{[^}]*?}/), Array.isArray(children) ? children : [children] ) ) } ) function extractDictLocales(lang: LangCode) { const req = require.context( '@/components/dictionaries', true, /_locales\.(json|ts)$/ ) return req.keys().reduce<{ [id: string]: DictLocales }>((o, filename) => { const localeModule = req(filename) const json: RawDictLocales = localeModule.locales || localeModule const dictId = /([^/]+)\/_locales\.(json|ts)$/.exec(filename)![1] o[dictId] = { name: json.name[lang] } if (json.options) { o[dictId].options = mapValues(json.options, rawLocale => rawLocale[lang]) } if (json.helps) { o[dictId].helps = mapValues(json.helps, rawLocale => rawLocale[lang]) } return o }, {}) }
anrgct/ext-saladict
src/components/WordPage/ExportModal/PlaceholderTable.tsx
import React, { FC } from 'react' import { Table } from 'antd' import { TFunction } from 'i18next' export interface PlaceholderTableProps { t: TFunction } export const PlaceholderTable: FC<PlaceholderTableProps> = ({ t }) => ( <Table rowKey="plcholderL" pagination={false} size="small" bordered={true} style={{ marginBottom: '1em' }} dataSource={[ { plcholderL: '%text%', contentL: t('common:note.word'), plcholderR: '%title%', contentR: t('common:note.srcTitle') }, { plcholderL: '%context%', contentL: t('common:note.context'), plcholderR: '%url%', contentR: t('common:note.srcLink') }, { plcholderL: '%note%', contentL: t('common:note.note'), plcholderR: '%favicon%', contentR: t('common:note.srcFavicon') }, { plcholderL: '%trans%', contentL: t('common:note.trans'), plcholderR: '%date%', contentR: t('common:note.date') } ]} columns={[ { title: t('export.placeholder'), dataIndex: 'plcholderL', key: 'plcholderL', width: '25%', align: 'center' }, { title: t('export.gencontent'), dataIndex: 'contentL', key: 'contentL', width: '25%', align: 'center' }, { title: t('export.placeholder'), dataIndex: 'plcholderR', key: 'plcholderR', width: '25%', align: 'center' }, { title: t('export.gencontent'), dataIndex: 'contentR', key: 'contentR', width: '25%', align: 'center' } ]} /> ) export const PlaceholderTableMemo = React.memo(PlaceholderTable)
anrgct/ext-saladict
src/options/components/Entries/Notebook/ShanbayModal.tsx
import React, { FC, useState } from 'react' import { Modal, Button, Switch, message as AntdMsg, notification } from 'antd' import { Service, SyncConfig } from '@/background/sync-manager/services/shanbay' import { setSyncConfig as uploadSyncConfig } from '@/background/sync-manager/helpers' import { message } from '@/_helpers/browser-api' import { getWords } from '@/_helpers/record-manager' import { useTranslate } from '@/_helpers/i18n' export interface WebdavModalProps { syncConfig?: SyncConfig show: boolean onClose: () => void } export const ShanbayModal: FC<WebdavModalProps> = props => { const { t } = useTranslate(['options', 'common']) const [syncConfig, setSyncConfig] = useState<SyncConfig>( props.syncConfig || { enable: false } ) return ( <Modal visible={props.show} title={t('syncService.shanbay.title')} destroyOnClose onCancel={props.onClose} footer={null} > <p>{t('syncService.shanbay.description')}</p> <div style={{ textAlign: 'center', marginBottom: 20 }}> {t('common:enable')}: <Switch checked={syncConfig.enable} onChange={onToggleEnable} /> </div> {syncConfig.enable && ( <div style={{ textAlign: 'center' }}> <Button onClick={onSyncAll} style={{ marginRight: 10 }}> {t('syncService.shanbay.sync_all')} </Button> <Button onClick={onSyncLast}> {t('syncService.shanbay.sync_last')} </Button> </div> )} </Modal> ) async function onToggleEnable(enable: boolean) { const newConfig = { ...syncConfig, enable } if (enable) { try { await message.send<'SYNC_SERVICE_INIT', SyncConfig>({ type: 'SYNC_SERVICE_INIT', payload: { serviceID: Service.id, config: newConfig } }) } catch (e) { Modal.confirm({ title: t('syncService.shanbay.login'), onOk: () => { Service.openLogin() } }) return } } try { await uploadSyncConfig('shanbay', newConfig) setSyncConfig(newConfig) AntdMsg.destroy() AntdMsg.success(t('msg_updated')) } catch (e) { notification.error({ message: t('config.opt.upload_error'), description: e?.message }) } } async function onSyncAll() { const { total } = await getWords('notebook', { itemsPerPage: 1, filters: {} }) if (total > 50 && !confirm(t('syncService.shanbay.sync_all_confirm'))) { return } AntdMsg.destroy() AntdMsg.success(t('sync.start')) try { await message.send<'SYNC_SERVICE_UPLOAD'>({ type: 'SYNC_SERVICE_UPLOAD', payload: { op: 'ADD', serviceID: Service.id, force: true } }) AntdMsg.success(t('sync.success')) } catch (e) { notification.error({ message: t('sync.failed'), description: e?.message }) } } async function onSyncLast() { const { words } = await getWords('notebook', { itemsPerPage: 1, filters: {} }) if (!words || words.length <= 0) { return } AntdMsg.destroy() AntdMsg.success(t('sync.start')) try { await message.send({ type: 'SYNC_SERVICE_UPLOAD', payload: { op: 'ADD', serviceID: Service.id, force: true, words } }) AntdMsg.success(t('sync.success')) } catch (e) { notification.error({ message: t('sync.failed'), description: e?.message }) } } }
anrgct/ext-saladict
src/options/components/MainEntry.tsx
<gh_stars>0 import React, { FC, useState, useEffect, useContext } from 'react' import { Helmet } from 'react-helmet' import { Layout, Row, Col, message as antMsg, notification } from 'antd' import { useObservablePickState, useSubscription } from 'observable-hooks' import { reportGA } from '@/_helpers/analytics' import { ErrorBoundary } from '@/components/ErrorBoundary' import { useTranslate, I18nContext } from '@/_helpers/i18n' import { EntrySideBarMemo } from './EntrySideBar' import { HeaderMemo } from './Header' import { EntryError } from './EntryError' import { BtnPreviewMemo } from './BtnPreview' import { config$$, GlobalsContext } from '../data' import { uploadResult$$ } from '../helpers/upload' import { ChangeEntryContext } from '../helpers/change-entry' const EntryComponent = React.memo(({ entry }: { entry: string }) => React.createElement(require(`./Entries/${entry}`)[entry]) ) export const MainEntry: FC = () => { const lang = useContext(I18nContext) const { t, ready } = useTranslate('options') const globals = useContext(GlobalsContext) const [entry, setEntry] = useState(getEntry) const { analytics, darkMode } = useObservablePickState( config$$, 'analytics', 'darkMode' )! useEffect(() => { if (getEntry() !== entry) { const { protocol, host, pathname } = window.location const newurl = `${protocol}//${host}${pathname}?menuselected=${entry}` window.history.pushState({ key: entry }, '', newurl) } if (analytics) { reportGA(`/options/${entry}`) } }, [entry, analytics]) // settings saving status useSubscription(uploadResult$$, result => { if (result.error) { notification.error({ message: t('config.opt.upload_error'), description: result.error.message }) } else if (!result.loading) { // success ;(globals as GlobalsContext).dirty = false antMsg.destroy() antMsg.success(t('msg_updated')) } }) // Warn about unsaved settings before closing window useEffect(() => { window.addEventListener('beforeunload', e => { if (globals.dirty) { e.preventDefault() e.returnValue = t('unsave_confirm') } }) }, []) return ( <> <Helmet> {ready && <title>{`${t('title')} - ${t('nav.' + entry)}`}</title>} </Helmet> <HeaderMemo openProfilesTab={setEntry} /> <Layout style={{ maxWidth: 1400, margin: '0 auto' }} className={`main-entry${darkMode ? ' dark-mode' : ''}`} > <Row> <Col> <EntrySideBarMemo entry={entry} onChange={setEntry} /> </Col> <Col style={{ flex: '1' }}> <Layout style={{ padding: 24 }}> <Layout.Content data-option-content={entry} // for utools hiding unused options style={{ padding: 24, backgroundColor: 'var(--opt-background-color)' }} > <ChangeEntryContext.Provider value={setEntry}> <ErrorBoundary key={entry + lang} error={EntryError}> {ready && <EntryComponent entry={entry} />} </ErrorBoundary> </ChangeEntryContext.Provider> </Layout.Content> </Layout> </Col> </Row> <BtnPreviewMemo /> </Layout> </> ) } function getEntry(): string { return new URL(document.URL).searchParams.get('menuselected') || 'General' }
anrgct/ext-saladict
src/components/dictionaries/liangan/engine.ts
<gh_stars>0 import { SearchFunction, GetSrcPageFunction, getChsToChz } from '../helpers' import { moedictSearch, GuoYuResult } from '../guoyu/engine' export const getSrcPage: GetSrcPageFunction = async text => { const chsToChz = await getChsToChz() return `https://www.moedict.tw/~${chsToChz(text)}` } export type LiangAnResult = GuoYuResult export const search: SearchFunction<LiangAnResult> = ( text, config, profile, payload ) => { return moedictSearch<LiangAnResult>('c', text, config).then(result => { if (result.result.h) { result.result.h.forEach(h => { if (h.p) { h.p = h.p.replace('<br>陸⃝', ' [大陆]: ') } }) } return result }) }
anrgct/ext-saladict
src/components/dictionaries/weblioejje/View.tsx
import React, { FC } from 'react' import { WeblioejjeResult } from './engine' import EntryBox from '@/components/EntryBox' import { ViewPorps } from '@/components/dictionaries/helpers' export const DictWeblioejje: FC<ViewPorps<WeblioejjeResult>> = ({ result }) => ( <div> {result.map((entry, i) => entry.title ? ( <EntryBox key={entry.title + i} title={entry.title}> <div dangerouslySetInnerHTML={{ __html: entry.content }} /> </EntryBox> ) : ( <div key={i} className="dictWeblioejje-Box" dangerouslySetInnerHTML={{ __html: entry.content }} /> ) )} </div> ) export default DictWeblioejje