repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
beenotung/stencil-virtual-scroll
src/components/virtual-scroll-list/helpers.ts
export function getElementHeight(e: Element): number { return e.clientHeight || e.getBoundingClientRect().height }
beenotung/stencil-virtual-scroll
src/components/virtual-scroll-demo/virtual-scroll-demo.tsx
import { Component, h, Host } from '@stencil/core'; @Component({ tag: 'virtual-scroll-demo', styleUrl: 'virtual-scroll-demo.css', scoped: true, }) export class VirtualScrollDemo { render() { const N = 100000; const width = 250; const height = 150; return ( <Host> before <virtual-scroll itemCount={N} renderItem={i => <img src={`https://via.placeholder.com/${width}x${height}/${i}`} />} itemWidth={width} itemHeight={height} style={{ display: 'block', width: '100%', height: '450px', maxHeight: '80vh', outline: 'blue solid 1px', }} /> after </Host> ); } }
martinsung00/Frostbolt
src/utils/currentStatus.ts
import { CurrentStatus } from "../types"; const statuses: CurrentStatus = { failed_internal: "Internal Error", failed_external: "Input Error", success: "Operation Successful", }; export default statuses;
martinsung00/Frostbolt
src/utils/index.ts
import dataTypes from "./dataTypes"; import statuses from "./currentStatus"; export { dataTypes, statuses };
martinsung00/Frostbolt
src/utils/dataTypes.ts
<reponame>martinsung00/Frostbolt<gh_stars>0 const dataTypes = { postgres: [ "boolean", "varchar", "char", "int", "smallint", "bigint", "decimal", "numeric", "real", "double precision", "smallserial", "bigserial", "serial", "money", "text", "varying", "bytea", "timestamp", "timestamptz", "date", "time", "point", "line", "lseg", "box", "path", "plygon", "circle", ], }; export default dataTypes;
martinsung00/Frostbolt
test/src/plugin.test.ts
import Seeder from "../../src"; describe("Seeder Plugin Tests", () => { const mockUrl: string = "localhost:5432"; const mockSchema: { [key: string]: string; } = { cats: "varchar", dog: "int", }; let seeder: Seeder; beforeAll(() => { seeder = new Seeder(mockUrl, mockSchema); }); afterAll(() => { jest.resetModules(); jest.resetAllMocks(); }); describe("Seed Method", () => { afterEach(() => { jest.resetAllMocks(); }); it("should return 'Operation Successful'", async (done) => { const expectedResult = "Operation Successful"; try { const testResult = await seeder.seed(); expect(testResult).toEqual(expectedResult); expect(typeof testResult).toEqual("string"); } catch (err) { console.log(err); } finally { done(); } }); it("should console log the target url", async (done) => { const spy: jest.SpyInstance = jest.spyOn(console, "log"); try { await seeder.seed(); expect(spy).toHaveBeenCalledWith(`Target url: ${mockUrl}`); } catch (err) { console.log(err); } finally { done(); } }); it("should console log the key value pairs", async (done) => { const spy: jest.SpyInstance = jest.spyOn(console, "log"); try { await seeder.seed(); expect(spy).toHaveBeenCalledWith(`cat: ${mockSchema.cat}`); expect(spy).toHaveBeenCalledWith(`dog: ${mockSchema.dog}`); } catch (err) { console.log(err); } finally { done(); } }); }); });
martinsung00/Frostbolt
src/index.ts
<filename>src/index.ts import Seeder from "./plugin"; export default Seeder;
martinsung00/Frostbolt
src/types/currentStatus.ts
<filename>src/types/currentStatus.ts export type CurrentStatus = { failed_internal: string; failed_external: string; success: string; };
martinsung00/Frostbolt
src/plugin.ts
<reponame>martinsung00/Frostbolt<filename>src/plugin.ts import { statuses } from "./utils"; export default class Seeder { url: string; schema: { [key: string]: "string" | number; }; constructor(url: string, schema: {}) { this.url = url; this.schema = schema; } public seed = async (): Promise<string> => { const url: string = this.url; const schema: {} = this.schema; let key: string; let value: any; for ([key, value] of Object.entries(schema)) { console.log(`${key}: ${value}`); } console.log(`Target url: ${url}`); return statuses.success; }; }
martinsung00/Frostbolt
src/types/index.ts
import { CurrentStatus } from "./currentStatus"; export { CurrentStatus };
egoist/svelte-convert
src/vue.ts
<reponame>egoist/svelte-convert import { isServer } from './shared' export function convert(Component: any): any { if (isServer) { return { functional: true, render(h: any, ctx: any) { const { html, style } = Component.render(ctx.attrs) return h('div', {}, [ h('style', { domProps: { innerHTML: style } }), h('div', { domProps: { innerHTML: html } }), ]) }, } } return { mounted() { this.comp = new Component({ target: this.$refs.target, props: this.$attrs, }) }, beforeDestroy() { if (this.comp) { this.comp.$destroy() } }, render(h: any) { return h('div', { ref: 'target' }) }, } }
egoist/svelte-convert
declarations.d.ts
declare module '*.svelte'
egoist/svelte-convert
test/react.test.tsx
<gh_stars>10-100 import React from 'react' import { renderToString } from 'react-dom/server' import SvelteCounter from './Counter.node.svelte' import { convert } from '../src/react' it('renders to string', () => { const Counter = convert<{ initialCount: number }>(SvelteCounter.default) const str = renderToString(<Counter initialCount={10} />) expect(str).toMatchInlineSnapshot(` "<style>button.svelte-aci4jg{color:red}</style><div><button class=\\"svelte-aci4jg\\">10 </button></div>" `) })
egoist/svelte-convert
vue.d.ts
<filename>vue.d.ts export * from './dist/vue'
egoist/svelte-convert
react.d.ts
<gh_stars>10-100 export * from './dist/react'
egoist/svelte-convert
src/react.tsx
import React from 'react' import { isServer } from './shared' export function convert<TProps = any>(Component: any): React.FC<TProps> { if (isServer) { return (props) => { const { html, css } = Component.render(props) return ( <> <style>{css.code}</style> <div dangerouslySetInnerHTML={{ __html: html }}></div> </> ) } } return (props) => { const ref = React.useRef(null) React.useEffect(() => { const comp = new Component({ target: ref.current, props, }) return () => comp.$destroy() }, []) return <div ref={ref}></div> } }
rynop/nativescript-app-templates
packages/template-patient-care-ng/src/care/care-card/shared/care-plan-event.model.ts
import { CarePlanActivity } from "./care-plan-activity.model"; export class CarePlanEvent { occurrenceIndexOfDay: number; date: Date; activity: CarePlanActivity; value: number; constructor(activity: CarePlanActivity, date: Date, occurrenceIndexOfDay: number, value: number = 0) { this.activity = activity; this.date = date; this.occurrenceIndexOfDay = occurrenceIndexOfDay; this.value = value; } }
rynop/nativescript-app-templates
packages/template-health-survey-ng/src/app/survey/survey-complete/survey-complete.component.ts
import { Component, OnInit } from "@angular/core"; import { RouterExtensions } from "nativescript-angular/router"; import { AppService } from "../../shared/app.service"; @Component({ selector: "Complete", templateUrl: "./survey-complete.component.html" }) export class SurveyCompleteComponent implements OnInit { constructor( public appService: AppService, private _routerExtensions: RouterExtensions ) { } ngOnInit(): void { /* *********************************************************** * Use the "ngOnInit" handler to initialize data for this component. *************************************************************/ } onCancelButtonTap() { this._routerExtensions.navigate(["/login"], { clearHistory: true, animated: true, transition: { name: "slideRight", duration: 200, curve: "ease" } }); } }
rynop/nativescript-app-templates
packages/template-patient-care-ng/src/care/care-routing.module.ts
<reponame>rynop/nativescript-app-templates import { NgModule } from "@angular/core"; import { Routes } from "@angular/router"; import { NativeScriptRouterModule } from "nativescript-angular/router"; import { ActivityDetailComponent } from "./care-card/activity-detail/activity-detail.component"; import { CareComponent } from "./care.component"; import { ConnectDetailComponent } from "./connect/connect-detail/connect-detail.component"; const routes: Routes = [ { path: "", component: CareComponent }, { path: "connect-detail/:id", component: ConnectDetailComponent }, { path: "activity-detail/:title/:date", component: ActivityDetailComponent } ]; @NgModule({ imports: [NativeScriptRouterModule.forChild(routes)], exports: [NativeScriptRouterModule] }) export class CareRoutingModule { }
rynop/nativescript-app-templates
packages/template-patient-care-ng/src/care/care-card/shared/care-plan-activity-type.enum.ts
export const enum CarePlanActivityType { Activity = 0, Assessment = 1, ReadOnly = 2 }
rynop/nativescript-app-templates
packages/template-drawer-navigation-ts/app/shared/selected-page-service.ts
import { BehaviorSubject, Observable } from "rxjs"; export class SelectedPageService { static getInstance(): SelectedPageService { return SelectedPageService._instance; } private static _instance: SelectedPageService = new SelectedPageService(); selectedPage$: Observable<string>; private _selectedPageSource: BehaviorSubject<string>; constructor() { if (SelectedPageService._instance) { throw new Error("Use SelectedPageService.getInstance() instead of new."); } SelectedPageService._instance = this; // Observable selectedPage source this._selectedPageSource = new BehaviorSubject<string>("Home"); // Observable selectedPage stream this.selectedPage$ = this._selectedPageSource.asObservable(); } updateSelectedPage(selectedPage: string) { this._selectedPageSource.next(selectedPage); } }
rynop/nativescript-app-templates
packages/template-patient-care-ng/src/care/care-card/shared/care-card.service.ts
import { Injectable } from "@angular/core"; import { BehaviorSubject, Observable } from "rxjs"; import { CareCardActivityService } from "./care-card-activity.service"; import { CareCardEventService } from "./care-card-event.service"; import { CarePlanActivityType } from "./care-plan-activity-type.enum"; import { CarePlanActivity } from "./care-plan-activity.model"; @Injectable({ providedIn: "root" }) export class CareCardService { selectedDate$: Observable<Date>; private _selectedDateItemSource: BehaviorSubject<Date>; constructor( private _careCardEventService: CareCardEventService, private _careCardActivityService: CareCardActivityService ) { // Observable selectedDate source this._selectedDateItemSource = new BehaviorSubject<Date>(new Date()); // Observable selectedDate stream this.selectedDate$ = this._selectedDateItemSource.asObservable(); } updateSelectedDate(date: Date) { this._selectedDateItemSource.next(date); } getOverviewValue(date: Date): Promise<number> { return this._careCardActivityService.getActivities(). then((activities: Array<CarePlanActivity>) => { let overviewValue: number = 0; let totalEventsCount: number = 0; let savedEventsCount: number = 0; const savedEventsPromises = []; activities.forEach((activity) => { if (activity.type === CarePlanActivityType.ReadOnly) { return; } const day: number = date.getDay(); totalEventsCount += activity.schedule.occurrences[day] || 0; savedEventsPromises.push(this._careCardEventService.findEvents(activity.title, date)); }); return Promise.all(savedEventsPromises) .then((values) => { values.forEach((savedEvents) => { savedEvents.forEach((savedEvent) => { if (savedEvent.value !== 0) { savedEventsCount++; } }); }); overviewValue = (savedEventsCount / totalEventsCount) * 100; if (overviewValue) { return parseFloat(overviewValue.toFixed(2)); } else { return 0; } }); }); } }
rynop/nativescript-app-templates
packages/template-health-survey-ng/src/app/core/task-manager/steps/study-text-step.model.ts
<gh_stars>1-10 import { StudyStep } from "./study-step.model"; export class StudyTextStep extends StudyStep { results: Array<any>; saveable: boolean; identifier: string; constructor(identifier: string, textAnswer: string) { super(identifier); this.results = [ { questionType: "Text", saveable: false, textAnswer, identifier } ]; } }
rynop/nativescript-app-templates
packages/template-master-detail-kinvey-ts/app/cars/car-detail-edit-page/car-detail-edit-view-model.ts
<reponame>rynop/nativescript-app-templates<filename>packages/template-master-detail-kinvey-ts/app/cars/car-detail-edit-page/car-detail-edit-view-model.ts import * as imagePicker from "nativescript-imagepicker"; import { Observable } from "tns-core-modules/data/observable"; import { Folder, knownFolders, path } from "tns-core-modules/file-system"; import { ImageAsset } from "tns-core-modules/image-asset"; import { fromAsset, ImageSource } from "tns-core-modules/image-source"; import { ObservableProperty } from "../../shared/observable-property-decorator"; import { Car } from "../shared/car-model"; import { CarService } from "../shared/car-service"; import { RoundingValueConverter } from "./roundingValueConverter"; import { VisibilityValueConverter } from "./visibilityValueConverter"; const tempImageFolderName = "nsimagepicker"; export class CarDetailEditViewModel extends Observable { static get imageTempFolder(): Folder { return knownFolders.temp().getFolder(tempImageFolderName); } private static clearImageTempFolder(): void { CarDetailEditViewModel.imageTempFolder.clear(); } @ObservableProperty() car: Car; @ObservableProperty() isUpdating: boolean; private _roundingValueConverter: RoundingValueConverter; private _visibilityValueConverter: VisibilityValueConverter; private _isCarImageDirty: boolean; private _carService: CarService; constructor(car: Car) { super(); // get a fresh editable copy of car model this.car = new Car(car); this._carService = CarService.getInstance(); this.isUpdating = false; this._isCarImageDirty = false; // set up value converter to force iOS UISlider to work with discrete steps this._roundingValueConverter = new RoundingValueConverter(); this._visibilityValueConverter = new VisibilityValueConverter(); } get roundingValueConverter(): RoundingValueConverter { return this._roundingValueConverter; } get visibilityValueConverter(): VisibilityValueConverter { return this._visibilityValueConverter; } saveChanges(): Promise<any> { let queue = Promise.resolve(); this.isUpdating = true; // TODO: car image should be required field if (this._isCarImageDirty && this.car.imageUrl) { queue = queue .then(() => { // no need to explicitly delete old image as upload to an existing remote path overwrites it const localFullPath = this.car.imageUrl; const remoteFullPath = this.car.imageStoragePath; return this._carService.uploadImage(remoteFullPath, localFullPath); }) .then((uploadedFile: any) => { this.car.imageUrl = uploadedFile.url; this._isCarImageDirty = false; }); } return queue.then(() => { return this._carService.update(this.car); }).then(() => this.isUpdating = false) .catch((errorMessage: any) => { this.isUpdating = false; throw errorMessage; }); } onImageAddRemove(): void { if (this.car.imageUrl) { this.handleImageChange(null); return; } CarDetailEditViewModel.clearImageTempFolder(); this.pickImage(); } private pickImage(): void { const context = imagePicker.create({ mode: "single" }); context .authorize() .then(() => context.present()) .then((selection) => selection.forEach( (selectedAsset: ImageAsset) => { selectedAsset.options.height = 768; fromAsset(selectedAsset) .then((imageSource: ImageSource) => this.handleImageChange(imageSource)); }) ).catch((errorMessage: any) => console.log(errorMessage)); } private handleImageChange(source: ImageSource): void { let raisePropertyChange = true; let tempImagePath = null; if (source) { tempImagePath = path.join(CarDetailEditViewModel.imageTempFolder.path, `${Date.now()}.jpg`); raisePropertyChange = source.saveToFile(tempImagePath, "jpeg"); } if (raisePropertyChange) { this.car.imageUrl = tempImagePath; this._isCarImageDirty = true; } } }
rynop/nativescript-app-templates
packages/template-health-survey-ng/src/app/core/task-manager/steps/sign-up-step.model.ts
<gh_stars>1-10 export class SignUpStep { results: Array<any>; saveable: boolean; identifier: string; constructor(identifier: string) { this.results = []; this.saveable = false; this.identifier = identifier; } }
rynop/nativescript-app-templates
packages/template-health-survey-ng/src/app/consent/consent-review/consent/consent-form.model.ts
export class ConsentForm { firstName: string; lastName: string; constructor() { this.firstName = ""; this.lastName = ""; } }
rynop/nativescript-app-templates
packages/template-health-survey-ng/src/app/core/task-manager/steps/consent-sharing-step.model.ts
export class ConsentSharingStep { results: Array<any>; saveable: boolean; identifier: string; constructor(identifier: string, answer: boolean) { this.results = [{ choiceAnswers: [ answer ], questionType: "SingleChoice", saveable: false, identifier: "consentSharingStep" }]; this.saveable = false; this.identifier = identifier; } }
rynop/nativescript-app-templates
packages/template-master-detail-kinvey-ng/src/app/app.module.ts
<reponame>rynop/nativescript-app-templates import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core"; import { NativeScriptModule } from "nativescript-angular/nativescript.module"; // TODO: should be imported from kinvey-nativescript-sdk/angular but declaration file is currently missing import { KinveyModule } from "kinvey-nativescript-sdk/lib/angular"; import { Config } from "./shared/config"; import { AppRoutingModule } from "./app-routing.module"; import { AppComponent } from "./app.component"; @NgModule({ bootstrap: [ AppComponent ], imports: [ NativeScriptModule, AppRoutingModule, /* *********************************************************** * The {N} Kinvey plugin initialization is explained in the plugin readme here: * http://devcenter.kinvey.com/nativescript/guides/getting-started#ConfigureYourApp * In this template, Kinvey is set up with a custom existing project, so that * You can build and run this template without creating your own Kinvey project. *************************************************************/ KinveyModule.init({ appKey: Config.kinveyAppKey, appSecret: Config.kinveyAppSecret }) ], declarations: [ AppComponent ], schemas: [ NO_ERRORS_SCHEMA ] }) export class AppModule { }
rynop/nativescript-app-templates
packages/template-patient-care-ng/src/care/connect/shared/patient.model.ts
<gh_stars>0 import { Contact } from "./contact.model"; export class Patient { name: string; monogram: string; userInfo: any; tintColor: string; careTeamContacts: Array<Contact>; constructor(options: any) { this.name = options.name; this.monogram = options.monogram; this.userInfo = options.userInfo; this.tintColor = options.tintColor ? this.getHexColor(options.tintColor) : ""; this.careTeamContacts = new Array<Contact>(); if (options.careTeamContacts && options.careTeamContacts.length) { options.careTeamContacts.forEach((careTeamContactData) => { const careTeamContact = new Contact(careTeamContactData); this.careTeamContacts.push(careTeamContact); }); } } getContactsByType(type: number): Array<Contact> { return this.careTeamContacts.filter((contact) => { return contact.type === type; }); } private getHexColor(tintColor: any): string { const r = Math.round(tintColor.r * 255).toString().slice(0, 2); const g = Math.round(tintColor.g * 255).toString().slice(0, 2); const b = Math.round(tintColor.b * 255).toString().slice(0, 2); let hexColor = `#${r + g + b}`; let a = tintColor.a; if (a < 1) { a = Math.round(a * 255).toString().slice(0, 2); hexColor += a; } return hexColor; } }
rynop/nativescript-app-templates
packages/template-patient-care-ng/src/login/registration/registration-form.model.ts
<reponame>rynop/nativescript-app-templates<filename>packages/template-patient-care-ng/src/login/registration/registration-form.model.ts export class RegistrationForm { email: string; password: string; passwordConfirm: string; givenName: string; familyName: string; gender: string; dateOfBirth: string; constructor() { this.email = ""; this.password = ""; this.passwordConfirm = ""; this.givenName = ""; this.familyName = ""; this.gender = "male"; this.dateOfBirth = null; } toPlainObject() { return { email: this.email, password: <PASSWORD>, givenName: this.givenName, familyName: this.familyName, gender: this.gender, dateOfBirth: this.dateOfBirth }; } }
rynop/nativescript-app-templates
packages/template-patient-care-ng/src/care/care-card/shared/care-plan-activity.model.ts
<gh_stars>0 import { CarePlanActivityGroup } from "./care-plan-activity-group.enum"; import { CarePlanEvent } from "./care-plan-event.model"; export class CarePlanActivity { groupIdentifier: CarePlanActivityGroup; title: string; text: string; tintColor: any; instructions: string; schedule: any; resultResettable: boolean; type: number; optional: boolean; hexColor: string; events: Array<CarePlanEvent>; constructor(options: any) { this.groupIdentifier = this.getGroupIdentifierType(options.groupIdentifier); this.title = options.title; this.text = options.text; this.tintColor = options.tintColor; this.instructions = options.instructions; this.schedule = options.schedule; this.resultResettable = options.resultResettable; this.type = options.type; this.optional = options.optional; this.events = new Array<CarePlanEvent>(); this.hexColor = options.tintColor ? this.getHexColor(options.tintColor) : ""; } getJson() { return { groupIdentifier: this.groupIdentifier.toString(), title: this.title, text: this.text, tintColor: this.tintColor, instructions: this.instructions, schedule: this.schedule, resultResettable: this.resultResettable, type: this.type, optional: this.optional }; } getNumberOfDaysSinceStart(): number { if (this.schedule && this.schedule.startDate) { let startDate = this.schedule.startDate; const oneDay = 24 * 60 * 60 * 1000; startDate = new Date(startDate.year, startDate.month - 1, startDate.day); return Math.round(Math.abs((startDate.getTime() - new Date().getTime()) / (oneDay))); } return 0; } private getGroupIdentifierType(groupIdentifier: string): CarePlanActivityGroup { if (groupIdentifier === CarePlanActivityGroup.Physical.toString()) { return CarePlanActivityGroup.Physical; } else if (groupIdentifier === CarePlanActivityGroup.Assessment.toString()) { return CarePlanActivityGroup.Assessment; } else if (groupIdentifier === CarePlanActivityGroup.Medication.toString()) { return CarePlanActivityGroup.Medication; } else { return CarePlanActivityGroup.Other; } } private getHexColor(tintColor: any): string { const r = Math.round(tintColor.r * 255).toString().slice(0, 2); const g = Math.round(tintColor.g * 255).toString().slice(0, 2); const b = Math.round(tintColor.b * 255).toString().slice(0, 2); let hexColor = `#${r + g + b}`; let a = tintColor.a; if (a < 1) { a = Math.round(a * 255).toString().slice(0, 2); hexColor += a; } return hexColor; } }
rynop/nativescript-app-templates
packages/template-health-survey-ng/src/app/survey/survey-routing.module.ts
<reponame>rynop/nativescript-app-templates<filename>packages/template-health-survey-ng/src/app/survey/survey-routing.module.ts import { NgModule } from "@angular/core"; import { Routes } from "@angular/router"; import { NativeScriptRouterModule } from "nativescript-angular/router"; import { SurveyBooleanQuestionComponent } from "./survey-boolean-question.component"; import { SurveyCompleteComponent } from "./survey-complete/survey-complete.component"; import { SurveyDateQuestionComponent } from "./survey-date-question.component"; import { SurveyTextQuestionComponent } from "./survey-text-question.component"; const routes: Routes = [ { path: "", component: SurveyBooleanQuestionComponent }, { path: "second", component: SurveyTextQuestionComponent }, { path: "third", component: SurveyDateQuestionComponent }, { path: "complete", component: SurveyCompleteComponent } ]; @NgModule({ imports: [NativeScriptRouterModule.forChild(routes)], exports: [NativeScriptRouterModule] }) export class SurveyRoutingModule { }
rynop/nativescript-app-templates
packages/template-health-survey-ng/src/app/core/task-manager/steps/index.ts
<filename>packages/template-health-survey-ng/src/app/core/task-manager/steps/index.ts export * from "./consent-review-step.model"; export * from "./consent-sharing-step.model"; export * from "./registration-step.model"; export * from "./sign-up-step.model"; export * from "./study-boolean-step.model"; export * from "./study-date-step.model"; export * from "./study-text-step.model"; export * from "./visual-consent-step.model";
rynop/nativescript-app-templates
packages/template-master-detail-kinvey-ts/app/shared/config.ts
<filename>packages/template-master-detail-kinvey-ts/app/shared/config.ts export class Config { static kinveyAppKey = "kid_By1mL8fnb"; static kinveyAppSecret = "4b0c01a98ce942e89d04acecdfa8dcaa"; static kinveyUsername = "admin"; static kinveyPassword = "<PASSWORD>"; }
rynop/nativescript-app-templates
packages/template-patient-care-ng/src/care/care-card/shared/care-card-activity.service.ts
import { Injectable } from "@angular/core"; // TODO: should be imported from kinvey-nativescript-sdk/angular but declaration file is currently missing import { DataStoreService, Errors } from "kinvey-nativescript-sdk/lib/angular"; import { CareCardEventService } from "./care-card-event.service"; import { CarePlanActivityGroup } from "./care-plan-activity-group.enum"; import { CarePlanActivityType } from "./care-plan-activity-type.enum"; import { CarePlanActivity } from "./care-plan-activity.model"; import { CarePlanEvent } from "./care-plan-event.model"; @Injectable({ providedIn: "root" }) export class CareCardActivityService { private _activityStore = null; private _activities: Array<CarePlanActivity>; private _activitiesPromise: Promise<any>; constructor(private _careCardEventService: CareCardEventService, dataStoreService: DataStoreService) { this._activityStore = dataStoreService.collection("Activity"); this._activities = new Array<CarePlanActivity>(); } getActivity(title: string): CarePlanActivity { const activity = this._activities.find((currentActivity) => { return currentActivity.title === title; }); return activity; } getActivities(): Promise<any> { if (!this._activitiesPromise) { this._activitiesPromise = this._activityStore.find().toPromise() .then((data) => { const activities = []; if (data && data.length) { data.forEach((activityData: any) => { const activity = new CarePlanActivity(activityData); activities.push(activity); }); } this._activities = activities; return activities; }) .catch((error: Errors.BaseError) => { alert({ title: "Oops something went wrong.", message: error.message, okButtonText: "Ok" }); }); } return this._activitiesPromise; } createActivitiesWithEvents(selectedDate: Date) { const physicalActivities = new Array<CarePlanActivity>(); const assessmentActivities = new Array<CarePlanActivity>(); const otherActivities = new Array<CarePlanActivity>(); const medicationActivities = new Array<CarePlanActivity>(); return this.getActivities() .then((activities: Array<CarePlanActivity>) => { for (const activity of activities) { activity.events = new Array<CarePlanEvent>(); if (activity.type !== CarePlanActivityType.ReadOnly) { activity.events = this.createActivityEventPlaceholders(activity, selectedDate); } if (activity.groupIdentifier === CarePlanActivityGroup.Physical) { physicalActivities.push(activity); } else if (activity.groupIdentifier === CarePlanActivityGroup.Assessment) { assessmentActivities.push(activity); } else if (activity.groupIdentifier === CarePlanActivityGroup.Medication) { medicationActivities.push(activity); } else if (activity.groupIdentifier === CarePlanActivityGroup.Other) { otherActivities.push(activity); } } const mapEventsPromises = []; mapEventsPromises.push(this.mapEvents(physicalActivities, selectedDate)); mapEventsPromises.push(this.mapEvents(assessmentActivities, selectedDate)); mapEventsPromises.push(this.mapEvents(otherActivities, selectedDate)); mapEventsPromises.push(this.mapEvents(medicationActivities, selectedDate)); return Promise.all(mapEventsPromises) .then(() => ({ physicalActivities, assessmentActivities, otherActivities, medicationActivities })); }); } private mapEvents(activityCollection: Array<CarePlanActivity>, selectedDate: Date) { const savedEventsPromises = []; activityCollection.forEach((activity) => { if (activity.type === CarePlanActivityType.ReadOnly) { return; } savedEventsPromises.push(this._careCardEventService.findEvents(activity.title, selectedDate) .then((savedEvents) => { if (savedEvents.length && activity.events.length) { for (const event of savedEvents) { activity.events[event.occurrenceIndexOfDay] = event; } } })); }); return Promise.all(savedEventsPromises); } private createActivityEventPlaceholders(activity: CarePlanActivity, selectedDate: Date): Array<CarePlanEvent> { const events = new Array<CarePlanEvent>(); const day: number = selectedDate.getDay(); const occurrencesForDay: number = activity.schedule.occurrences[day] || 0; for (let index = 0; index < occurrencesForDay; index++) { const event = new CarePlanEvent(activity, selectedDate, index); events.push(event); } return events; } }
rynop/nativescript-app-templates
packages/template-health-survey-ng/src/app/survey/survey-text-question.component.ts
import { Component } from "@angular/core"; import { RouterExtensions } from "nativescript-angular/router"; import { StudyTextStep } from "../core/task-manager/steps"; import { TaskManagerService } from "../core/task-manager/task-manager.service"; import { AppService } from "../shared/app.service"; @Component({ selector: "SurveyTextQuestion", templateUrl: "./survey-text-question.component.html" }) export class SurveyTextQuestionComponent { answer: string; constructor( public appService: AppService, private _routerExtensions: RouterExtensions, private _taskManagerService: TaskManagerService ) { } get isAnswerSelected(): boolean { return this.answer != null && this.answer.length > 0; } onNextButtonTap(pushTask: boolean = true) { if (pushTask) { this._taskManagerService.addStep(new StudyTextStep("textQuestionStep", this.answer)); this._taskManagerService.pushTask("textQuestionTask"); } this._routerExtensions.navigate(["/survey/third"], { clearHistory: true, animated: true, transition: { name: "slide", duration: 200, curve: "ease" } }); } }
rynop/nativescript-app-templates
packages/template-health-survey-ng/src/app/shared/shared.module.ts
import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core"; import { NativeScriptUIDataFormModule } from "nativescript-ui-dataform/angular"; @NgModule({ imports: [ NativeScriptUIDataFormModule ], exports: [ NativeScriptUIDataFormModule ], providers: [], schemas: [ NO_ERRORS_SCHEMA ] }) export class SharedModule { }
rynop/nativescript-app-templates
packages/template-health-survey-ng/src/app/core/task-manager/steps/consent-review-step.model.ts
export class ConsentReviewStep { results: Array<any>; saveable: boolean; identifier: string; constructor(identifier: string, givenName: string, familyName: string) { this.results = [{ identifier: "consentDocumentParticipantSignature", consented: true, saveable: false, signature: { signatureImage: "", requiresName: true, givenName, requiresSignatureImage: false, title: "Participant", familyName, signatureDate: new Date().toUTCString(), identifier: "consentDocumentParticipantSignature" } }]; this.saveable = false; this.identifier = identifier; } }
rynop/nativescript-app-templates
packages/template-master-detail-kinvey-ts/app/cars/car-detail-page/car-detail-page.ts
import { topmost } from "tns-core-modules/ui/frame"; import { NavigatedData, Page } from "tns-core-modules/ui/page"; import { CarDetailViewModel } from "./car-detail-view-model"; /* *********************************************************** * This is the item details code behind in the master-detail structure. * This code behind retrieves the passed parameter from the master list component, * finds the data item by this parameter and displays the detailed data item information. *************************************************************/ /* *********************************************************** * Use the "onNavigatingTo" handler to initialize the page binding context. *************************************************************/ export function onNavigatingTo(args: NavigatedData): void { /* *********************************************************** * The "onNavigatingTo" event handler lets you detect if the user navigated with a back button. * Skipping the re-initialization on back navigation means the user will see the * page in the same data state that he left it in before navigating. *************************************************************/ if (args.isBackNavigation) { return; } const page = <Page>args.object; page.bindingContext = new CarDetailViewModel(page.navigationContext); } /* *********************************************************** * The back button is essential for a master-detail feature. *************************************************************/ export function onBackButtonTap(): void { topmost().goBack(); } /* *********************************************************** * The master-detail template comes with an example of an item edit page. * Check out the edit page in the /cars/car-detail-edit-page folder. *************************************************************/ export function onEditButtonTap(args): void { const bindingContext = <CarDetailViewModel>args.object.bindingContext; topmost().navigate({ moduleName: "cars/car-detail-edit-page/car-detail-edit-page", context: bindingContext.car, animated: true, transition: { name: "slideTop", duration: 200, curve: "ease" } }); }
rynop/nativescript-app-templates
packages/template-patient-care-ng/src/care/connect/shared/contact.model.ts
import { ContactInfo } from "./contact-info.model"; export class Contact { id: string; name: string; monogram: string; tintColor: string; relation: string; type: number; contactInfoItems: Array<ContactInfo>; constructor(options: any) { this.id = options._id; this.name = options.name; this.monogram = options.monogram; this.relation = options.relation; this.type = options.type; this.contactInfoItems = new Array<ContactInfo>(); if (options.contactInfoItems && options.contactInfoItems.length) { options.contactInfoItems.forEach((contactInfoData) => { const contactInfo = new ContactInfo(contactInfoData); this.contactInfoItems.push(contactInfo); }); } } }
rynop/nativescript-app-templates
packages/template-health-survey-ng/src/app/shared/config.ts
export class Config { static kinveyAppKey: string = "<KEY>"; static kinveyAppSecret: string = "4440bad69221497e90051e761c97deed"; static kinveyApiHostname: string; static kinveyMicHostname: string; }
rynop/nativescript-app-templates
packages/template-patient-care-ng/src/care/connect/shared/connect-item.model.ts
export class ConnectItem { id: string; name: string; shortName: string; title: string; phone: string; email: string; constructor(id, name, shortName, title, phone, email) { this.id = id; this.name = name; this.shortName = shortName; this.title = title; this.phone = phone; this.email = email; } }
rynop/nativescript-app-templates
packages/template-health-survey-ng/src/app/survey/survey.module.ts
import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core"; import { NativeScriptCommonModule } from "nativescript-angular/common"; import { NativeScriptFormsModule } from "nativescript-angular/forms"; import { SharedModule } from "../shared/shared.module"; import { SurveyBooleanQuestionComponent } from "./survey-boolean-question.component"; import { SurveyCompleteComponent } from "./survey-complete/survey-complete.component"; import { SurveyDateQuestionComponent } from "./survey-date-question.component"; import { SurveyRoutingModule } from "./survey-routing.module"; import { SurveyTextQuestionComponent } from "./survey-text-question.component"; @NgModule({ imports: [ NativeScriptFormsModule, NativeScriptCommonModule, SharedModule, SurveyRoutingModule ], declarations: [ SurveyBooleanQuestionComponent, SurveyCompleteComponent, SurveyDateQuestionComponent, SurveyTextQuestionComponent ], schemas: [ NO_ERRORS_SCHEMA ] }) export class SurveyModule { }
rynop/nativescript-app-templates
packages/template-master-detail-kinvey-ts/app/cars/cars-list-view-model.ts
<reponame>rynop/nativescript-app-templates import { Observable } from "tns-core-modules/data/observable"; import { ObservableArray } from "tns-core-modules/data/observable-array"; import { Config } from "../shared/config"; import { ObservableProperty } from "../shared/observable-property-decorator"; import { Car } from "./shared/car-model"; import { CarService } from "./shared/car-service"; /* *********************************************************** * This is the master list view model. *************************************************************/ export class CarsListViewModel extends Observable { @ObservableProperty() cars: ObservableArray<Car> = new ObservableArray<Car>([]); @ObservableProperty() isLoading: boolean = false; private _carService: CarService; constructor() { super(); this._carService = CarService.getInstance(); } load(): void { this.isLoading = true; this._carService.load() .then((cars: Array<Car>) => { this.cars = new ObservableArray(cars); this.isLoading = false; }) .catch(() => { this.isLoading = false; }); } }
rynop/nativescript-app-templates
packages/template-health-survey-ng/src/app/core/task-manager/steps/study-date-step.model.ts
import * as jsTimezone from "jstimezonedetect"; import { StudyStep } from "./study-step.model"; export class StudyDateStep extends StudyStep { private static getIsDaylightSavingTime(date: Date) { const januaryDate = new Date(date.getFullYear(), 0, 1); const julyDate = new Date(date.getFullYear(), 6, 1); const standardTimeZoneOffset = Math.max(januaryDate.getTimezoneOffset(), julyDate.getTimezoneOffset()); return date.getTimezoneOffset() < standardTimeZoneOffset; } private static getTimezoneAbbreviation(date: Date): string { const localeTimeStringArray = date.toLocaleTimeString("en-us", { timeZoneName: "short" }).split(" "); let abbreviation = ""; if (localeTimeStringArray.length > 2) { abbreviation = localeTimeStringArray[2].replace(/[(^,)$]/g, ""); } return abbreviation; } results: Array<any>; saveable: boolean; identifier: string; constructor(identifier: string, dateAnswer: Date) { super(identifier); this.results = [ { calendar: "Gregorian", timeZone: { secondsFromGMT: dateAnswer.getTimezoneOffset() * 60, isDaylightSavingTime: StudyDateStep.getIsDaylightSavingTime(dateAnswer), abbreviation: StudyDateStep.getTimezoneAbbreviation(dateAnswer), identifier: jsTimezone.determine().name() }, questionType: "Date", saveable: false, dateAnswer, identifier } ]; } }
rynop/nativescript-app-templates
packages/template-master-detail-kinvey-ng/src/app/cars/shared/car.service.ts
<reponame>rynop/nativescript-app-templates<gh_stars>1-10 import { Injectable } from "@angular/core"; // TODO: should be imported from kinvey-nativescript-sdk/angular but declaration file is currently missing import { DataStoreService, FilesService, UserService, Query } from "kinvey-nativescript-sdk/lib/angular"; import { File } from "tns-core-modules/file-system"; import { Config } from "../../shared/config"; import { Car } from "./car.model"; const editableProperties = [ "class", "doors", "hasAC", "transmission", "luggage", "name", "price", "seats", "imageUrl" ]; @Injectable({ providedIn: "root" }) export class CarService { private static cloneUpdateModel(car: Car): object { // tslint:disable-next-line:ban-comma-operator return editableProperties.reduce((a, e) => (a[e] = car[e], a), { _id: car.id }); } private _allCars: Array<Car> = []; private _carsStore = null; constructor( dataStoreService: DataStoreService, private _filesService: FilesService, private _userService: UserService) { this._carsStore = dataStoreService.collection("cars"); } getCarById(id: string): Car { if (!id) { return; } return this._allCars.filter((car) => { return car.id === id; })[0]; } load(): Promise<any> { return this.login().then(() => { return this._carsStore.sync(); }).then(() => { const sortByNameQuery = new Query(); sortByNameQuery.ascending("name"); const stream = this._carsStore.find(sortByNameQuery); return stream.toPromise(); }).then((data) => { this._allCars = []; data.forEach((carData: any) => { carData.id = carData._id; const car = new Car(carData); this._allCars.push(car); }); return this._allCars; }); } update(carModel: Car): Promise<any> { const updateModel = CarService.cloneUpdateModel(carModel); return this._carsStore.save(updateModel); } uploadImage(remoteFullPath: string, localFullPath: string): Promise<any> { const imageFile = File.fromPath(localFullPath); const imageContent = imageFile.readSync(); const metadata = { filename: imageFile.name, mimeType: this.getMimeType(imageFile.extension), size: imageContent.length, public: true }; return this._filesService.upload(imageFile, metadata, { timeout: 2147483647 }) .then((uploadedFile: any) => { const query = new Query(); query.equalTo("_id", uploadedFile._id); return this._filesService.find(query); }) .then((files: Array<any>) => { if (files && files.length) { const file = files[0]; file.url = file._downloadURL; return file; } else { Promise.reject(new Error("No items with the given ID could be found.")); } }); } private login(): Promise<any> { if (!!this._userService.getActiveUser()) { return Promise.resolve(); } else { return this._userService.login(Config.kinveyUsername, Config.kinveyPassword); } } private getMimeType(imageExtension: string): string { const extension = imageExtension === "jpg" ? "jpeg" : imageExtension; return "image/" + extension.replace(/\./g, ""); } }
rynop/nativescript-app-templates
packages/template-drawer-navigation-ts/app/search/search-page.ts
import { RadSideDrawer } from "nativescript-ui-sidedrawer"; import * as app from "tns-core-modules/application"; import { EventData } from "tns-core-modules/data/observable"; import { NavigatedData, Page } from "tns-core-modules/ui/page"; import { SearchViewModel } from "./search-view-model"; export function onNavigatingTo(args: NavigatedData) { const page = <Page>args.object; page.bindingContext = new SearchViewModel(); } export function onDrawerButtonTap(args: EventData) { const sideDrawer = <RadSideDrawer>app.getRootView(); sideDrawer.showDrawer(); }
rynop/nativescript-app-templates
packages/template-patient-care-ng/src/care/care-card/shared/care-plan-activity-group.enum.ts
export const enum CarePlanActivityGroup { Physical = "Physical Activity", Assessment = "Assessment", Medication = "Medications", Other = "Other" }
rynop/nativescript-app-templates
packages/template-patient-care-ng/src/care/care.module.ts
import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core"; import { NativeScriptCommonModule } from "nativescript-angular/common"; import { NativeScriptFormsModule } from "nativescript-angular/forms"; import { NativeScriptUIGaugeModule } from "nativescript-ui-gauge/angular"; import { NativeScriptUIListViewModule } from "nativescript-ui-listview/angular"; import { ActivityDetailComponent } from "./care-card/activity-detail/activity-detail.component"; import { ActivityListComponent } from "./care-card/activity/activity-list.component"; import { CareCardComponent } from "./care-card/care-card.component"; import { CareDashboardComponent } from "./care-card/care-dashboard/care-dashboard.component"; import { RadialRatingComponent } from "./care-card/care-dashboard/radial-rating/radial-rating.component"; import { ConnectDetailComponent } from "./connect/connect-detail/connect-detail.component"; import { ConnectComponent } from "./connect/connect.component"; import { CareRoutingModule } from "./care-routing.module"; import { CareComponent } from "./care.component"; @NgModule({ imports: [ NativeScriptCommonModule, NativeScriptUIGaugeModule, NativeScriptUIListViewModule, NativeScriptFormsModule, CareRoutingModule ], declarations: [ CareCardComponent, CareDashboardComponent, RadialRatingComponent, ConnectComponent, ActivityDetailComponent, ActivityListComponent, ConnectDetailComponent, CareComponent ], providers: [], schemas: [ NO_ERRORS_SCHEMA ] }) export class CareModule { }
rynop/nativescript-app-templates
packages/template-health-survey-ng/src/app/core/task-manager/steps/registration-step.model.ts
export class RegistrationStep { results: Array<any>; saveable: boolean; identifier: string; constructor(identifier: string, registrationData: any) { this.results = [ { textAnswer: registrationData.email, questionType: "Text", saveable: false, identifier: "ORKRegistrationFormItemEmail" }, { questionType: "Text", saveable: false, identifier: "ORKRegistrationFormItemPassword" }, { questionType: "Text", saveable: false, identifier: "ORKRegistrationFormItemConfirmPassword" }, { textAnswer: registrationData.givenName, questionType: "Text", saveable: false, identifier: "ORKRegistrationFormItemGivenName" }, { textAnswer: registrationData.familyName, questionType: "Text", saveable: false, identifier: "ORKRegistrationFormItemFamilyName" }, { choiceAnswers: [ registrationData.gender ], questionType: "SingleChoice", saveable: false, identifier: "ORKRegistrationFormItemGender" }, { calendar: "Gregorian", questionType: "Date", saveable: false, dateAnswer: registrationData.dateOfBirth, identifier: "ORKRegistrationFormItemDOB" } ]; this.saveable = false; this.identifier = identifier; } }
rynop/nativescript-app-templates
packages/template-health-survey-ng/src/app/consent/consent-routing.module.ts
import { NgModule } from "@angular/core"; import { Routes } from "@angular/router"; import { NativeScriptRouterModule } from "nativescript-angular/router"; import { ConsentComponent } from "./consent-review/consent/consent.component"; import { ReviewComponent } from "./consent-review/review/review.component"; import { ConsentSharingComponent } from "./consent-sharing/consent-sharing.component"; import { DataGatheringComponent } from "./visual-consent/data-gathering/data-gathering.component"; import { DataUseComponent } from "./visual-consent/data-use/data-use.component"; import { StudySurveyComponent } from "./visual-consent/study-survey/study-survey.component"; import { TimeCommitmentComponent } from "./visual-consent/time-commitment/time-commitment.component"; import { WithdrawingComponent } from "./visual-consent/withdrawing/withdrawing.component"; import { WelcomeComponent } from "./welcome.component"; const routes: Routes = [ { path: "", component: WelcomeComponent }, { path: "consent-review/consent", component: ConsentComponent }, { path: "consent-review/review", component: ReviewComponent }, { path: "consent-sharing", component: ConsentSharingComponent }, { path: "visual-consent/data-gathering", component: DataGatheringComponent }, { path: "visual-consent/data-use", component: DataUseComponent }, { path: "visual-consent/study-survey", component: StudySurveyComponent }, { path: "visual-consent/time-commitment", component: TimeCommitmentComponent }, { path: "visual-consent/withdrawing", component: WithdrawingComponent } ]; @NgModule({ imports: [NativeScriptRouterModule.forChild(routes)], exports: [NativeScriptRouterModule] }) export class ConsentRoutingModule { }
rynop/nativescript-app-templates
packages/template-master-detail-ts/app/cars/cars-list-page.ts
<filename>packages/template-master-detail-ts/app/cars/cars-list-page.ts<gh_stars>0 import { ListViewEventData } from "nativescript-ui-listview"; import { topmost } from "tns-core-modules/ui/frame"; import { NavigatedData, Page } from "tns-core-modules/ui/page"; import { CarsListViewModel } from "./cars-list-view-model"; import { Car } from "./shared/car-model"; export function onNavigatingTo(args: NavigatedData): void { if (args.isBackNavigation) { return; } const viewModel = new CarsListViewModel(); viewModel.load(); const page = <Page>args.object; page.bindingContext = viewModel; } export function onCarItemTap(args: ListViewEventData): void { const tappedCarItem = <Car>args.view.bindingContext; topmost().navigate({ moduleName: "cars/car-detail-page/car-detail-page", context: tappedCarItem, animated: true, transition: { name: "slide", duration: 200, curve: "ease" } }); }
rynop/nativescript-app-templates
packages/template-health-survey-ng/src/app/consent/consent.module.ts
<filename>packages/template-health-survey-ng/src/app/consent/consent.module.ts import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core"; import { NativeScriptCommonModule } from "nativescript-angular/common"; import { SharedModule } from "../shared/shared.module"; import { ConsentComponent } from "./consent-review/consent/consent.component"; import { ReviewComponent } from "./consent-review/review/review.component"; import { ConsentRoutingModule } from "./consent-routing.module"; import { ConsentSharingComponent } from "./consent-sharing/consent-sharing.component"; import { DataGatheringComponent } from "./visual-consent/data-gathering/data-gathering.component"; import { DataUseComponent } from "./visual-consent/data-use/data-use.component"; import { StudySurveyComponent } from "./visual-consent/study-survey/study-survey.component"; import { TimeCommitmentComponent } from "./visual-consent/time-commitment/time-commitment.component"; import { WithdrawingComponent } from "./visual-consent/withdrawing/withdrawing.component"; import { WelcomeComponent } from "./welcome.component"; @NgModule({ imports: [ ConsentRoutingModule, NativeScriptCommonModule, SharedModule ], declarations: [ WelcomeComponent, ConsentComponent, DataGatheringComponent, DataUseComponent, ReviewComponent, ConsentSharingComponent, StudySurveyComponent, TimeCommitmentComponent, WithdrawingComponent ], schemas: [ NO_ERRORS_SCHEMA ] }) export class ConsentModule { }
SimonAlling/better-sweclockers
src/operations/actions/split-quote.ts
<reponame>SimonAlling/better-sweclockers import * as BB from "bbcode-tags"; import * as CONFIG from "~src/config"; import * as SITE from "~src/site"; import { r } from "~src/utilities"; import { insertIn, placeCursorIn } from "../logic/textarea"; export default function(textarea: HTMLTextAreaElement, undoSupport: boolean): void { // Yes, this code is hard to understand. It was conceived using a considerable amount of trial and error. const beforeSelection = textarea.value.substring(0, textarea.selectionStart); const afterSelection = textarea.value.substring(textarea.selectionEnd); const existingNewlinesBeforeSelection = lengthOfGuaranteedMatchIn(beforeSelection, /\n*$/); const existingNewlinesAfterSelection = lengthOfGuaranteedMatchIn(afterSelection, /^\n*/); const cursorIsBetweenTwoExistingQuotes = ( new RegExp(r`\[\/${SITE.TAG.quote}\]$`, "i").test(beforeSelection.trimRight()) && new RegExp(r`^\[${SITE.TAG.quote}`, "i").test(afterSelection.trimLeft()) ); if (cursorIsBetweenTwoExistingQuotes) { // Just insert empty lines and place the cursor accordingly. const numberOfNewlinesToInsert = Math.max( 0, // Using a negative value with String.prototype.repeat is a RangeError. CONFIG.CONTENT.splitQuoteEmptyLines + 1 - existingNewlinesBeforeSelection - existingNewlinesAfterSelection, ); // If there are more newlines than we'd like between the quotes, they will be left untouched, because we don't want to mess with deleting content. insertIn(textarea, { string: "\n".repeat(numberOfNewlinesToInsert), replace: undoSupport, }); placeCursorIn(textarea, beforeSelection.length - existingNewlinesBeforeSelection + 1); // + 1 to get past the first line break } else { // Add quote tags and place cursor. const startTag = BB.start(SITE.TAG.quote); const endTag = BB.end(SITE.TAG.quote); const extraNewlineBeforeSelectionNeeded = existingNewlinesBeforeSelection === 0; const extraNewlineAfterSelectionNeeded = existingNewlinesAfterSelection === 0; insertIn(textarea, { string: [ extraNewlineBeforeSelectionNeeded ? "\n" : "", endTag, "\n".repeat(CONFIG.CONTENT.splitQuoteEmptyLines + 1), startTag, extraNewlineAfterSelectionNeeded ? "\n" : "", ].join(""), replace: undoSupport }); placeCursorIn(textarea, beforeSelection.length + (extraNewlineBeforeSelectionNeeded ? 1 : 0) + endTag.length + 1); // + 1 to get past a line break } } function lengthOfGuaranteedMatchIn(s: string, regexThatAlwaysMatches: RegExp): number { // This function should only be used with regexes that always match (which can't be statically checked). return (s.match(regexThatAlwaysMatches) as RegExpMatchArray)[0].length; }
SimonAlling/better-sweclockers
__tests__/browser.test.ts
import { check } from "jest-function"; import * as browser from "../src/browser"; import { sorted } from "./utilities"; // What Is My Browser (WIMB) Database: // https://developers.whatismybrowser.com/useragents/explore/software_type_specific/web-browser describe("Android detection", () => { it("is sound", () => { const NON_ANDROID_USER_AGENT_STRINGS = [ `Mozilla/5.0 (Windows NT 5.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36`, // Windows, Chrome 60 (from WIMB) `Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36`, // Ubuntu 20.04, Chrome 83 `Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:24.0) Gecko/20100101 Firefox/24.0`, // Ubuntu, Firefox 24 (from WIMB) `Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0`, // Ubuntu 20.04, Firefox 78 `Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1`, // iPad Pro, iOS 11, Safari (from Chrome developer tools) `Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1`, // iPhone X, iOS 13, Safari (from Chrome developer tools) ] as const; expect(NON_ANDROID_USER_AGENT_STRINGS).toEqual(sorted(NON_ANDROID_USER_AGENT_STRINGS)); // Enforces sorted order above. const soundnessSpecification = NON_ANDROID_USER_AGENT_STRINGS.map(x => ({ in: x, out: false })); check(browser.isAndroid).against(soundnessSpecification); }); it("is complete", () => { const ANDROID_USER_AGENT_STRINGS = [ `Mozilla/5.0 (Android 10; Mobile; rv:68.0) Gecko/68.0 Firefox/68.0`, // Galaxy S9, Firefox `Mozilla/5.0 (Linux; Android 10; SM-G960F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Mobile Safari/537.36`, // Galaxy S9, Chrome `Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Mobile Safari/537.36`, // Galaxy S5 in Chrome developer tools `Mozilla/5.0 (Linux; Android 6.0.1; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Mobile Safari/537.36`, // Moto G4 in Chrome developer tools `Mozilla/5.0 (Linux; Android 6.0.1; RedMi Note 5 Build/RB3N5C; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/68.0.3440.91 Mobile Safari/537.36`, // WIMB `Mozilla/5.0 (Linux; Android 7.0; F5321) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Mobile Safari/537.36`, // Xperia X Compact, Chrome `Mozilla/5.0 (Linux; Android 7.1.2; AFTMM Build/NS6265; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/70.0.3538.110 Mobile Safari/537.36`, // WIMB ] as const; expect(ANDROID_USER_AGENT_STRINGS).toEqual(sorted(ANDROID_USER_AGENT_STRINGS)); // Enforces sorted order above. const completenessSpecification = ANDROID_USER_AGENT_STRINGS.map(x => ({ in: x, out: true })); check(browser.isAndroid).against(completenessSpecification); }); });
SimonAlling/better-sweclockers
src/operations.ts
<reponame>SimonAlling/better-sweclockers<gh_stars>10-100 import { DOMCONTENTLOADED } from "userscripter/lib/environment"; import { Operation, operation } from "userscripter/lib/operations"; import * as CONFIG from "~src/config"; import { isInEditMode, isInEditMode_forum, isInEditMode_market, isInEditMode_marketContact, isInEditMode_PM, isInForumThreadsView, isOnBSCPreferencesPage, isOnSomeProfilePage, isOnSweclockersSettingsPage, isReadingEditorialContent, isReadingForumThread, isReadingThread, mayHaveJustSubmittedForumPost, mayHaveJustSubmittedPM, } from "~src/environment"; import { P, Preferences } from "~src/preferences"; import SELECTOR from "~src/selectors"; import * as SITE from "~src/site"; import * as autosaveDraft from "./operations/autosave-draft"; import manageCaretPosition from "./operations/caret-position"; import * as DarkTheme from "./operations/dark-theme"; import insertDraftModeToggle from "./operations/draft-mode-toggle"; import insertEditingTools from "./operations/editing-tools"; import insertHeadingToolbarButton from "./operations/heading-toolbar-button"; import enableImprovedBuiltinEditingTools from "./operations/improved-builtin-editing-tools"; import enableImprovedBuiltinEditingToolsUrl from "./operations/improved-builtin-editing-tools-url"; import adaptCorrectionsLink from "./operations/improved-corrections"; import * as keyboardShortcutsEditMode from "./operations/keyboard-shortcuts/edit-mode"; import insertLinkToTop from "./operations/link-to-top"; import insertMentionEveryoneButton from "./operations/mention-everyone"; import performMousetrapPreparations from "./operations/mousetrap-preparations"; import insertPMLinks from "./operations/pm-links"; import insertPreferencesLink from "./operations/preferences-link"; import insertPreferencesMenu from "./operations/preferences-menu"; import insertPreferencesShortcut from "./operations/preferences-shortcut"; import preventAccidentalSignout from "./operations/prevent-accidental-signout"; import * as preventAccidentalUnload from "./operations/prevent-accidental-unload"; import * as Proofreading from "./operations/proofreading"; import insertQuoteSignatureButtons from "./operations/quote-signature-buttons"; import rememberLocationInMarket from "./operations/remember-location-in-market"; import removeMobileSiteDisclaimer from "./operations/remove-mobile-site-disclaimer"; import replaceFollowedThreadsLink from "./operations/replace-followed-threads-link"; import insertTableToolbarButton from "./operations/table-toolbar-button"; import insertTextareaSizeToggle from "./operations/textarea-size-toggle"; import filterUninterestingSubforums from "./operations/uninteresting-subforums"; const ALWAYS = true; const improvedBuiltinEditingToolsDescription = "enable improved built-in editing tools"; const shouldEnableImprovedBuiltinEditingTools = (isInEditMode || isReadingThread) && Preferences.get(P.edit_mode._.improved_builtin_editing_tools); const shouldInsertPreferencesShortcut = Preferences.get(P.general._.insert_preferences_shortcut); const uninterestingSubforumIDs = Preferences.get(P.interests._.uninteresting_subforums); // True here means the user wants us to act as if there is undo support (i.e. take no precautions to protect data). // Chrome always has actual undo support and Firefox never does. const undoSupport = Preferences.get(P.advanced._.undo_support); const OPERATIONS: readonly Operation<any>[] = [ operation({ description: "set document id", condition: () => ALWAYS, action: () => { document.documentElement.id = CONFIG.ID.document; }, }), operation({ // I haven't managed to make this operation work at all in Firefox; the default action is just not overridden. description: improvedBuiltinEditingToolsDescription + " (URL/hyperlink button)", condition: () => shouldEnableImprovedBuiltinEditingTools, // This operation cannot be deferred until DOMContentLoaded, because then it can't override the default action for the URL button. dependencies: { body: "body" }, // Defers the operation until SweClockers' script has defined Main (needed by the operation). action: enableImprovedBuiltinEditingToolsUrl(undoSupport), }), operation({ description: "insert preferences menu", condition: () => isOnBSCPreferencesPage, dependencies: { body: "body" }, // Back in 2018, I had problems with document.body being null when logged out and DOMContentLoaded not firing when logged in. Not able to reproduce it in July 2020, but this always works. action: insertPreferencesMenu, }), operation({ description: "disable scroll restoration", condition: () => Preferences.get(P.advanced._.disable_scroll_restoration), action: () => { if ("scrollRestoration" in history) { history.scrollRestoration = "manual"; } }, }), operation({ description: "prevent accidental unload (post or message)", condition: () => isInEditMode && Preferences.get(P.advanced._.prevent_accidental_unload), dependencies: { textarea: SELECTOR.textarea, _actionButtons: SELECTOR.actionButtons, }, action: preventAccidentalUnload.postOrMessage, }), operation({ description: "prevent accidental unload (corrections)", condition: () => isReadingEditorialContent && Preferences.get(P.advanced._.prevent_accidental_unload), action: preventAccidentalUnload.corrections, }), operation({ description: "manage caret position in textarea", condition: () => isInEditMode, // Should be run unconditionally (see the implementation for more info). dependencies: { textarea: SELECTOR.textarea, // The market doesn't have a dedicated preview button; its save button fills that purpose in this context. previewButton: isInEditMode_market ? SELECTOR.saveButton : SELECTOR.previewButton, }, action: manageCaretPosition, }), operation({ description: "remove mobile site disclaimer", condition: () => isInEditMode_forum && Preferences.get(P.edit_mode._.remove_mobile_site_disclaimer), dependencies: { textarea: SELECTOR.textarea }, action: removeMobileSiteDisclaimer, }), operation({ description: "insert editing tools", condition: () => isInEditMode && Preferences.get(P.editing_tools._.enable), dependencies: { textarea: SELECTOR.textarea }, action: insertEditingTools(undoSupport), }), operation({ description: "insert editing tools in quick reply form", condition: () => isReadingThread && Preferences.get(P.editing_tools._.enable) && Preferences.get(P.editing_tools._.in_quick_reply_form), dependencies: { textarea: SELECTOR.textarea }, action: insertEditingTools(undoSupport), }), operation({ description: improvedBuiltinEditingToolsDescription, condition: () => shouldEnableImprovedBuiltinEditingTools, deferUntil: DOMCONTENTLOADED, // because Tanuki must be defined action: enableImprovedBuiltinEditingTools, }), operation({ description: "insert heading toolbar button", condition: () => isInEditMode && Preferences.get(P.edit_mode._.insert_heading_toolbar_button), dependencies: { textarea: SELECTOR.textarea, strikeButton: SELECTOR.textareaToolbarStrikeButton, }, action: insertHeadingToolbarButton(undoSupport), }), operation({ description: "insert table toolbar button", condition: () => isInEditMode && Preferences.get(P.edit_mode._.insert_table_toolbar_button), dependencies: { textarea: SELECTOR.textarea, unorderedListButton: SELECTOR.textareaToolbarUnorderedListButton, }, action: insertTableToolbarButton(undoSupport), }), operation({ description: "insert textarea size toggle", condition: () => isInEditMode && Preferences.get(P.edit_mode._.textarea_size_toggle), dependencies: { textarea: SELECTOR.textarea, toolbarInner: SELECTOR.textareaToolbarInner, }, action: insertTextareaSizeToggle, }), operation({ description: "insert preferences shortcut", condition: () => !isOnBSCPreferencesPage && shouldInsertPreferencesShortcut, dependencies: { notificationsBar: "." + SITE.CLASS.notifications, }, action: insertPreferencesShortcut, }), operation({ description: "insert dark theme toggle", condition: () => !isOnBSCPreferencesPage && Preferences.get(P.dark_theme._.show_toggle), dependencies: { menuLockToggle: "#" + SITE.ID.menuLockToggle }, action: DarkTheme.insertToggle, }), operation({ description: "prevent accidental signout", condition: () => isOnSomeProfilePage && Preferences.get(P.advanced._.prevent_accidental_signout), action: preventAccidentalSignout, deferUntil: DOMCONTENTLOADED, // We can't extract the user's ID at document-start. }), operation({ description: "insert preferences link", condition: () => isOnSweclockersSettingsPage, dependencies: { settingsNavigation: SELECTOR.settingsNavigation }, action: insertPreferencesLink, }), operation({ description: "insert link to top", condition: () => isReadingThread && Preferences.get(P.forum_threads._.insert_link_to_top), action: insertLinkToTop, dependencies: { parent: SELECTOR.pageNavigationAfterForumPosts }, }), operation({ description: "insert PM links", condition: () => isReadingForumThread && Preferences.get(P.forum_threads._.insert_pm_links), action: insertPMLinks, deferUntil: DOMCONTENTLOADED, }), operation({ description: "insert quote signature buttons", condition: () => isReadingThread && Preferences.get(P.forum_threads._.quote_signature_buttons), action: insertQuoteSignatureButtons, deferUntil: DOMCONTENTLOADED, }), operation({ description: "adapt corrections link to work with improved corrections", condition: () => isReadingEditorialContent && Preferences.get(P.general._.improved_corrections), dependencies: { correctionsLink: "#" + SITE.ID.correctionsLink }, action: adaptCorrectionsLink, }), operation({ description: "filter uninteresting subforums", condition: () => isInForumThreadsView && uninterestingSubforumIDs.length > 0, dependencies: { body: "body" }, action: filterUninterestingSubforums(uninterestingSubforumIDs), deferUntil: DOMCONTENTLOADED, }), operation({ description: "enable proofreading", condition: () => Preferences.get(P.advanced._.proofread_articles) === Proofreading.Options.ALWAYS, action: () => { // The border must become red before we make it transparent, so we get the nice "flash" effect. window.setTimeout(Proofreading.enable, 10); }, deferUntil: DOMCONTENTLOADED, }), operation({ description: "add proofreading listeners", condition: () => isReadingEditorialContent && Preferences.get(P.advanced._.proofread_articles) === Proofreading.Options.CORRECTIONS, dependencies: { correctionsLink: "#" + SITE.ID.correctionsLink }, action: Proofreading.addListeners, }), operation({ description: "perform proofreading processing", condition: () => ( (isReadingEditorialContent && Preferences.get(P.advanced._.proofread_articles) !== Proofreading.Options.NEVER) || (isInEditMode && Preferences.get(P.advanced._.proofread_forum_posts)) ), action: Proofreading.performProcessing( // Hotfix for #152. isReadingEditorialContent ? [ SELECTOR.bbParagraph ] : [ SELECTOR.bbParagraph, "h1", "h2", "h3" ] ), deferUntil: DOMCONTENTLOADED, }), operation({ description: "replace followed threads link with a link to my posts", condition: () => !isOnBSCPreferencesPage && Preferences.get(P.general._.replace_followed_threads_link), dependencies: { followedThreadsLinkTextOrSigninButton: SELECTOR.signinButtonOr(SELECTOR.followedThreadsLinkText) }, action: replaceFollowedThreadsLink, }), operation({ description: "remember location in market", condition: () => isInEditMode_market && Preferences.get(P.general._.remember_location_in_market), dependencies: { city: SELECTOR.cityInput, region: SELECTOR.regionSelect, saveButton: SELECTOR.saveButton, }, action: rememberLocationInMarket, }), operation({ description: "insert mention everyone button", condition: () => isReadingForumThread && Preferences.get(P.forum_threads._.mention_everyone_button), dependencies: { forumPostContainer: SELECTOR.forumPostContainer, replyButton: SELECTOR.replyButtonAfterForumPosts, quickReplyForm: SELECTOR.quickReplyForm, }, action: insertMentionEveryoneButton, }), operation({ description: "insert draft mode toggle", condition: () => (isInEditMode_forum || isInEditMode_PM) && Preferences.get(P.edit_mode._.draft_mode_toggle), dependencies: { saveButton: SELECTOR.saveButton, previewButton: SELECTOR.previewButton, }, action: insertDraftModeToggle, }), operation({ description: "enable autosave draft watchdog", condition: () => (isInEditMode_forum || isInEditMode_PM) && Preferences.get(P.edit_mode._.autosave_draft), dependencies: { saveButton: SELECTOR.saveButton, textarea: SELECTOR.textarea, toolbarInner: SELECTOR.textareaToolbarInner, }, action: autosaveDraft.manageAutosaveWatchdog(undoSupport), }), operation({ description: "delete any obsolete autosaved draft", condition: () => (mayHaveJustSubmittedForumPost || mayHaveJustSubmittedPM) && Preferences.get(P.edit_mode._.autosave_draft), dependencies: { post: SELECTOR.linkedForumPost }, action: autosaveDraft.clearAutosavedDraftIfObsolete, }), operation({ description: "delete any leftover autosaved draft", condition: () => false === Preferences.get(P.edit_mode._.autosave_draft), action: autosaveDraft.clearAutosavedDraft, }), // Keyboard shortcuts operation({ description: "perform Mousetrap preparations", condition: () => ALWAYS, action: performMousetrapPreparations, deferUntil: DOMCONTENTLOADED, }), operation({ description: "enable Tab key", condition: () => isInEditMode && Preferences.get(P.edit_mode._.insert_tab), dependencies: { textarea: SELECTOR.textarea, }, action: keyboardShortcutsEditMode.insertTab(Preferences.get(P.edit_mode._.insert_tab_content), undoSupport), deferUntil: DOMCONTENTLOADED, }), operation({ description: "add edit mode keyboard shortcut (submit)", condition: () => isInEditMode && Preferences.get(P.edit_mode._.keyboard_shortcuts), dependencies: { textarea: SELECTOR.textarea, saveButton: SELECTOR.saveButton, }, action: keyboardShortcutsEditMode.submit, deferUntil: DOMCONTENTLOADED, }), operation({ description: "add edit mode keyboard shortcut (preview)", condition: () => isInEditMode && !isInEditMode_marketContact && Preferences.get(P.edit_mode._.keyboard_shortcuts), dependencies: { textarea: SELECTOR.textarea, previewButton: SELECTOR.previewButton, }, action: keyboardShortcutsEditMode.preview, deferUntil: DOMCONTENTLOADED, }), operation({ description: "add quick reply keyboard shortcut (submit)", condition: () => isReadingThread && Preferences.get(P.edit_mode._.keyboard_shortcuts_in_quick_reply), dependencies: { textarea: SELECTOR.textarea, saveButton: SELECTOR.saveButtonQuickReply, }, action: keyboardShortcutsEditMode.submit, }), operation({ description: "add quick reply keyboard shortcut (preview)", condition: () => isReadingThread && Preferences.get(P.edit_mode._.keyboard_shortcuts_in_quick_reply), dependencies: { textarea: SELECTOR.textarea, previewButton: SELECTOR.previewButtonQuickReply, }, action: keyboardShortcutsEditMode.preview, }), ]; export default OPERATIONS;
SimonAlling/better-sweclockers
__tests__/utilities.ts
<filename>__tests__/utilities.ts<gh_stars>10-100 // Pure (not in-place) sort function. export function sorted<T>(xs: readonly T[]): T[] { return xs.slice().sort(); }
SimonAlling/better-sweclockers
webpack.config.ts
<filename>webpack.config.ts import * as AppRootPath from "app-root-path"; import { createWebpackConfig, distFileName, DEFAULT_BUILD_CONFIG, DEFAULT_METADATA_SCHEMA, } from "userscripter/build"; import * as webpack from "webpack"; import { RawSource } from "webpack-sources"; import METADATA, { versionBasedOnDate } from "./metadata"; import * as CONFIG from "./src/config"; import PROOFREADING from "./src/lib/proofreading/classes"; import * as SITE from "./src/site"; import * as T from "./src/text"; import U from "./src/userscript"; const now = new Date(); const w = createWebpackConfig({ buildConfig: { ...DEFAULT_BUILD_CONFIG({ rootDir: AppRootPath.path, id: U.id, now: now, }), hostedAt: U.hostedAt, sassVariables: { CONFIG, PROOFREADING, SITE, T }, }, metadata: METADATA, metadataSchema: DEFAULT_METADATA_SCHEMA, env: process.env, }); class VersionPlugin { public apply(compiler: webpack.Compiler) { compiler.hooks.afterCompile.tap( VersionPlugin.name, compilation => { const userscriptAssetName = distFileName(U.id, "user"); const compiledCode: string = compilation.assets[userscriptAssetName]._value; // This doesn't affect metadata at all, only the actual JavaScript: compilation.assets[userscriptAssetName] = new RawSource(compiledCode.replace(U.version, versionBasedOnDate(now))); }, ); } } w.plugins?.push(new VersionPlugin()); export default w;
SimonAlling/better-sweclockers
src/preferences/keyboard.ts
import { ListPreference } from "ts-preferences"; import { Action } from "~src/actions"; import * as T from "~src/text"; export type ShortcutEntry = Readonly<{ shortcut: string, action: Action, }> export default new ListPreference<ShortcutEntry>({ key: "keyboard", label: T.preferences._.NO_LABEL, default: [ { shortcut: "mod+s", action: Action.SUBMIT }, { shortcut: "mod+p", action: Action.PREVIEW }, { shortcut: "tab", action: Action.INSERT_TAB }, ], extras: { implicit: true }, });
SimonAlling/better-sweclockers
src/operations/preferences-menu.tsx
<reponame>SimonAlling/better-sweclockers import { h } from "preact"; import { insertAtTheEnd, renderIn } from "~src/operations/logic/render"; import { PreferencesForm } from "~src/preferences-menu"; import * as SITE from "~src/site"; import * as T from "~src/text"; import { yyyymmdd } from "~src/utilities"; export default () => { document.title = T.preferences._.title; document.documentElement.appendChild((() => { const link = document.createElement("link"); link.rel = "stylesheet"; link.href = SITE.STYLESHEET_URL(yyyymmdd(new Date())); return link; })()); renderIn(document.body, insertAtTheEnd, <PreferencesForm />); };
SimonAlling/better-sweclockers
src/utilities.ts
<filename>src/utilities.ts export const r = String.raw; export function fromMaybeUndefined<T>(fallback: T, x?: T): T { return x === undefined ? fallback : x; } export function truncate(maxTotalLength: number, s: string): string { const REPLACEMENT = "[…]" as const; return ( s.length > maxTotalLength ? s.slice(0, maxTotalLength - REPLACEMENT.length) + REPLACEMENT : s ); } export function withMaybe<A, B>(ma: A | null, f: (x: A) => B): void { if (ma !== null) { f(ma); } } export function yyyymmdd(date: Date): string { const yyyy = date.getFullYear(); const mm = (date.getMonth() + 1 /* 0-indexed */).toString().padStart(2, "0"); const dd = date.getDate().toString().padStart(2, "0"); return yyyy + mm + dd; }
SimonAlling/better-sweclockers
src/operations/autosave-draft.ts
import * as ms from "milliseconds"; import * as Storage from "ts-storage"; import { isNumber, isString } from "ts-type-guards"; import { log } from "userscripter"; import * as CONFIG from "~src/config"; import { insertAtTheEnd, renderIn } from "~src/operations/logic/render"; import { P, Preferences } from "~src/preferences"; import * as SITE from "~src/site"; import * as T from "~src/text"; import { isCleanSlate_reply } from "./edit-mode"; import { generalButton } from "./logic/editing-tools"; import { insertIn } from "./logic/textarea"; /* If the user visits a linked post and tried to submit a post "just now", we will assume it's this one, and delete any autosaved draft. Should be longer than it usually takes to submit a post, but short enough so the user is unlikely to do anything else, or give up waiting, meanwhile. */ const MAX_MILLISECONDS_TO_COUNT_AS_JUST_NOW = 3000; /* If the user visits a linked post that can be determined to have been "recently" created, we will consider it just posted, so we can go ahead and delete any autosaved draft. Should be longer than it usually takes to submit a post, but short enough so the user is unlikely to submit another post meanwhile. */ const MAX_MILLISECONDS_TO_COUNT_AS_RECENTLY = ms.seconds(30); const AUTOSAVE_INTERVAL_SECONDS = 3; const MIN_LENGTH_TO_SAVE = 10; const MAX_LENGTH_TO_SHOW = 200; // when asking if draft should be restored export const manageAutosaveWatchdog = (undoSupport: boolean) => (e: { textarea: HTMLElement, saveButton: HTMLElement, toolbarInner: HTMLElement, }) => { const textarea = e.textarea as HTMLTextAreaElement; // If the user came here by previewing their post, there is nothing saved at this point, because we cleared the draft when they deliberately unloaded the page. maybeOfferToRestoreAutosavedPost(textarea, e.toolbarInner, undoSupport); // Now that we have inserted the restore button or decided not to, we can start autosaving the text in the textarea. enableWatchdog(textarea); e.saveButton.addEventListener("click", () => { const nowInMilliseconds = Date.now(); Storage.set_session(CONFIG.KEY.last_time_user_tried_to_submit, nowInMilliseconds); }); }; export function clearAutosavedDraftIfObsolete(e: { post: HTMLElement }) { const result = draftIsObsolete(e.post); if (isString(result)) { return result; } else if (result === true) { log.log(`Deleting autosaved draft because the post seems to have been successfully submitted.`); clearAutosavedDraft(); } } export function clearAutosavedDraft() { Storage.remove(CONFIG.KEY.autosaved_draft); } function enableWatchdog(textarea: HTMLTextAreaElement) { // Save immediately, regularly and when page is unloaded: saveDraft(textarea); setInterval(() => saveDraft(textarea), ms.seconds(AUTOSAVE_INTERVAL_SECONDS)); window.addEventListener("beforeunload", () => saveDraft(textarea)); if (Preferences.get(P.advanced._.prevent_accidental_unload)) { // Assuming it works correctly, prevent accidental unload should be enough protection against misclicks. // If the user has confirmed that they want to unload the page, we should consider their saved draft obsolete by virtue of that decision. window.addEventListener("unload", clearAutosavedDraft); } } function saveDraft(textarea: HTMLTextAreaElement): void { const text = textarea.value; if (mayBeWorthSaving(text)) { // Trim because SweClockers does: const response = Storage.set(CONFIG.KEY.autosaved_draft, text.trim()); if (response.status === Storage.Status.STORAGE_ERROR) { log.error(`Could not save draft.`); } } else { clearAutosavedDraft(); } } function mayBeWorthSaving(text: string): boolean { return text.length >= MIN_LENGTH_TO_SAVE && !isCleanSlate_reply(text); } function maybeOfferToRestoreAutosavedPost(textarea: HTMLTextAreaElement, toolbarInner: HTMLElement, undoSupport: boolean) { const saved = Storage.get(CONFIG.KEY.autosaved_draft, ""); if (saved.status === Storage.Status.OK && textarea.value !== saved.value) { // There is a saved draft that the user might want to restore. const button = generalButton({ label: T.general.restore_draft_label, tooltip: T.general.restore_draft_tooltip, class: CONFIG.CLASS.button_restoreDraft, action: (textarea, undoSupport) => { const draftPreview = shortenedIfLongerThan(MAX_LENGTH_TO_SHOW, saved.value); const question_restore = T.general.restore_draft_question + "\n\n" + draftPreview; if (confirm(question_restore)) { // Avoid overwriting current textarea content in the absence of undo support: if (undoSupport || textarea.value === "" || confirm(T.general.restore_draft_confirm)) { // `confirm` is problematic in Chrome (see docs/dialogs.md), but Chrome has full undo support. textarea.select(); insertIn(textarea, { string: saved.value, replace: true }); // Not replacing would be confusing. Firefox users are protected by the confirmation dialog above. removeRestoreButton(); } } }, }); renderIn(toolbarInner, insertAtTheEnd, button(textarea, undoSupport)); } } function removeRestoreButton() { // A bit ugly, but it does the trick. const buttons = Array.from(document.getElementsByClassName(CONFIG.CLASS.button_restoreDraft)); for (const button of buttons) button.remove(); } function draftIsObsolete(post: HTMLElement): boolean | string { // Check if user came from any page at all: if (document.referrer === "") return false; // For subsequent checks, first check if authored by user: if (!post.classList.contains(SITE.CLASS.forumPostByCurrentUser)) return false; const referrerPath = new URL(document.referrer).pathname; const nowInMilliseconds = Date.now(); // Check if user tried to submit a post just now: const lastTimeUserTriedToSubmit = Storage.get_session(CONFIG.KEY.last_time_user_tried_to_submit, 0).value; const attemptedSubmitJustNow = nowInMilliseconds < lastTimeUserTriedToSubmit + MAX_MILLISECONDS_TO_COUNT_AS_JUST_NOW; if (attemptedSubmitJustNow) return true; // Check if recently created: const creationTimeInSeconds = getCreationTimeInSeconds(post); if (creationTimeInSeconds === null) return couldNotDetermine("created"); const postCreatedRecently = nowInMilliseconds < ms.seconds(creationTimeInSeconds) + MAX_MILLISECONDS_TO_COUNT_AS_RECENTLY; const cameFromEditMode = SITE.PATH.EDIT_MODE_FORUM.test(referrerPath); // assuming user came from within SweClockers if (cameFromEditMode && postCreatedRecently) return true; // Was not recently created; check if just edited: const matchPostID = post.id.match(/\d{7,}/); // all post IDs back to at least 2002 if (matchPostID === null) return couldNotDetermine("edited"); const postID = parseInt(matchPostID[0]); const cameFromEditingThisPost = referrerPath === SITE.PATH.editPost(postID); // assuming user came from within SweClockers const attemptedSubmitRecently = nowInMilliseconds < lastTimeUserTriedToSubmit + MAX_MILLISECONDS_TO_COUNT_AS_RECENTLY; if (cameFromEditingThisPost && attemptedSubmitRecently) return true; // As far as we can tell, any saved draft may still be relevant. return false; } function couldNotDetermine(kind: "created" | "edited"): string { return `Could not determine if post was just ${kind}.`; } function getCreationTimeInSeconds(post: HTMLElement): number /* UTC */ | null { try { const parseResult = JSON.parse(post.dataset.post || "").createTime; return isNumber(parseResult) ? parseResult : null; } catch (_) { return null; } } /* (4, "abcd") => "abcd" (4, "abcde") => "ab\n[…]\nde" (5, "abcde") => "abcde" (5, "abcdef") => "ab\n[…]\ndef" */ function shortenedIfLongerThan(max: number, s: string): string { return ( s.length <= max ? s : s.substr(0, max/2) + "\n[…]\n" + s.substr(s.length - max/2) ); }
SimonAlling/better-sweclockers
src/preferences/dark-theme.ts
import * as ms from "milliseconds"; import { BooleanPreference, IntegerRangePreference, } from "ts-preferences"; import * as CONFIG from "~src/config"; import * as T from "~src/text"; import { TimePreference } from "./TimePreference"; const auto = new BooleanPreference({ key: "dark_theme_auto", default: true, label: T.preferences.dark_theme.auto, description: T.preferences.dark_theme.auto_description, extras: { class: [ CONFIG.CLASS.inlinePreference, CONFIG.CLASS.primaryInlinePreference ] }, }); const dependencies_auto = [ { preference: auto, condition: (v: boolean) => v, }, ]; export default { active: new BooleanPreference({ key: "dark_theme_active", default: false, label: T.preferences._.NO_LABEL, extras: { implicit: true }, }), last_autoset_state: new BooleanPreference({ key: "dark_theme_last_autoset_state", default: false, label: T.preferences._.NO_LABEL, extras: { implicit: true }, }), show_toggle: new BooleanPreference({ key: "dark_theme_show_toggle", default: true, label: T.preferences.dark_theme.show_toggle, description: T.preferences.dark_theme.show_toggle_description, }), auto, time_on: new TimePreference({ key: "dark_theme_time_on", default: ms.hours(21), label: T.preferences.dark_theme.between, description: T.preferences.dark_theme.auto_description, min: 0, max: ms.days(1), dependencies: dependencies_auto, extras: { class: CONFIG.CLASS.inlinePreference }, }), time_off: new TimePreference({ key: "dark_theme_time_off", default: ms.hours(7), label: T.preferences.dark_theme.and, description: T.preferences.dark_theme.auto_description, min: 0, max: ms.days(1), dependencies: dependencies_auto, extras: { class: CONFIG.CLASS.inlinePreference }, }), interval: new IntegerRangePreference({ key: "dark_theme_interval", default: 10, label: T.preferences.dark_theme.interval, description: T.preferences.dark_theme.interval_description, min: 1, max: 600, extras: { suffix: T.general.seconds }, }), } as const;
SimonAlling/better-sweclockers
src/text.ts
// This file cannot contain Webpack-resolved imports (e.g. "~src/foo"). import * as BB from "bbcode-tags"; import * as browser from "./browser"; import * as CONFIG from "./config"; import * as SITE from "./site"; import { InsertButtonDescription } from "./types"; function genitive(name: string): string { return ["s", "x", "z"].some(letter => name.endsWith(letter)) ? name : name + "s"; } function darkThemeBy(author: string): string { return `${genitive(author)} mörka tema`; } const mention_everyone_label = `Nämn alla`; const my_posts = `Mina inlägg`; const down_for_maintenance = `Nere för underhåll`; const draft_mode_toggle_label = `Utkast`; const draft_mode_description = `Slipp posta ofärdiga inlägg av misstag`; const OBVIOUS = `Som det låter`; export const general = { seconds: `sekunder`, loading: `Laddar …`, dark_theme_toggle_tooltip: (author: string) => `${darkThemeBy(author)} på/av`, preferences_link: CONFIG.USERSCRIPT_NAME, signout_confirmation: `Är du säker på att du vill logga ut?`, draft_mode_toggle_label, draft_mode_toggle_tooltip: draft_mode_description, draft_mode_enabled_tooltip: `Kryssa ur "${draft_mode_toggle_label}" för att posta`, improved_url_button_url: `Adress (URL):`, improved_url_button_text: `Länktext:`, restore_draft_label: `Återställ`, restore_draft_tooltip: `Återställ autosparat utkast`, restore_draft_question: `Vill du återställa följande utkast?`, restore_draft_confirm: `Din nuvarande text kommer ersättas. Är du säker?`, nbsps_confirm: (n: number) => `${n} mellanslag kommer ersättas med hårda mellanslag. Är du säker?`, generic_lines_confirm: (n: number) => `${n} markerad${n > 1 ? "e rader" : " rad"} kommer formateras. Är du säker?`, quote_signature_label: `Citera med sign.`, quote_signature_tooltip: `Citera inlägget och dess signatur`, quote_signature_tooltip_no_signature: (author: string) => `${author} har ingen signatur`, mention_everyone_label, mention_everyone_tooltip: `Nämn alla tråddeltagare på den här sidan i ett nytt inlägg`, uninteresting_subforum: (subforumName: string) => `Du har markerat kategorin ${subforumName} som ointressant.`, pm_link_label: "&nbsp;PM", go_to_post: `Gå till inlägget`, link_to_top_tooltip: `Gå till toppen`, textarea_size_small: `Liten textruta`, textarea_size_large: `Stor textruta`, tooltip_h: `Rubrik`, tooltip_table: `Tabell`, down_for_maintenance, my_posts, } as const; export const preferences = { _: { NO_LABEL: ``, shortcut_label: `BSC`, title: `Inställningar för Better SweClockers`, back_to_sweclockers: `Tillbaka till ${SITE.NAME}`, save_notice: `Inställningarna sparas automatiskt, men endast lokalt på den här enheten.`, failed_to_fetch_categories: `Kunde inte hämta forumkategorier.`, in_quick_reply_form: `i formuläret <em>Snabbsvar</em>`, in_quick_reply_form_description: `Längst ner i trådar`, }, general: { label: `Allmänt`, lock_heights: `Lås höjden på reklam etc`, lock_heights_description: `Förhindrar att sidans innehåll hoppar när t ex reklam laddas in`, improved_corrections: `Bättre rättelsegränssnitt`, improved_corrections_description: `Gör det enklare att skicka in rättelser`, insert_preferences_shortcut: `Genväg till inställningar för ${CONFIG.USERSCRIPT_NAME}`, insert_preferences_shortcut_description: `Visa en länk till ${CONFIG.USERSCRIPT_NAME} inställningsmeny högst upp`, replace_followed_threads_link: `Ersätt länken <em>Följda trådar</em> med <em>${my_posts}</em>`, replace_followed_threads_link_description: OBVIOUS, remember_location_in_market: `Kom ihåg min plats i marknaden`, remember_location_in_market_description: `Slipp fylla i län och stad varje gång du skapar en annons`, }, forum_threads: { label: `Forumtrådar`, improved_pagination_buttons: `Bättre bläddringsknappar`, improved_pagination_buttons_description: `Större knappar som är lättare att klicka på`, insert_link_to_top: `Länk till toppen längst ner`, insert_link_to_top_description: OBVIOUS, highlight_own_posts: `Framhäv egna inlägg extra tydligt`, highlight_own_posts_description: `Gör den orangea kanten på egna inlägg tjockare`, insert_pm_links: `PM-knappar`, insert_pm_links_description: `Skicka PM till en användare direkt från deras inlägg`, mention_everyone_button: `<em>${mention_everyone_label}</em>-knapp`, mention_everyone_button_description: `Nämn alla tråddeltagare på den aktuella sidan (framförallt användbart i annonskommentarer)`, quote_signature_buttons: `<em>Citera med signatur</em>-knappar`, quote_signature_buttons_description: `Citera ett inlägg inklusive dess signatur`, quote_signature_message: `Meddelande vid citering med signatur`, quote_signature_message_description: `Fylls i automatiskt när du citerar med signatur`, quote_signature_message_default: `Nu består trådens värde även när du byter signatur.`, }, edit_mode: { label: `Redigeringsläge`, autosave_draft: `Spara utkast automatiskt`, autosave_draft_description: `Skydda dina inlägg mot blåskärmar, strömavbrott och andra missöden`, draft_mode_toggle: `Kryssrutan <em>${draft_mode_toggle_label}</em>`, draft_mode_toggle_description: draft_mode_description, textarea_size_save: `Kom ihåg textrutans storlek`, textarea_size_save_description: `Behåll samma storlek på textrutan mellan sidladdningar`, textarea_size_toggle: `Knappar för att växla storlek på textrutan`, textarea_size_toggle_description: `Toggla textrutans storlek precis ovanför den`, textarea_size_small: `mellan`, textarea_size_large: `och`, textarea_size_unit: `px`, monospace_font: `<span style="font-family: monospace">Monospace</span>-font i textrutan`, monospace_font_description: `Underlättar formatering av kod och dylikt`, keyboard_shortcuts: `Kortkommandon för att skicka (<kbd>Ctrl</kbd> + <kbd>S</kbd>) och förhandsgranska (<kbd>Ctrl</kbd> + <kbd>P</kbd>)`, keyboard_shortcuts_description: `Skicka och förhandsgranska med tangentbordet`, insert_tab: `Tab-tangenten infogar`, insert_tab_description: `Använd Tab-tangenten i textrutan`, insert_tab_spaces: (n: number) => `${n} blanksteg`, insert_tab_tab: `tabbtecken`, improved_builtin_editing_tools: `Förbättrade inbyggda redigeringsverktyg`, improved_builtin_editing_tools_description: `Mer intuitiv funktionalitet och ångra-stöd (i webbläsare som stöder det)`, insert_heading_toolbar_button: `Knapp för att formatera som rubrik`, insert_heading_toolbar_button_description: `Knappen infogar BB-taggen ${BB.start(SITE.TAG.h)}`, insert_table_toolbar_button: `Knapp för att infoga tabell`, insert_table_toolbar_button_description: `Knappen infogar en komplett tabell`, remember_caret_position: `Kom ihåg markörens position vid förhandsgranskning`, remember_caret_position_description: `Fortsätt skriva precis där du var när du förhandsgranskat ett inlägg`, remove_mobile_site_disclaimer: `Ta bort <small><em>${SITE.MOBILE_SITE_DISCLAIMER.sentFrom} ${SITE.MOBILE_SITE_DISCLAIMER.mobileSiteDomain}</em></small>`, remove_mobile_site_disclaimer_description: `Ta automatiskt bort ${SITE.MOBILE_SITE_DISCLAIMER.mobileSiteDomain}-disclaimern från citat`, }, editing_tools: { label: `Utökade formateringsverktyg`, enable: `Aktivera utökade formateringsverktyg`, enable_description: `En hel samling extra formateringsverktyg för att underlätta inläggsskrivandet`, position: { label: `Placering`, description: OBVIOUS, above: `Ovanför textfältet`, below: `Under textfältet`, }, special_characters: `Verktyg för specialtecken`, meta: `Verktyg för tillagd och borttagen text`, code: `Kodrelaterade verktyg`, math: `Matematikrelaterade verktyg`, whitespace: `Whitespaceverktyg`, definitions: `Verktyg för definitioner`, embed: `Verktyg för länkar, bilder och sökresultat`, search_engine: { label: `Sökmotor`, description: `Vilken sökmotor som ska användas för länkar till sökresultat`, }, doge: `very doge buttons`, doge_description: ` wow`, color_palette: `Färgpaletten`, color_palette_description: `Ändra textfärg snabbt och enkelt`, smileys: `Smileys`, }, dark_theme: { label: (author: string, infoUrl: string) => `${darkThemeBy(author)} (<a target="_blank" href="${infoUrl}">forumtråd</a>)`, show_toggle: `Manuell aktivering`, show_toggle_description: `Toggla manuellt det mörka temat med en ikon högst upp på sidan`, auto: `Automatisk aktivering`, auto_description: `Aktivera det mörka temat automatiskt under nattens timmar`, between: `mellan`, and: `och`, interval: `Uppdateringsintervall`, interval_description: `Hur ofta ${CONFIG.USERSCRIPT_NAME} ska kolla vad klockan är`, }, customize_content: { label: `Anpassa innehåll`, carousel: `Bildspelsvyn högst upp`, social_media: `Knappar för sociala medier`, guides: `Guider`, popular_galleries: `Bubblare i Galleriet`, new_in_forum_side: `Nytt i forumet (till höger)`, new_in_market: `Senaste privatannonserna`, new_in_test_lab: `Nytt i testlabbet`, in_the_store: `Just nu i butiken`, popular_at_prisjakt: `Populärast på Prisjakt`, new_tech_jobs: `Nya teknikjobb`, external_news: `Externa nyheter`, more_articles: `Fler artiklar (under varje artikel)`, latest_news: `Senaste nyheterna (längst ner)`, new_in_forum_main: `Nytt i forumet (längst ner)`, footer: `Sidfot`, }, advanced: { label: `Avancerat`, prevent_accidental_signout: `Fråga vid utloggning`, prevent_accidental_signout_description: `Undvik att logga ut av misstag`, prevent_accidental_unload: `Fråga vid navigering från redigeringsläge`, prevent_accidental_unload_description: `Värdefullt om du råkar klicka på fel länk mitt i ett inlägg`, improved_image_controls: `Bättre zoom- och länkikoner i bilder`, improved_image_controls_description: `Visa ikoner framför bilder endast när du hovrar över dem`, disable_scroll_restoration: `Förhindra webbläsaren från att komma ihåg scrollning`, disable_scroll_restoration_description: `Kan vara praktiskt för tangentbordssurfare`, down_for_maintenance: `${down_for_maintenance} varje natt mellan 4:30 och 5:10`, down_for_maintenance_description: `Never forget!`, proofread_articles: { label: `Markera möjliga fel i artiklar`, description: `Exempelvis hårda mellanslag och tankstreck`, always: `Alltid`, corrections: `I rättelsegränssnittet`, never: `Aldrig`, }, proofread_forum_posts: `Markera möjliga fel i foruminlägg (i redigeringsläge)`, proofread_forum_posts_description: `Samma som ovan, fast i forumet`, undo_support: (browser.supportsUndo, { // Make sure the labels match the actual support check (referenced here to facilitate a `git grep` search). label: `När ett verktyg infogar text`, description: `Om din webbläsare inte låter dig ångra åtgärder utförda med redigeringsverktygen kan ${CONFIG.USERSCRIPT_NAME} skydda markerad text mot oavsiktlig radering om du råkar trycka på fel knapp`, replace_selected: `Ersätt markerad text – rekommenderas i alla webbläsare med fullgott ångra-stöd`, keep_selected: `Behåll markerad text – rekommenderas i <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1220696">Firefox/Gecko</a> samt på Android`, // Make sure the text matches the actual support check. }), developer_mode: `Utvecklarläge`, developer_mode_description: `Visa fel och varningar längst ner på skärmen`, custom_css_enable: `Infoga egen CSS:`, custom_css_enable_description: `Anpassa layout och utseende precis som du vill`, custom_css_warning: `Klistra aldrig in kod som du inte litar på!`, }, keyboard: `Kortkommandon`, interests: { label: `Intressen`, }, } as const; export const editing_tools = { size_label: `<big>A</big><small>A</small>`, size_tooltip: `Textstorlek`, color_tooltip: `Textfärg`, font_tooltip: `Typsnitt`, mark_label: `<mark>mark</mark>`, mark_tooltip: `Markerad/framhävd text`, abbr_label: SITE.TAG.abbr, abbr_tooltip: `Förkortning`, quote_tooltip: `Forumcitat`, bq_label: `bq`, bq_tooltip: `Allmänt blockcitat`, spoiler_tooltip: `Spoilers`, expander_tooltip: `Långa textstycken`, noparse_tooltip: `Inaktivera BB-kod i en viss del av texten`, pre_tooltip: `Visa indrag och mellanrum som de är`, cmd_tooltip: `Inlinekod`, code_tooltip: `Kodstycke`, math_label: `<big><i>x</i></big>`, math_tooltip: `Matematiska formler och uttryck`, sub_label: `<span>⬚</span><sub><i>x</i></sub>`, sub_tooltip: `Nedsänkt text`, sup_label: `<span>⬚</span><sup><i>x</i></sup>`, sup_tooltip: `Upphöjd text`, nbsps_label: `␣`, nbsps_tooltip: `Ersätt alla mellanslag med hårda mellanslag i markerad text`, url_tooltip: `Klickbar länk`, img_tooltip: `Bädda in bilder`, search_link_tooltip: `Länka till en sökning på markerad text`, shibe_label: `shibe`, shibe_tooltip: `wow`, doge_label: `doge`, doge_tooltip: `pls click`, split_quote_tooltip: `Splitta ett citat mitt i`, edit_label: `Edit`, edit_tooltip: `Infoga en redigeringsnotis`, ins_label: `<ins class="${SITE.CLASS.bbIns}">${SITE.TAG.ins}</ins>`, ins_tooltip: `Tillagd text`, del_label: `<del class="${SITE.CLASS.bbDel}">${SITE.TAG.del}</del>`, del_tooltip: `Borttagen text`, dl_label: SITE.TAG.dl, dl_tooltip: `Definitionslista`, dt_label: SITE.TAG.dt, dt_tooltip: `Term att definiera/beskriva (måste ligga inuti en ${BB.start(SITE.TAG.dl)})`, dd_label: SITE.TAG.dd, dd_tooltip: `Termens definition/beskrivning (måste ligga inuti en ${BB.start(SITE.TAG.dl)} och efter en ${BB.start(SITE.TAG.dt)})`, } as const; export const special_characters: readonly InsertButtonDescription[] = [ { insert: "\u2011", tooltip: "Hårt bindestreck (tillåter ej radbrytning)" }, { insert: "–", tooltip: "Kort tankstreck (talstreck; intervall)" }, { insert: "—", tooltip: "Långt tankstreck" }, { insert: "…", tooltip: "Uteslutningstecken (Ellipsis)" }, { insert: "≈", tooltip: "Ungefär lika med" }, { insert: "−", tooltip: "Minustecken" }, { insert: "×", tooltip: "Multiplikationstecken" }, { insert: "·", tooltip: "Halvhög punkt (multiplikationstecken)" }, { insert: "°", tooltip: "Gradtecken" }, { insert: "\u202F°C", tooltip: "Grader celsius (inkl. hårt blanksteg)" }, { insert: CONFIG.NBSP, label: "NBSP", tooltip: "Hårt blanksteg (tillåter ej radbrytning)" }, { insert: "\u202F", label: "NNBSP", tooltip: "Smalt hårt blanksteg (tillåter ej radbrytning, används som enhets- och tusentalsseparator)" }, { insert: "²", tooltip: "Upphöjd tvåa" }, { insert: "′", tooltip: "Primtecken (fot; minuter)" }, { insert: "″", tooltip: "Dubbelprimtecken (tum; sekunder)" }, { insert: "✓", tooltip: "Bock" }, { insert: "→", tooltip: "Högerpil" }, { insert: "™", tooltip: "Varumärke (trademark)" }, ]; export const developer_mode = { nothing_logged: `Nothing has been logged.`, tooltip: { error: (n: number) => `${n} fel`, warning: (n: number) => `${n} varning${n === 1 ? "" : "ar"}`, }, } as const;
SimonAlling/better-sweclockers
src/operations/logic/render.ts
import { JSX, render } from "preact"; import { isString } from "ts-type-guards"; import { log } from "userscripter"; import { truncate } from "~src/utilities"; /** * A function assumed to insert `placeholder` in `parent`. */ type InsertIn<Parent extends Element> = ( /* This type has an object parameter instead of two plain parameters because otherwise it would be easy to accidentally pass something that's not an actual insertion function. In particular, one could accidentally pass `insertBefore` instead of `insertBefore(reference)` and get no type error. It's still possible to pass something stupid like `console.log` or `() => {}`, but that's hard to prevent and not very likely anyway. We could have parameterized over the type of `placeholder` and required that the return type be that type, but then one might be tempted to pass something like `({ placeholder }) => placeholder`. Using `void` makes it obvious that the function should have at least some side effect. */ (_: { parent: Parent, placeholder: Text }) => void ) type Insert = InsertIn<Element> /** * Renders a virtual node at a specific position in a parent element. * @param parent The element to render inside. * @param insert A function describing where in the parent element the rendered element should be inserted. It will be given `{ parent, placeholder }` and will be assumed to actually insert `placeholder` directly under `parent`. * @param vnode The virtual node to render. */ export function renderIn<Parent extends Element>( parent: Parent, insert: InsertIn<Parent>, vnode: JSX.Element, ): void { const placeholder = document.createTextNode(""); // Doesn't matter what type of node we use here, because it will be replaced by the rendered element. insert({ parent, placeholder }); if (placeholder.parentNode === parent) { // "If the optional replaceNode parameter is provided, it must be a child of containerNode." https://preactjs.com/guide/v10/api-reference/ render(vnode, parent, placeholder); } else { const nodeType = isString(vnode.type) ? ` "${vnode.type}"` : ""; // Cluttered message if it's not a string. const nodeProps = truncate(200, JSON.stringify(vnode.props)); // Cluttered message if it's too long. log.error(`Placeholder for virtual${nodeType} node with properties\n\n ${nodeProps}\n\nwas not inserted directly under the intended parent element.`); } } export const insertAtTheEnd: Insert = ( ({ parent, placeholder }) => { parent.append(placeholder); } ); export const insertAtTheBeginning: Insert = ( ({ parent, placeholder }) => { parent.prepend(placeholder); } ); export const insertBefore: (reference: Node) => Insert = ( reference => ({ parent, placeholder }) => { parent.insertBefore(placeholder, reference); } ); export const insertAfter: (reference: Node) => Insert = ( reference => ({ parent, placeholder }) => { parent.insertBefore(placeholder, reference.nextSibling); // If reference.nextSibling is null, reference is the last child and placeholder will be inserted after it. } );
SimonAlling/better-sweclockers
src/operations/preferences-shortcut.tsx
<reponame>SimonAlling/better-sweclockers import { h } from "preact"; import * as CONFIG from "~src/config"; import { insertAtTheBeginning, renderIn } from "~src/operations/logic/render"; import * as SITE from "~src/site"; import * as T from "~src/text"; export default (e: { notificationsBar: HTMLElement, }) => { renderIn(e.notificationsBar, insertAtTheBeginning, ( // Derived from the other links in the notifications bar. <a href={CONFIG.PATH.PREFERENCES.link(SITE.PATH.SETTINGS.link)} title={T.preferences._.title} class="margin-medium-right" > <svg class="icon" dangerouslySetInnerHTML={{ __html: SITE.ICONS.settings }} /> <span class="margin-small-left display-none display-l-inherit"> {T.preferences._.shortcut_label} </span> </a> )); };
SimonAlling/better-sweclockers
src/search-engines.ts
export const enum SearchEngine { // Be careful! These strings are used in the UI. GOOGLE = "Google", DUCKDUCKGO = "DuckDuckGo", } function searchEngineURL(engine: SearchEngine): string { switch (engine) { case SearchEngine.GOOGLE: return "https://google.com/search?q="; case SearchEngine.DUCKDUCKGO: return "https://duckduckgo.com/?q="; } } export function searchURL(engine: SearchEngine, completePhrase: string): string { return searchEngineURL(engine) + completePhrase.trim().replace(/\s+/g, "+"); }
SimonAlling/better-sweclockers
src/lib/proofreading/index.ts
import { RULES, RULES_SUP, PATTERN_DOPPELGANGERS } from "@alling/sweclockers-writing-rules"; import { compose } from "@typed/compose"; import { proofreadWith, highlightWith } from "highlight-mistakes"; import C from "./classes"; type StringTransformer = (s: string) => string; export function processNodeWith(f: StringTransformer, sup: StringTransformer): (node: Node) => void { return node => { if (node.nodeType === Node.TEXT_NODE) { const span = document.createElement("span"); span.innerHTML = f(escapeHTML(node.textContent || "")); (node.parentNode as Node).replaceChild(span, node); } else if (node.nodeType === Node.ELEMENT_NODE) { if (node.nodeName === "SUP") { (node as HTMLElement).innerHTML = sup(node.textContent || ""); } else { Array.from(node.childNodes).forEach(processNodeWith(f, sup)); } } }; } export function markWith(className: string): (info: string | null) => StringTransformer { const isMistake = className === C.mistake; return info => s => [ `<span class="${C.proofread} ${className}"`, (isMistake && info !== null ? ` title="Förslag: ${info}"` : ""), `>${s}</span>`, ].join(""); } export const processSup = proofreadWith({ rules: RULES_SUP, markMistake: markWith(C.mistake), markVerified: markWith(C.verified), }); export const processText = compose( highlightWith({ pattern: PATTERN_DOPPELGANGERS, mark: markWith(C.any)(null), }), proofreadWith({ rules: RULES, markMistake: markWith(C.mistake), markVerified: markWith(C.verified), }), ); export const processNode = processNodeWith(processText, processSup); function replacer(found: `&` | `<` | `>` | `"` | `'`): string { switch (found) { case `&`: return "&amp;"; case `<`: return "&lt;"; case `>`: return "&gt;"; case `"`: return "&quot;"; case `'`: return "&#039;"; // https://stackoverflow.com/questions/2083754 } } function escapeHTML(html: string): string { return html.replace(/[&<>"']/g, replacer as (substring: string) => string); }
SimonAlling/better-sweclockers
src/operations/developer-mode.tsx
import { Component, h, JSX, render } from "preact"; import * as Storage from "ts-storage"; import { log } from "userscripter"; import * as CONFIG from "~src/config"; import * as T from "~src/text"; export function logger(regularLogger: log.Logger, rootNode: Element): log.Logger { const initOpen = Storage.get_session(CONFIG.KEY.developer_tools_open, false).value; let devTools: DevTools; render(<DevTools initOpen={initOpen} ref={self => { devTools = self; }} />, rootNode); return { ...regularLogger, error: (prefix: string, message: string) => { devTools.log({ kind: "error", content: message }); regularLogger.error(prefix, message); }, warn: (prefix: string, message: string) => { devTools.log({ kind: "warning", content: message }); regularLogger.warn(prefix, message); }, }; } type Kind = "error" | "warning" type Message = { kind: Kind content: string } type DevToolsProps = { initOpen: boolean } type DevToolsState = { loggedMessages: readonly Message[] isOpen: boolean } class DevTools extends Component<DevToolsProps, DevToolsState> { constructor(props: DevToolsProps) { super(props); this.state = { loggedMessages: [], isOpen: props.initOpen, }; } public log(message: Message) { this.setState(state => ({ loggedMessages: [ ...state.loggedMessages, message ], })); } render() { const loggedMessages = this.state.loggedMessages; const loggedWarnings = loggedMessages.filter(msg => msg.kind === "warning"); const loggedErrors = loggedMessages.filter(msg => msg.kind === "error"); return ( <footer id={CONFIG.ID.developerTools} class={this.state.isOpen ? "open" : undefined} data-how-many={loggedMessages.length}> <a onClick={_ => { this.setState(state => { const newOpenState = !state.isOpen; Storage.set_session(CONFIG.KEY.developer_tools_open, newOpenState); return { ...state, isOpen: newOpenState }; }); }}> {summary(loggedErrors.length, "error")} {summary(loggedWarnings.length, "warning")} </a> <ol> { loggedMessages.length > 0 ? loggedMessages.map(msg => <li class={CONFIG.CLASS.developerTools[msg.kind]}>{msg.content}</li>) : <li>{T.developer_mode.nothing_logged}</li> } </ol> </footer> ); } } function summary(howMany: number, what: Kind): JSX.Element { const icon = ({ error: "❌", warning: "⚠️", } as const)[what]; return ( <strong data-how-many={howMany} class={CONFIG.CLASS.developerTools[what]} title={T.developer_mode.tooltip[what](howMany)}> {icon}&nbsp;&nbsp;{howMany} </strong> ); }
SimonAlling/better-sweclockers
src/operations/remember-location-in-market.ts
<filename>src/operations/remember-location-in-market.ts import { isString } from "ts-type-guards"; import { log } from "userscripter"; import { P, Preferences } from "~src/preferences"; export default (e: { city: HTMLElement, region: HTMLElement, saveButton: HTMLElement, }) => { const cityInput = e.city as HTMLInputElement; const regionSelect = e.region as HTMLSelectElement; if (cityInput.value === "") { cityInput.value = Preferences.get(P.general._.location_city); } if (regionSelect.selectedIndex === 0) { // no actual selection regionSelect.value = Preferences.get(P.general._.location_region).toString(); } e.saveButton.addEventListener("click", () => { Preferences.set(P.general._.location_city, cityInput.value); const parseResult = P.general._.location_region.fromString(regionSelect.value); if (isString(parseResult)) { log.error(parseResult); } else { Preferences.set(P.general._.location_region, parseResult.value); } }); };
SimonAlling/better-sweclockers
src/preferences.ts
<gh_stars>10-100 import { PreferenceManager } from "ts-preferences"; import { loggingResponseHandler, subscriptable } from "userscripter/lib/preferences"; import * as CONFIG from "~src/config"; import * as darkTheme from "~src/dark-theme"; import * as T from "~src/text"; import U from "~src/userscript"; import advancedPreferences from "./preferences/advanced"; import customizeContentPreferences from "./preferences/customize-content"; import darkThemePreferences from "./preferences/dark-theme"; import editModePreferences from "./preferences/edit-mode"; import editingToolsPreferences from "./preferences/editing-tools"; import forumThreadsPreferences from "./preferences/forum-threads"; import generalPreferences from "./preferences/general"; import interestsPreferences from "./preferences/interests"; import keyboardPreferences from "./preferences/keyboard"; export const P = { general: { label: T.preferences.general.label, _: generalPreferences, }, forum_threads: { label: T.preferences.forum_threads.label, _: forumThreadsPreferences, }, edit_mode: { label: T.preferences.edit_mode.label, _: editModePreferences, }, editing_tools: { label: T.preferences.editing_tools.label, _: editingToolsPreferences, extras: { id: CONFIG.ID.editingToolsPreferences }, }, dark_theme: { label: T.preferences.dark_theme.label(darkTheme.AUTHOR, darkTheme.URL.info), _: darkThemePreferences, }, advanced: { label: T.preferences.advanced.label, _: advancedPreferences, }, customize_content: { label: T.preferences.customize_content.label, _: customizeContentPreferences, }, keyboard: keyboardPreferences, interests: { label: T.preferences.interests.label, _: interestsPreferences, }, } as const; export const responseHandler = subscriptable(loggingResponseHandler); export const Preferences = new PreferenceManager(P, U.id + "-preference-", responseHandler.handler);
SimonAlling/better-sweclockers
src/operations/dark-theme.tsx
<gh_stars>10-100 import * as ms from "milliseconds"; import { h } from "preact"; import { isNull } from "ts-type-guards"; import { disable } from "userscripter/lib/stylesheets"; import * as CONFIG from "~src/config"; import * as darkTheme from "~src/dark-theme"; import iconDarkThemeToggle from "~src/icons/dark-theme-toggle.svg"; import { insertAfter, renderIn } from "~src/operations/logic/render"; import { P, Preferences } from "~src/preferences"; import STYLESHEETS from "~src/stylesheets"; import * as T from "~src/text"; import { timeIsWithin } from "~src/time"; import { withMaybe } from "~src/utilities"; export function insertToggle(e: { menuLockToggle: HTMLElement, }) { renderIn(e.menuLockToggle.parentElement as Element, insertAfter(e.menuLockToggle), ( // Derived from the menu lock toggle. <li class="menu-lock menu-lock-active"> <div class="menu-lock-click" title={T.general.dark_theme_toggle_tooltip(darkTheme.AUTHOR)} onClick={() => set(!Preferences.get(P.dark_theme._.active))} /> <span class="menu-lock"> <svg class="icon" dangerouslySetInnerHTML={{ __html: iconDarkThemeToggle }} /> </span> </li> )); disable(STYLESHEETS.dark_theme_toggle_preparations); } export function manage(): void { if (Preferences.get(P.dark_theme._.active)) { apply(true); } if (Preferences.get(P.dark_theme._.auto)) { sheldon(); setInterval(sheldon, ms.seconds(Preferences.get(P.dark_theme._.interval))); } } function apply(newState: boolean): void { const url = withCacheInvalidation(darkTheme.URL.stylesheet, new Date()); if (newState) { if (isNull(document.getElementById(CONFIG.ID.darkThemeStylesheet))) { // Not document.head because it can be null, e.g. in a background tab in Firefox: const link = document.createElement("link"); link.rel = "stylesheet"; link.href = url; link.id = CONFIG.ID.darkThemeStylesheet; document.documentElement.appendChild(link); } } else { withMaybe(document.getElementById(CONFIG.ID.darkThemeStylesheet), element => element.remove()); } } function set(newState: boolean): void { Preferences.set(P.dark_theme._.active, newState); apply(newState); } function sheldon(): void { // Sheldon cannot do the same thing twice in a row, because the user must be able to override him. const whatSheldonWants = timeIsWithin({ start: Preferences.get(P.dark_theme._.time_on), end: Preferences.get(P.dark_theme._.time_off), })(new Date()); const whatSheldonDidLast = Preferences.get(P.dark_theme._.last_autoset_state); if (whatSheldonWants !== whatSheldonDidLast) { Preferences.set(P.dark_theme._.last_autoset_state, whatSheldonWants); set(whatSheldonWants); } // If the dark theme was toggled (auto or not) in another tab, Sheldon must toggle it here as well: apply(Preferences.get(P.dark_theme._.active)); } function withCacheInvalidation(url: string, date: Date): string { const yyyy = date.getFullYear(); const mm = (date.getMonth() + 1 /* 0-indexed */).toString().padStart(2, "0"); const dd = date.getDate().toString().padStart(2, "0"); return `${url}?v=${yyyy}${mm}${dd}`; }
SimonAlling/better-sweclockers
src/stylesheets/hide.ts
<gh_stars>10-100 import { isString } from "ts-type-guards"; import { r } from "~src/utilities"; export function hideById(i: string): string { return hideBySelector("#" + i); } export function hideByClass(c: string | readonly string[]): string { return hideBySelector(isString(c) ? "."+c : c.map(x => "."+x).join(", ")); } export function hideBySelector(selector: string): string { return ( r` ${selector} { display: none; } ` ); }
SimonAlling/better-sweclockers
src/operations/improved-builtin-editing-tools.ts
import { insertIn, wrapIn } from "./logic/textarea"; declare namespace Tanuki { const Templates: any; } export default () => { /* SweClockers' built-in functions use `.value`, which kills undo history. This operation replaces them with our own `text-field-edit`-based versions, thereby reintroducing undo/redo support in supported browsers. Our versions sort of mimic the default ones, but they feature more intuitive behavior, such as keeping the selection when a wrap tool (e.g. B/U/I) is used. We don't care about protecting data in the absence of undo support; I assume SweClockers only ever modify textarea content "safely" (i.e. without deleting anything). */ try { // If SweClockers change their "API", we want to fail gracefully. Tanuki.Templates.Textarea.Helpers.setSelection = (textarea: HTMLTextAreaElement, replacement: string) => { insertIn(textarea, { string: replacement, replace: true }); }; Tanuki.Templates.Textarea.Helpers.insertAtCaret = (textarea: HTMLTextAreaElement, before: string, after: string) => { if (after === undefined) { insertIn(textarea, { string: before, replace: true }); } else { wrapIn(textarea, { before, after, cursor: "KEEP_SELECTION" }); } }; } catch (err) { return err.toString(); // String conversion is necessary for the error to be handled properly by Userscripter. } };
SimonAlling/better-sweclockers
src/dark-theme.ts
export const AUTHOR = "Soitora" as const; export const URL = { stylesheet: "https://soitora.com/SweClockers-Dark/sweclockers-dark.css", info: "/forum/trad/1515628", } as const;
SimonAlling/better-sweclockers
src/operations/table-toolbar-button.tsx
import { empty, end, start } from "bbcode-tags"; import { unlines } from "lines-unlines"; import { insertAtTheEnd, renderIn } from "~src/operations/logic/render"; import * as SITE from "~src/site"; import * as T from "~src/text"; import { toolbarButton } from "./logic/editing-tools"; import { indent, insert } from "./logic/textarea"; const enum Headings { NONE, FIRST, ALL } const TABLE_CONFIG = { rows: 4, columns: 3, headings: true }; const tableToolbarButton = toolbarButton({ action: (textarea, undoSupport) => insert(table(TABLE_CONFIG))(textarea, undoSupport), // eta-abstracted to defer table generation until button clicked class: SITE.CLASS.toolbarTableButton, tooltip: T.general.tooltip_table, }); export default (undoSupport: boolean) => (e: { textarea: HTMLElement, unorderedListButton: HTMLElement, }) => { const parent = e.unorderedListButton.parentElement as Element; renderIn(parent, insertAtTheEnd, tableToolbarButton(e.textarea as HTMLTextAreaElement, undoSupport)); }; function table(config: Readonly<typeof TABLE_CONFIG>): string { const headingRow = tableRowLines(config.columns, Headings.ALL); const regularRow = tableRowLines(config.columns, config.headings ? Headings.FIRST : Headings.NONE); const theadLines = concat([ start("thead"), headingRow.map(indent), end("thead"), ]); const tbodyLines = concat([ start("tbody"), concat(replicate(config.rows - 1, regularRow.map(indent))), end("tbody"), ]); const tableLines = concat([ start("table"), theadLines.map(indent), tbodyLines.map(indent), end("table"), ]); return unlines(tableLines); } function tableRowLines(columns: number, headings: Headings): readonly string[] { const cell_first = headings === Headings.NONE ? "td" : "th"; const cell_rest = headings === Headings.ALL ? "th" : "td"; return concat([ start("tr"), indent(empty(cell_first)), replicate(columns - 1, indent(empty(cell_rest))), end("tr"), ]); } // From Haskell. Example: replicate(3, 42) = [42, 42, 42] function replicate<T>(n: number, x: T): readonly T[] { return Array(n).fill(x); } function concat(xs: readonly (string | readonly string[])[]): readonly string[] { return ([] as string[]).concat(...xs); }
SimonAlling/better-sweclockers
metadata.ts
import { Metadata } from "userscript-metadata"; import { BuildConfig, metadataUrl, } from "userscripter/build"; import U from "./src/userscript"; export default function(buildConfig: BuildConfig): Metadata { const hostedAt = buildConfig.hostedAt; return { name: U.name, version: versionBasedOnDate(buildConfig.now), description: U.description, author: U.author, namespace: U.namespace, match: [ `*://${U.hostname}/*`, `*://www.${U.hostname}/*`, ], run_at: U.runAt, noframes: U.noframes, ...( hostedAt === null ? {} : { downloadURL: metadataUrl(hostedAt, U.id, "user"), updateURL: metadataUrl(hostedAt, U.id, "meta"), } ), }; } export function versionBasedOnDate(d: Date): string { return [ d.getFullYear(), d.getMonth() + 1, // 0-indexed d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), ].join("."); }
SimonAlling/better-sweclockers
src/operations/edit-mode.ts
<reponame>SimonAlling/better-sweclockers<gh_stars>10-100 import * as SITE from "~src/site"; // Examples include `@Alling: `, `@Alling:` and `@"---": `. const REGEX_POSSIBLY_CLEAN_SLATE_REPLY = /^@("?)([^"]+)\1: ?$/; // Examples include `@Alling: `, `@Alling:` and `@"Better SweClockers": `. export function isCleanSlate_reply(text: string): boolean { const match = text.match(REGEX_POSSIBLY_CLEAN_SLATE_REPLY); return match === null ? false : SITE.isValidUsername(match[2]); } export function mention(username: string): string { // It's non-trivial to write a sound and complete predicate that decides whether a username needs quotes or not. // One complicating factor is that some disallowed usernames have been allowed before (e.g. "simon.alling"). // To avoid having to deal with this, we'll just always add quotes. return `@"${username}"`; }
SimonAlling/better-sweclockers
src/operations/logic/click.ts
<filename>src/operations/logic/click.ts import { BUTTON_CLICK_EVENT } from "~src/operations/prevent-accidental-unload"; export function clickOn(element: HTMLElement): void { // Prevent accidental unload listens for these events: element.dispatchEvent(new Event(BUTTON_CLICK_EVENT)); // click() is necessary for the button to be triggered; dispatching // mousedown and then mouseup is not. element.click(); }
SimonAlling/better-sweclockers
src/selectors.ts
<gh_stars>10-100 import "css.escape"; // It is side-effecty. import * as SITE from "~src/site"; const C = SITE.CLASS; const settingsNavigation = `ul.${C.settingsNavigation}`; const actionButtons = `button[name=action]`; const actionButtonsQuickReply = `#quickreply .controls button`; const forumPostContainer = "." + SITE.CLASS.forumPosts; const signoutButton = `a[href="${SITE.PATH.SIGNOUT}"]`; const textareaToolbarInner = `form .toolbar .tbInner`; export default { textarea: "textarea#" + CSS.escape(SITE.ID.textarea), textareaToolbarInner, textareaToolbarStrikeButton: textareaToolbarInner + ` .strike`, textareaToolbarUnorderedListButton: textareaToolbarInner + ` .ul`, proofDialogTextarea: `.${SITE.CLASS.proofDialog} textarea`, threadTitle: `h1`, moreArticles: `.mainContent ~ .mainContent`, settingsNavigation, actionButtons, quoteButton: "a.button.quote", previewButton: actionButtons + `[value=${SITE.FORM.value.preview}]`, saveButton: actionButtons + `[value=${SITE.FORM.value.submit}]`, saveButtonQuickReply: actionButtonsQuickReply + `:nth-of-type(1)`, previewButtonQuickReply: actionButtonsQuickReply + `:nth-of-type(2)`, forumPostContainer, replyButtonAfterForumPosts: `${forumPostContainer} ~ * .replyToThread`, cityInput: `input[name="city"]`, regionSelect: `select[name="location"]`, sideColumnGuides: `.videoPush.${C.sideBox}`, sideColumnPopularGalleries: `.popularGalleries.${C.sideBox}`, bbParagraph: `.bbParagraph`, forumLink: `.subForums td:first-child > * a[href^="/forum/"]`, // Have to be this specific because there are other random links that we don't want to match. forumPost: "." + SITE.CLASS.forumPost, forumPostAuthorLink: `a.name[itemprop="author"]`, linkedForumPost: `.` + SITE.CLASS.forumPost + `.is-linked`, pageNavigationAfterForumPosts: `${forumPostContainer} ~ * .pages`, quickReplyForm: `#quickreply form`, signoutButton, signinButtonOr: (selector: string) => `a[href="${SITE.PATH.SIGNIN}"], ${selector}`, // Order doesn't matter. followedThreadsLinkText: `#${SITE.ID.header} a[href="${SITE.PATH.FOLLOWED}"] span`, proofDialogCloseButton: "." + SITE.CLASS.proofDialog + " .cntClose", } as const;
SimonAlling/better-sweclockers
src/operations/textarea-size-toggle.tsx
import { h, JSX } from "preact"; import { NumericPreference } from "ts-preferences"; import * as CONFIG from "~src/config"; import iconTextareaLarge from "~src/icons/textarea-large.svg"; import iconTextareaSmall from "~src/icons/textarea-small.svg"; import { insertAtTheEnd, renderIn } from "~src/operations/logic/render"; import { P, Preferences } from "~src/preferences"; import * as SITE from "~src/site"; import * as T from "~src/text"; export default (e: { textarea: HTMLElement, toolbarInner: HTMLElement }) => { const textarea = e.textarea as HTMLTextAreaElement; renderIn(e.toolbarInner, insertAtTheEnd, ( <div class={[ SITE.CLASS.toolbarGroup, CONFIG.CLASS.textareaSize ].join(" ")}> {button(textarea, P.edit_mode._.textarea_size_small)} {button(textarea, P.edit_mode._.textarea_size_large)} </div> )); }; function button(textarea: HTMLTextAreaElement, mode: NumericPreference): JSX.Element { const [ tooltip, icon ] = ( mode === P.edit_mode._.textarea_size_small ? [ T.general.textarea_size_small, iconTextareaSmall ] : [ T.general.textarea_size_large, iconTextareaLarge ] ); return ( <div class="tbButton iconButton noselect" title={tooltip}> <div class="inner"> <div class={SITE.CLASS.toolbarButtonIcon} onClick={() => apply(mode, textarea)} dangerouslySetInnerHTML={{__html: icon}} /> </div> </div> ); } function apply(mode: NumericPreference, textarea: HTMLTextAreaElement): void { const size = Preferences.get(mode); textarea.style.height = size + "px"; Preferences.set(P.edit_mode._.textarea_size, size); }
SimonAlling/better-sweclockers
src/types.ts
<gh_stars>10-100 export interface InsertButtonDescription { insert: string tooltip: string label?: string }
SimonAlling/better-sweclockers
src/operations/actions/shibe.ts
<reponame>SimonAlling/better-sweclockers import * as BB from "bbcode-tags"; import { lines, unlines } from "lines-unlines"; import * as CONFIG from "~src/config"; import * as SITE from "~src/site"; import * as T from "~src/text"; import { insertIn, selectedTextIn } from "../logic/textarea"; export default function(textarea: HTMLTextAreaElement, undoSupport: boolean): void { const selectedText = selectedTextIn(textarea); const selectedLines = lines(selectedText); if (undoSupport || !shibeConfirmationNeeded(selectedLines) || confirm(T.general.generic_lines_confirm(selectedLines.length))) { // `confirm` is problematic in Chrome (see docs/dialogs.md), but Chrome has full undo support. insertIn(textarea, { string: shibeText(selectedText), replace: true, }); } } // A heuristic intended to catch cases when the user likely didn't mean to apply shibe formatting and/or it would be cumbersome to restore the change without undo support. function shibeConfirmationNeeded(selectedLines: readonly string[]): boolean { const nonEmptyLines = selectedLines.filter(line => line !== ""); const longestLineLength = Math.max(...nonEmptyLines.map(line => line.length)); // Shibe formatting is usually applied to a few short lines of text ("wow" etc), and content worth protecting tends to have more and/or longer lines. return nonEmptyLines.length > 5 || longestLineLength > 15; } function shibeText(original: string): string { const MAX = 100; return unlines(lines(original).map( line => [ BB.start(SITE.TAG.font, CONFIG.CONTENT.shibeFont), BB.start(SITE.TAG.color, CONFIG.CONTENT.shibeColor), BB.start(SITE.TAG.i), CONFIG.NBSP.repeat(randomIntBetween(0, Math.max(0, MAX - line.length))), line, BB.end(SITE.TAG.i), BB.end(SITE.TAG.color), BB.end(SITE.TAG.font), ].join("") )); } function randomIntBetween(min: number, max: number): number { return Math.floor(Math.random() * (max - min + 1)) + min; }
SimonAlling/better-sweclockers
src/time.ts
<reponame>SimonAlling/better-sweclockers export function timeIsWithin(interval: Readonly<{ start: number, end: number }>) { return (time: Date): boolean => { const t = timeOfDay(time); const start = interval.start; const end = interval.end; return ( end < start ? t >= start || t < end : t >= start && t < end ); }; } function timeOfDay(date: Date): number { const startOfToday = new Date(); startOfToday.setHours(0); startOfToday.setMinutes(0); startOfToday.setSeconds(0); startOfToday.setMilliseconds(0); return date.getTime() - startOfToday.getTime(); }
SimonAlling/better-sweclockers
src/preferences/customize-content.ts
import { BooleanPreference, } from "ts-preferences"; import * as T from "~src/text"; export default { carousel: new BooleanPreference({ key: "customize_content_carousel", default: true, label: T.preferences.customize_content.carousel, }), social_media: new BooleanPreference({ key: "customize_content_social_media", default: true, label: T.preferences.customize_content.social_media, }), guides: new BooleanPreference({ key: "customize_content_guides", default: true, label: T.preferences.customize_content.guides, }), popular_galleries: new BooleanPreference({ key: "customize_content_popular_galleries", default: true, label: T.preferences.customize_content.popular_galleries, }), new_in_forum_side: new BooleanPreference({ key: "customize_content_new_in_forum_side", default: true, label: T.preferences.customize_content.new_in_forum_side, }), new_in_market: new BooleanPreference({ key: "customize_content_new_in_market", default: true, label: T.preferences.customize_content.new_in_market, }), new_in_test_lab: new BooleanPreference({ key: "customize_content_new_in_test_lab", default: true, label: T.preferences.customize_content.new_in_test_lab, }), in_the_store: new BooleanPreference({ key: "customize_content_in_the_store", default: true, label: T.preferences.customize_content.in_the_store, }), popular_at_prisjakt: new BooleanPreference({ key: "customize_content_popular_at_prisjakt", default: true, label: T.preferences.customize_content.popular_at_prisjakt, }), new_tech_jobs: new BooleanPreference({ key: "customize_content_new_tech_jobs", default: true, label: T.preferences.customize_content.new_tech_jobs, }), external_news: new BooleanPreference({ key: "customize_content_external_news", default: true, label: T.preferences.customize_content.external_news, }), more_articles: new BooleanPreference({ key: "customize_content_more_articles", default: true, label: T.preferences.customize_content.more_articles, }), latest_news: new BooleanPreference({ key: "customize_content_latest_news", default: true, label: T.preferences.customize_content.latest_news, }), new_in_forum_main: new BooleanPreference({ key: "customize_content_new_in_forum_main", default: true, label: T.preferences.customize_content.new_in_forum_main, }), footer: new BooleanPreference({ key: "customize_content_footer", default: true, label: T.preferences.customize_content.footer, }), } as const;
SimonAlling/better-sweclockers
src/operations/improved-corrections.ts
import * as SITE from "~src/site"; import { withMaybe } from "~src/utilities"; export default (e: { correctionsLink: HTMLElement }) => { e.correctionsLink.addEventListener("click", event => { withMaybe(document.querySelector("." + SITE.CLASS.proofDialog), proofDialog => { event.stopImmediatePropagation(); const textarea = proofDialog.querySelector("textarea"); if (textarea instanceof HTMLElement) { textarea.focus(); } }); }, true); };
SimonAlling/better-sweclockers
src/operations/heading-toolbar-button.tsx
<reponame>SimonAlling/better-sweclockers<filename>src/operations/heading-toolbar-button.tsx import { insertAtTheEnd, renderIn } from "~src/operations/logic/render"; import * as SITE from "~src/site"; import * as T from "~src/text"; import { toolbarButton } from "./logic/editing-tools"; import { wrap_tag } from "./logic/textarea"; export default (undoSupport: boolean) => (e: { textarea: HTMLElement, strikeButton: HTMLElement, }) => { const parent = e.strikeButton.parentElement as Element; renderIn(parent, insertAtTheEnd, ( headingToolbarButton(e.textarea as HTMLTextAreaElement, undoSupport) )); }; const headingToolbarButton = toolbarButton({ action: wrap_tag({ tag: SITE.TAG.h, parameterized: false, block: false }), class: SITE.CLASS.toolbarHeadingButton, tooltip: T.general.tooltip_h, style: "background: none;", // to override gray background for .header });
SimonAlling/better-sweclockers
src/operations/actions/search-link.ts
import * as BB from "bbcode-tags"; import { SearchEngine, searchURL } from "~src/search-engines"; import * as SITE from "~src/site"; import { selectedTextIn, wrapIn } from "../logic/textarea"; export default (engine: SearchEngine) => (textarea: HTMLTextAreaElement, _: boolean) => { const tagName = SITE.TAG.url; const selected = selectedTextIn(textarea); const startTag = BB.start(tagName, searchURL(engine, selected)); wrapIn(textarea, { before: startTag, after: BB.end(tagName), cursor: selected === "" ? startTag.length - 2 /* for "] */ : "KEEP_SELECTION", }); };
SimonAlling/better-sweclockers
src/operations/keyboard-shortcuts/edit-mode.ts
import * as Mousetrap from "mousetrap"; import { Action } from "~src/actions"; import { clickOn } from "~src/operations/logic/click"; import { P, Preferences } from "~src/preferences"; import { insertIn } from "../logic/textarea"; const keyboardShortcuts = Preferences.get(P.keyboard); export function submit(e: { textarea: HTMLElement, saveButton: HTMLElement, }) { bindKeyboardShortcut( Action.SUBMIT, _ => clickOn(e.saveButton), { preventDefault: true }, ); } export function preview(e: { textarea: HTMLElement, previewButton: HTMLElement, }) { bindKeyboardShortcut( Action.PREVIEW, _ => clickOn(e.previewButton), { preventDefault: true }, ); } export const insertTab = (content: string, undoSupport: boolean) => (e: { textarea: HTMLElement, }) => { bindKeyboardShortcut( Action.INSERT_TAB, event => { if (document.activeElement === e.textarea) { event.preventDefault(); insertIn(e.textarea as HTMLTextAreaElement, { string: content, replace: undoSupport }); } }, { preventDefault: false }, ); }; function bindKeyboardShortcut( action: Action, handler: (event: Event) => void, options: { preventDefault: boolean, }, ) { for (const entry of keyboardShortcuts) { if (entry.action === action) { Mousetrap.bind(entry.shortcut, event => { if (options.preventDefault) { event.preventDefault(); } handler(event); }); } } }
SimonAlling/better-sweclockers
src/environment.ts
import * as CONFIG from "./config"; import * as SITE from "./site"; // NOTE: Be careful with document.head here, as it may be null at the time of // userscript execution (e.g. in a background tab in Firefox)! export const isOnBSCPreferencesPage = pathMatches(CONFIG.PATH.PREFERENCES.check(SITE.PATH.SETTINGS.check)); export const isOnSweclockersSettingsPage = pathMatches(SITE.PATH.SETTINGS.check) && !isOnBSCPreferencesPage; export const isOnSomeProfilePage = pathMatches(SITE.PATH.PROFILE("\\d+")); function pathMatches(r: RegExp): boolean { return r.test(document.location.pathname); } export const isInForumThreadsView = pathMatches(SITE.PATH.FORUM_THREADS_VIEW); export const isInEditMode_forum = pathMatches(SITE.PATH.EDIT_MODE_FORUM); export const isInEditMode_market = pathMatches(SITE.PATH.EDIT_MODE_MARKET); export const isInEditMode_marketContact = pathMatches(SITE.PATH.EDIT_MODE_MARKET_CONTACT); export const isInEditMode_PM = pathMatches(SITE.PATH.EDIT_MODE_PM); export const isInEditMode_report = pathMatches(SITE.PATH.EDIT_MODE_REPORT); export const isInEditMode_signature = pathMatches(SITE.PATH.EDIT_MODE_SIGNATURE); export const mayHaveJustSubmittedForumPost = pathMatches(SITE.PATH.SUCCESSFULLY_SUBMITTED_FORUM_POST); export const mayHaveJustSubmittedPM = pathMatches(SITE.PATH.SUCCESSFULLY_SUBMITTED_PM); export const isInEditMode = [ isInEditMode_forum, isInEditMode_market, isInEditMode_PM, isInEditMode_report, isInEditMode_signature, ].some(x => x); export const isReadingEditorialContent = [ SITE.PATH.ARTICLE, SITE.PATH.GUIDE, SITE.PATH.NEWS, SITE.PATH.COMPETITION, SITE.PATH.TEST, SITE.PATH.TESTPILOT, ].some(pathMatches); export const isReadingThread = !isInEditMode && [ SITE.PATH.THREAD, SITE.PATH.POST, ].some(pathMatches); export const isReadingForumThread = isReadingThread && document.location.pathname.startsWith(SITE.PATH.FORUM);
SimonAlling/better-sweclockers
__tests__/editing-tools.test.ts
<reponame>SimonAlling/better-sweclockers<filename>__tests__/editing-tools.test.ts import * as smileys from "../src/operations/logic/smileys"; describe("smiley toolbar", () => { it("contains :)", () => { expect(smileys.SMILEYS).toContainEqual<smileys.Smiley>([ ":)", "smiley-smile" ]); }); });
SimonAlling/better-sweclockers
src/browser.ts
export function supportsUndo(userAgent: string): boolean { /* Hard to know for sure, but Gecko browsers don't support document.execCommand as of 2020-07-18 (Firefox 78). https://bugzilla.mozilla.org/show_bug.cgi?id=1220696 "Why not use feature detection?" Because document.execCommand can't be feature-detected: "Note: Only returns true if part of a user interaction. Don't try using the return value to verify browser support before calling a command." https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand#Return_value Android doesn't support undo in general. */ // Make sure the preference labels referencing this function match the implementation. return ![ // Having functions, rather than their return values, in this list means we can reap the full benefits of short-circuiting (however important that may or may not be). isGecko, isAndroid, ].some(f => f(userAgent)); } export function isGecko(userAgent: string): boolean { // Many browsers have "Gecko" in their user agent strings, but I believe only Gecko ones have the eight-digit suffix. return /Gecko\/\d{8}/.test(userAgent); } export function isAndroid(userAgent: string): boolean { return userAgent.includes("Android "); }
SimonAlling/better-sweclockers
src/stylesheets.ts
import * as ms from "milliseconds"; import { ALWAYS } from "userscripter/lib/environment"; import { Stylesheets, stylesheet } from "userscripter/lib/stylesheets"; import * as CONFIG from "~src/config"; import { isInEditMode, isOnBSCPreferencesPage, isOnSweclockersSettingsPage, isReadingThread } from "~src/environment"; import STYLE_PROOFREADING from "~src/lib/proofreading/style.scss"; import { P, Preferences } from "~src/preferences"; import SELECTOR from "~src/selectors"; import * as SITE from "~src/site"; import { hideByClass, hideById, hideBySelector } from "~src/stylesheets/hide"; import { timeIsWithin } from "~src/time"; import autosaveDraft from "./stylesheets/autosave-draft.scss"; import darkThemeTogglePreparations from "./stylesheets/dark-theme-toggle-preparations.scss"; import darkThemeToggle from "./stylesheets/dark-theme-toggle.scss"; import developerMode from "./stylesheets/developer-mode.scss"; import doge from "./stylesheets/doge.scss"; import downForMaintenance from "./stylesheets/down-for-maintenance.scss"; import editingTools from "./stylesheets/editing-tools.scss"; import hideFooter from "./stylesheets/hide-footer.scss"; import highlightOwnPosts from "./stylesheets/highlight-own-posts.scss"; import improvedCorrections from "./stylesheets/improved-corrections.scss"; import improvedImageControls from "./stylesheets/improved-image-controls.scss"; import improvedPaginationButtons from "./stylesheets/improved-pagination-buttons.scss"; import lockHeights from "./stylesheets/lock-heights.scss"; import main from "./stylesheets/main.scss"; import mentionEveryone from "./stylesheets/mention-everyone.scss"; import preferencesLink from "./stylesheets/preferences-link.scss"; import preferencesShortcut from "./stylesheets/preferences-shortcut.scss"; import preferences from "./stylesheets/preferences.scss"; import replaceFollowedThreadsLink from "./stylesheets/replace-followed-threads-link.scss"; import textareaSizeToggle from "./stylesheets/textarea-size-toggle.scss"; import uninterestingSubforums from "./stylesheets/uninteresting-subforums.scss"; function isTimeForMaintenance() { const start = ms.hours(4) + ms.minutes(30); const end = ms.hours(5) + ms.minutes(10); return timeIsWithin({ start, end })(new Date()); } function i(x: string): string { return CONFIG.PREFIX_ID + "stylesheet-" + x; } const STYLESHEETS = { main: stylesheet({ condition: ALWAYS, css: main, }), developer_mode: stylesheet({ condition: () => Preferences.get(P.advanced._.developer_mode), css: developerMode, }), dark_theme_toggle_preparations: stylesheet({ condition: () => Preferences.get(P.dark_theme._.show_toggle), css: darkThemeTogglePreparations, id: i("dark-theme-toggle-preparations"), }), dark_theme_toggle: stylesheet({ condition: () => Preferences.get(P.dark_theme._.show_toggle), css: darkThemeToggle, }), doge: stylesheet({ condition: ALWAYS, css: doge, }), preferences_link: stylesheet({ condition: _ => isOnSweclockersSettingsPage, css: preferencesLink, }), preferences: stylesheet({ condition: _ => isOnBSCPreferencesPage, css: preferences, }), preferences_shortcut: stylesheet({ condition: () => Preferences.get(P.general._.insert_preferences_shortcut), css: preferencesShortcut, }), lock_heights: stylesheet({ condition: () => Preferences.get(P.general._.lock_heights), css: lockHeights, }), improved_pagination_buttons: stylesheet({ condition: () => Preferences.get(P.forum_threads._.improved_pagination_buttons), css: improvedPaginationButtons, }), improved_corrections: stylesheet({ condition: () => Preferences.get(P.general._.improved_corrections), css: improvedCorrections, }), highlight_own_posts: stylesheet({ condition: () => Preferences.get(P.forum_threads._.highlight_own_posts), css: highlightOwnPosts, }), editing_tools: stylesheet({ condition: ALWAYS, css: editingTools, }), textarea_size_toggle: stylesheet({ condition: ALWAYS, css: textareaSizeToggle, }), monospace_font: stylesheet({ condition: () => isInEditMode && Preferences.get(P.edit_mode._.monospace_font), css: `#${CONFIG.ID.document} ${SELECTOR.textarea} { font-family: monospace; }`, }), monospace_font_in_quick_reply_form: stylesheet({ condition: () => isReadingThread && Preferences.get(P.edit_mode._.monospace_font_in_quick_reply_form), css: `#${CONFIG.ID.document} ${SELECTOR.textarea} { font-family: monospace; }`, }), textarea_size_toggle_textarea_height: stylesheet({ condition: () => isInEditMode && Preferences.get(P.edit_mode._.textarea_size_toggle), css: `#${CONFIG.ID.document} ${SELECTOR.textarea} { height: ${Preferences.get(P.edit_mode._.textarea_size)}px; }`, }), autosave_draft: stylesheet({ condition: () => isInEditMode && Preferences.get(P.edit_mode._.autosave_draft), css: autosaveDraft, }), improved_image_controls: stylesheet({ condition: () => Preferences.get(P.advanced._.improved_image_controls), css: improvedImageControls, }), uninteresting_subforums: stylesheet({ condition: ALWAYS, css: uninterestingSubforums, }), replace_followed_threads_link: stylesheet({ condition: () => Preferences.get(P.general._.replace_followed_threads_link), css: replaceFollowedThreadsLink, }), proofread_forum_posts: stylesheet({ condition: () => isInEditMode && Preferences.get(P.advanced._.proofread_forum_posts), css: STYLE_PROOFREADING, id: i("proofread-forum-posts"), }), down_for_maintenance: stylesheet({ condition: () => !isOnBSCPreferencesPage && isTimeForMaintenance() && Preferences.get(P.advanced._.down_for_maintenance), css: downForMaintenance, }), custom_css: stylesheet({ condition: () => Preferences.get(P.advanced._.custom_css_enable), css: Preferences.get(P.advanced._.custom_css_code), }), mention_everyone: stylesheet({ condition: () => Preferences.get(P.forum_threads._.mention_everyone_button), css: mentionEveryone, }), // Customize content: customize_content_carousel: stylesheet({ condition: () => false === Preferences.get(P.customize_content._.carousel), css: hideById(SITE.ID.carousel), }), customize_content_social_media: stylesheet({ condition: () => false === Preferences.get(P.customize_content._.social_media), css: hideByClass(SITE.CLASS.socialMediaButtons), }), customize_content_guides: stylesheet({ condition: () => false === Preferences.get(P.customize_content._.guides), css: hideBySelector(SELECTOR.sideColumnGuides), }), customize_content_popular_galleries: stylesheet({ condition: () => false === Preferences.get(P.customize_content._.popular_galleries), css: hideBySelector(SELECTOR.sideColumnPopularGalleries), }), customize_content_new_in_forum_side: stylesheet({ condition: () => false === Preferences.get(P.customize_content._.new_in_forum_side), css: hideById(SITE.ID.newInForumWidget_side), }), customize_content_new_in_market: stylesheet({ condition: () => false === Preferences.get(P.customize_content._.new_in_market), css: hideById(SITE.ID.newInMarketWidget), }), customize_content_new_in_test_lab: stylesheet({ condition: () => false === Preferences.get(P.customize_content._.new_in_test_lab), css: hideById(SITE.ID.newInTestLabWidget), }), customize_content_in_the_store: stylesheet({ condition: () => false === Preferences.get(P.customize_content._.in_the_store), css: hideById(SITE.ID.inTheStoreWidget), }), customize_content_popular_at_prisjakt: stylesheet({ condition: () => false === Preferences.get(P.customize_content._.popular_at_prisjakt), css: hideById(SITE.ID.popularAtPrisjaktWidget), }), customize_content_new_tech_jobs: stylesheet({ condition: () => false === Preferences.get(P.customize_content._.new_tech_jobs), css: hideById(SITE.ID.newTechJobsWidget), }), customize_content_external_news: stylesheet({ condition: () => false === Preferences.get(P.customize_content._.external_news), css: hideById(SITE.ID.externalNewsWidget), }), customize_content_more_articles: stylesheet({ condition: () => false === Preferences.get(P.customize_content._.more_articles), css: hideBySelector(SELECTOR.moreArticles), }), customize_content_latest_news: stylesheet({ condition: () => false === Preferences.get(P.customize_content._.latest_news), css: hideById(SITE.ID.latestNewsWidget), }), customize_content_new_in_forum_main: stylesheet({ condition: () => false === Preferences.get(P.customize_content._.new_in_forum_main), css: hideById(SITE.ID.newInForumWidget_main), }), customize_content_footer: stylesheet({ condition: () => false === Preferences.get(P.customize_content._.footer), css: hideFooter, }), } as const; // This trick uncovers type errors in STYLESHEETS while retaining the static knowledge of its properties (so we can still write e.g. STYLESHEETS.foo): const _: Stylesheets = STYLESHEETS; void _; export default STYLESHEETS;
SimonAlling/better-sweclockers
src/operations/logic/textarea.ts
import * as BB from "bbcode-tags"; import * as textFieldEdit from "text-field-edit"; import { isNumber } from "ts-type-guards"; import * as CONFIG from "~src/config"; type InsertionResult = Readonly<{ textareaContent: string, startOfInserted: number, endOfInserted: number, }> type Insertion = Readonly<{ string: string, replace: boolean, }> type WrapAction = Readonly<{ cursor: CursorBehavior, before: string, after: string, }> type TagWrapAction = Readonly<{ tag: string, parameterized: boolean, block: boolean, }> export type Action = (textarea: HTMLTextAreaElement, undoSupport: boolean) => void export type CursorBehavior = number | "KEEP_SELECTION" export function indent(s: string): string { return CONFIG.CONTENT.indentation + s; } export function wrapIn(textarea: HTMLTextAreaElement, w: WrapAction): void { const replacement = w.before + selectedTextIn(textarea) + w.after; // Since wrapping doesn't delete any text, undo support is not relevant and replacing is always safe. const insertionResult = insertPure(textarea, { string: replacement, replace: true }); // We must use textFieldEdit.wrapSelection, because if we use insertPure + textFieldEdit.set, the entire textarea content gets selected when the user issues an undo command. textFieldEdit.wrapSelection(textarea, w.before, w.after); // Since we use the insertion result here, it must represent the same modification of the textarea content as textFieldEdit.wrapSelection. if (isNumber(w.cursor)) { placeCursorIn(textarea, insertionResult.startOfInserted + w.cursor); } else { selectRangeIn(textarea, insertionResult.startOfInserted + w.before.length, insertionResult.endOfInserted - w.after.length); } } export function wrap_verbatim(w: WrapAction): Action { return (textarea, _) => wrapIn(textarea, w); } export function wrap_tag(w: TagWrapAction): Action { const spacing = w.block ? "\n" : ""; return wrap_verbatim({ before: BB.start(w.tag, w.parameterized ? "" : undefined) + spacing, after: spacing + BB.end(w.tag), cursor: ( w.parameterized ? 1 + w.tag.length + 2 // 1 for '[', 2 for '="' : "KEEP_SELECTION" ), }); } export function selectedTextIn(textarea: HTMLTextAreaElement): string { return textarea.value.substring(textarea.selectionStart, textarea.selectionEnd); } // Simple insertion. Selected text is kept in the absence of undo support to protect against accidental deletion. export function insert(str: string): Action { return (textarea, undoSupport) => insertIn(textarea, { string: str, replace: undoSupport }); } export function insertIn(textarea: HTMLTextAreaElement, insertion: Insertion): void { // The caller of this function is fully responsible for deciding whether to replace selected text or not. // textFieldEdit.insert replaces selected text, so if that's not desired, we'll first unselect it such that the insertion is done after the selection. if (!insertion.replace) { placeCursorIn(textarea, textarea.selectionEnd); } // We must use textFieldEdit.insert, because if we use insertPure + textFieldEdit.set, the entire textarea content gets selected when the user issues an undo command. textFieldEdit.insert(textarea, insertion.string); textarea.focus(); } function insertPure(textarea: HTMLTextAreaElement, insertion: Insertion): InsertionResult { const text = textarea.value; const start = textarea.selectionStart; const end = textarea.selectionEnd; const startOfInsertedText = insertion.replace ? start : end; return { textareaContent: text.substring(0, startOfInsertedText) + insertion.string + text.substring(end), startOfInserted: startOfInsertedText, endOfInserted: startOfInsertedText + insertion.string.length, }; } export function placeCursorIn(textarea: HTMLTextAreaElement, position: number): void { selectRangeIn(textarea, position, position); } export function selectRangeIn(textarea: HTMLTextAreaElement, start: number, end: number): void { textarea.setSelectionRange(start, end); textarea.focus(); // Must be after setSelectionRange to avoid scrolling to the bottom of the textarea in Chrome. }
SimonAlling/better-sweclockers
src/operations/link-to-top.tsx
<reponame>SimonAlling/better-sweclockers<filename>src/operations/link-to-top.tsx import { h } from "preact"; import { insertAtTheEnd, renderIn } from "~src/operations/logic/render"; import * as SITE from "~src/site"; import * as T from "~src/text"; export default (e: { parent: HTMLElement }) => { renderIn(e.parent, insertAtTheEnd, ( <a href="javascript:window.scrollTo(0, 0)" title={T.general.link_to_top_tooltip}> <svg class={SITE.CLASS.icon} style="transform: rotate(-90deg);"> <use xlinkHref="#icon_double_arrow_right" /> </svg> </a> )); };
SimonAlling/better-sweclockers
src/site.ts
// This file cannot contain Webpack-resolved imports (e.g. "~src/foo"). import U from "./userscript"; export const NAME = U.sitename; export const HOSTNAME = U.hostname; export const HOSTNAME_MOBILE = `m.` + HOSTNAME; export const STYLESHEET_URL = (yyyymmdd: string) => `/css/combine.min.sass.css?v=${yyyymmdd}`; export const BANNER_HEIGHT_TOP = `${121}px`; // default height of top ad banner export const BANNER_HEIGHT_MID = `${360}px`; // default height of page ad modules export const WRAPPER_WIDTH_WIDE_PX = 1250; export const WRAPPER_WIDTH_NARROW_PX = 1000; export const MAX_WIDTH_FOR_NARROW_LAYOUT_PX = 1100; export const EXTRA_TAB_MARGIN = `${8}px`; export const GUTTER_SIZE_PX = 6; // the small padding to the very left and right export const ARTICLE_WIDTH_PX = 680; export const WIDTH_WHERE_NARROW_LAYOUT_GOES_CENTERED = WRAPPER_WIDTH_NARROW_PX + 2 * GUTTER_SIZE_PX; export const WIDTH_WHERE_WIDE_LAYOUT_GOES_CENTERED = WRAPPER_WIDTH_WIDE_PX + 2 * GUTTER_SIZE_PX; export const ID = { header: "header", textarea: "__laika_cnt.textarea.0", carousel: "carousel", menuLockToggle: "menuLock", menuLockToggleOpen: "menuLockOpen", correctionsLink: "proofArticle", postPreview: "preview", latestNewsWidget: "wdgtMainRecentNews", newInForumWidget_main: "wdgtMainRecentThreads", newInForumWidget_side: "wdgtSideRecentThreads", newInMarketWidget: "wdgtSideRecentClassifieds", newInTestLabWidget: "wdgtSideRecentReviews", inTheStoreWidget: "wdgtSideGeeksShop", popularAtPrisjaktWidget: "wdgtSidePopularProducts", newTechJobsWidget: "wdgtSideMonsterJobs", externalNewsWidget: "wdgtSideExternalFeeds", } as const; export const CLASS = { fieldset: "s5fieldset", button: "button", link: "link", icon: "icon", label: "label", disabled: "is-disabled", inner: "inner", colorOrange: "color-orange", menuItem: "menuItem", settingsNavigation: "menuItems", forumPosts: "forumPosts", forumPost: "forum-post", forumPostProfileDetails: "details", forumPostSignature: "signature", forumPostControls: "controls", forumPostByCurrentUser: "isReader", // Don't use isAuthor; it means submitted by OP! bbcode: "bbcode", bbDel: "bbDel", bbImage: "bbImage", bbIns: "bbIns", imgControls: "imgControls", notifications: "pw-notifications", proofDialog: "proofDialog", socialMediaButtons: [ `threadShare`, `greyContentShare`, `sideShare` ], sideBox: "sideBox", smiley: "smiley", subforums: "subforums", toolbarGroup: "tbGroup", toolbarButton: "tbButton iconButton noselect", toolbarButtonIcon: "btnIcon", toolbarHeadingButton: "header", toolbarTableButton: "tbl", } as const; export const FORM = { name: { action: "action", csrfToken: "csrf", message: "message", recipients: "rcpt[]", title: "title", }, value: { preview: "doPreview", submit: "doSubmit", }, } as const; export const PATH = { EDIT_MODE_FORUM: /^\/forum\/(.*\/(svara(\?citera)?|redigera)|ny-trad)/, EDIT_MODE_MARKET: /^\/marknad\/(.+\/(redigera|kontakt)|ny-annons)$/, EDIT_MODE_MARKET_CONTACT: /^\/marknad\/.+\/kontakt$/, EDIT_MODE_PM: /^\/medlem\/\d+\/meddelanden\/(?:nytt-meddelande|post\/\d+\/(?:redigera|svara))/, EDIT_MODE_REPORT: /^\/(forum|marknad|medlem\/\d+\/meddelanden)\/.+\/anmal$/, EDIT_MODE_SIGNATURE: /^\/medlem\/\d+\/installningar\/signatur$/, SETTINGS: { link: "/profil/installningar", // Relying on this path being redirected to the actual settings path allows us to create a link to the preferences page without knowing the user's ID. check: /^\/medlem\/\d+\/installningar/, // Should not have a "$" because it should match subpaths too. }, FOLLOWED: "/forum/foljda", MY_POSTS: "/profil/inlagg", SIGNIN: `/konto/logga-in`, SIGNOUT: `/konto/logga-ut`, ARTICLE: /^\/artikel\//, GUIDE: /^\/guide\//, NEWS: /^\/nyhet\//, COMPETITION: /^\/tavling\//, TEST: /^\/test\//, TESTPILOT: /^\/testpilot\//, FORUM_CATEGORY: /\/forum\/(\d+)/, FORUM: "/forum", FORUM_THREADS_VIEW: /^\/forum\/(aktiva|obesvarade|foljda|skapade|lasta)$/, PROFILE: (userId: number | "\\d+") => new RegExp(`^/medlem/${userId}$`), THREAD: /^\/(?:forum|medlem\/\d+\/meddelanden)\/trad\//, POST: /^\/(?:forum|medlem\/\d+\/meddelanden)\/post\//, SUCCESSFULLY_SUBMITTED_FORUM_POST: /^\/forum\/post\/\d+$/, SUCCESSFULLY_SUBMITTED_PM: /^\/medlem\/\d+\/meddelanden\/(?:post\/\d+(?:#preview)?|trad\/\d+-.+)$/, newPrivateMessage: (sender: number) => `/medlem/${sender}/meddelanden/nytt-meddelande`, forumPost: (postID: string) => `/forum/post/${postID}`, editPost: (postID: number) => `/forum/post/${postID}/redigera`, } as const; export const TAG = { abbr: "abbr", b: "b", bq: "bq", cmd: "cmd", code: "code", color: "color", del: "del", dd: "dd", dl: "dl", dt: "dt", expander: "expander", font: "font", h: "h", i: "i", img: "img", ins: "ins", mark: "mark", math: "math", noparse: "noparse", pre: "pre", quote: "quote", size: "size", spoiler: "spoiler", sub: "sub", sup: "sup", u: "u", url: "url", youtube: "youtube", } as const; const URL_ICONS_TOOLBAR = "/gfx/toolbar2x.png"; export const ICONS = { toolbarIcon: (position: string): string => `<div style="background-image: url('${URL_ICONS_TOOLBAR}'); background-size: 500px auto; background-position: ${position};"></div>`, position_toolbar_url: "0 -125px", position_toolbar_img: "-50px -125px", settings: `<use xlink:href="#icon_settings"></use>`, } as const; export const MOBILE_SITE_DISCLAIMER = { sentFrom: `Skickades från`, mobileSiteDomain: HOSTNAME_MOBILE, } as const; export const USER_ID_NOT_LOGGED_IN = 1; export function getUserID(): number | undefined { const userID = (window as any)?.session?._userid; return typeof userID === "number" ? userID : undefined; } export function isValidUsername(s: string): boolean { // https://www.sweclockers.com/konto/registrera // "Namnet kan innehålla 3–32 tecken: bokstäver, siffror, mellanslag samt binde- och understreck." // My experiments show that e.g. Å and ß are valid characters, and that the name cannot start or end with " ", "-" or "_". // That a username is "valid" does not necessarily mean that it can be used for registering a _new_ account, only that it might be in use by someone. // For example, "." is forbidden, but has been allowed earlier: https://www.sweclockers.com/medlem/197838 // So has '"': https://www.sweclockers.com/medlem/26129 // Weird Unicode intervals are \u00C0-\u00FF with × and ÷ excluded. // Regex matches "Alling ", "Alling-" and "Alling_", so the reverse of the string must also be checked. const REGEX_ALMOST_USERNAME = /^(?![ \-_"])[\w\d \-.\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]{3,32}$/; return REGEX_ALMOST_USERNAME.test(s) && REGEX_ALMOST_USERNAME.test(s.split("").reverse().join("")); }
SimonAlling/better-sweclockers
src/preferences/general.ts
<gh_stars>10-100 import { BooleanPreference, IntegerPreference, StringPreference, } from "ts-preferences"; import * as T from "~src/text"; export default { lock_heights: new BooleanPreference({ key: "lock_heights", default: true, label: T.preferences.general.lock_heights, description: T.preferences.general.lock_heights_description, }), improved_corrections: new BooleanPreference({ key: "improved_corrections", default: true, label: T.preferences.general.improved_corrections, description: T.preferences.general.improved_corrections_description, }), insert_preferences_shortcut: new BooleanPreference({ key: "insert_preferences_shortcut", default: true, label: T.preferences.general.insert_preferences_shortcut, description: T.preferences.general.insert_preferences_shortcut_description, }), replace_followed_threads_link: new BooleanPreference({ key: "replace_followed_threads_link", default: false, label: T.preferences.general.replace_followed_threads_link, description: T.preferences.general.replace_followed_threads_link_description, }), remember_location_in_market: new BooleanPreference({ key: "remember_location_in_market", default: true, label: T.preferences.general.remember_location_in_market, description: T.preferences.general.remember_location_in_market_description, }), location_region: new IntegerPreference({ key: "location_region", default: 0, // "Välj region:" label: T.preferences._.NO_LABEL, extras: { implicit: true }, }), location_city: new StringPreference({ key: "location_city", default: "", label: T.preferences._.NO_LABEL, multiline: false, extras: { implicit: true }, }), } as const;
SimonAlling/better-sweclockers
src/operations/mention-everyone.tsx
import unique from "array-uniq"; import { h, JSX } from "preact"; import * as CONFIG from "~src/config"; import { mention } from "~src/operations/edit-mode"; import { insertBefore, renderIn } from "~src/operations/logic/render"; import SELECTOR from "~src/selectors"; import * as SITE from "~src/site"; import * as T from "~src/text"; export default (e: { forumPostContainer: HTMLElement, quickReplyForm: HTMLElement, replyButton: HTMLElement, }) => { const button = mentionEveryoneButton({ message: usersToMention(e.forumPostContainer).map(mention).join(" "), replyURL: (e.quickReplyForm as HTMLFormElement).getAttribute("action") || "", csrf: session.getCsrfToken(), }); if (document.querySelector(`${SELECTOR.forumPost} ${SELECTOR.forumPostAuthorLink}`) === null) { // Broken thread participant detection. return "Could not detect thread participants"; } renderIn(e.replyButton.parentElement as Element, insertBefore(e.replyButton), button); }; function usersToMention(forumPostContainer: HTMLElement): string[] { const postBySomeoneElse = SELECTOR.forumPost + `:not(.${SITE.CLASS.forumPostByCurrentUser})`; const selector = `${postBySomeoneElse} ${SELECTOR.forumPostAuthorLink}`; const nameLinks = Array.from(forumPostContainer.querySelectorAll(selector)); return unique(nameLinks.map(e => (e.textContent as string).trim())); } function mentionEveryoneButton(props: { message: string, replyURL: string, csrf: string, }): JSX.Element { return ( <form method="POST" action={props.replyURL} class={CONFIG.CLASS.mentionEveryoneButton}> <input name={SITE.FORM.name.message} type="hidden" value={props.message} /> <input name={SITE.FORM.name.csrfToken} type="hidden" value={props.csrf} /> <input name={SITE.FORM.name.action} type="hidden" value={SITE.FORM.value.preview} /> <button type="submit" class={SITE.CLASS.button} title={T.general.mention_everyone_tooltip} > {T.general.mention_everyone_label} </button> </form> ); } declare namespace session { function getCsrfToken(): string }
SimonAlling/better-sweclockers
src/operations/logic/smileys.ts
export type Smiley = readonly [string, string] export const SMILEYS: ReadonlyArray<Smiley> = [ // Pairs of BBCode code and CSS class: [ ":)", "smiley-smile" ], [ ";)", "smiley-wink" ], [ ":D", "smiley-biggrin" ], [ ":P", "smiley-tongue" ], [ ":O", "smiley-surprised" ], [ ":(", "smiley-frown" ], [ ";(", "smiley-cry" ], [ ":|", "smiley-speechless" ], [ ":arrow:", "smiley-arrow" ], [ ":up:", "smiley-up" ], [ ":down:", "smiley-down" ], [ ":confused:", "smiley-confused" ], [ ":mad:", "smiley-mad" ], [ ":lol:", "smiley-lol" ], [ ":joyful:", "smiley-joyful" ], [ ":cool:", "smiley-cool" ], [ ":ninja:", "smiley-ninja" ], [ ":innocent:", "smiley-innocent" ], [ ":rolleyes:", "smiley-rolleyes" ], ]; export function codeFor(smiley: Smiley): string { return smiley[0]; } export function classFor(smiley: Smiley): string { return smiley[1]; }
SimonAlling/better-sweclockers
src/preferences/forum-threads.ts
<filename>src/preferences/forum-threads.ts import { BooleanPreference, StringPreference, } from "ts-preferences"; import * as T from "~src/text"; const quote_signature_buttons = new BooleanPreference({ key: "quote_signature_buttons", default: true, label: T.preferences.forum_threads.quote_signature_buttons, description: T.preferences.forum_threads.quote_signature_buttons_description, }); const dependencies_quote_signature = [ { preference: quote_signature_buttons, condition: (v: boolean) => v, }, ]; export default { improved_pagination_buttons: new BooleanPreference({ key: "improved_pagination_buttons", default: true, label: T.preferences.forum_threads.improved_pagination_buttons, description: T.preferences.forum_threads.improved_pagination_buttons_description, }), insert_link_to_top: new BooleanPreference({ key: "insert_link_to_top", default: true, label: T.preferences.forum_threads.insert_link_to_top, description: T.preferences.forum_threads.insert_link_to_top_description, }), highlight_own_posts: new BooleanPreference({ key: "highlight_own_posts", default: true, label: T.preferences.forum_threads.highlight_own_posts, description: T.preferences.forum_threads.highlight_own_posts_description, }), insert_pm_links: new BooleanPreference({ key: "insert_pm_links", default: true, label: T.preferences.forum_threads.insert_pm_links, description: T.preferences.forum_threads.insert_pm_links_description, }), mention_everyone_button: new BooleanPreference({ key: "mention_everyone_button", default: false, label: T.preferences.forum_threads.mention_everyone_button, description: T.preferences.forum_threads.mention_everyone_button_description, }), quote_signature_buttons, quote_signature_message: new StringPreference({ key: "quote_signature_message", default: T.preferences.forum_threads.quote_signature_message_default, label: T.preferences.forum_threads.quote_signature_message, description: T.preferences.forum_threads.quote_signature_message_description, multiline: true, dependencies: dependencies_quote_signature, }), } as const;