New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

glitched-writer

Package Overview
Dependencies
Maintainers
1
Versions
39
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

glitched-writer - npm Package Compare versions

Comparing version 2.0.2 to 2.0.3

lib/emiter.d.ts

6

lib/char.d.ts

@@ -6,2 +6,3 @@ import GlitchedWriter from './index';

stepsLeft: number;
maxGhosts: number;
ghostsBefore: string[];

@@ -14,6 +15,7 @@ ghostsAfter: string[];

get finished(): boolean;
get isSpecial(): boolean;
type(): Promise<boolean>;
nextStep(): boolean;
addGhost(l: string): void;
nextStep(): void;
addGhost(): void;
removeGhost(): void;
}

@@ -12,5 +12,8 @@ "use strict";

this.writer = writer;
this.stepsLeft = writer.options.genSteps;
if (initialGhosts)
this.ghostsBefore = [...initialGhosts];
this.stepsLeft = writer.options.stepsLeft;
if (this.isSpecial)
this.stepsLeft = 0;
this.maxGhosts = writer.options.genMaxGhosts;
}

@@ -25,2 +28,5 @@ get string() {

}
get isSpecial() {
return ['\t', '\n', '\r', '\f', '\v'].includes(this.goal);
}
async type() {

@@ -30,6 +36,6 @@ const loop = async () => {

this.nextStep();
this.writer.emitStep();
this.writer.emiter.call('step');
return true;
};
await utils_1.wait(this.writer.options.genInitDelay);
!this.isSpecial && (await utils_1.wait(this.writer.options.genInitDelay));
await utils_1.promiseWhile(() => !this.finished && !this.writer.state.isPaused && !this.stop, loop);

@@ -39,4 +45,3 @@ return this.finished;

nextStep() {
const areStepsLeft = this.stepsLeft > 0;
if (areStepsLeft && this.char !== this.goal) {
if (this.stepsLeft > 0 && this.char !== this.goal) {
/**

@@ -46,12 +51,9 @@ * IS GROWING

const { genGhostChance: ghostChance, genChangeChance: changeChance, } = this.writer.options;
if (Math.random() <= ghostChance) {
if (this.writer.state.nGhosts < this.writer.options.genMaxGhosts) {
const newGhost = this.writer.options.genGhost;
this.writer.state.nGhosts++;
this.addGhost(newGhost);
}
if (utils_1.coinFlip(ghostChance)) {
if (this.writer.state.nGhosts < this.maxGhosts)
this.addGhost();
else
this.removeGhost();
}
if (Math.random() <= changeChance)
if (utils_1.coinFlip(changeChance))
this.char = this.writer.options.genGhost;

@@ -63,4 +65,3 @@ }

*/
if (this.char !== this.goal)
this.char = this.goal;
this.char = this.goal;
this.removeGhost();

@@ -72,9 +73,10 @@ }

*/
return true;
return;
}
this.stepsLeft--;
return false;
}
addGhost(l) {
Math.random() < 0.5
addGhost() {
const l = this.writer.options.genGhost;
this.writer.state.nGhosts++;
utils_1.coinFlip()
? insertGhost(this.ghostsBefore, l)

@@ -84,3 +86,3 @@ : insertGhost(this.ghostsAfter, l);

removeGhost() {
Math.random() < 0.5 && this.ghostsBefore.length > 0
utils_1.coinFlip() && this.ghostsBefore.length > 0
? utils_1.deleteRandom(this.ghostsBefore)

@@ -87,0 +89,0 @@ : utils_1.deleteRandom(this.ghostsAfter);

import Options from './options';
import State from './state';
import Char from './char';
import { ConstructorOptions, WriteOptions, PlayOptions } from './types';
import Emiter from './emiter';
import { ConstructorOptions, WriteOptions, PlayOptions, WriterDataResponse, Callback } from './types';
import { wait } from './utils';
import { presets, glyphs } from './presets';
export { presets, glyphs, wait };
declare type StepCallback = (string: string, writerData?: WriterDataResponse) => any;
export interface WriterDataResponse {
string: string;
writer: GlitchedWriter;
options: Options;
state: State;
status?: 'ERROR' | 'SUCCESS';
message?: string;
error?: any;
}
export default class GlitchedWriter {

@@ -22,11 +12,10 @@ htmlElement?: HTMLElement;

state: State;
emiter: Emiter;
charTable: Char[];
previousString: string;
goalString: string;
onStepCallback?: StepCallback;
constructor(htmlElement?: HTMLElement, options?: ConstructorOptions, onStepCallback?: StepCallback);
constructor(htmlElement?: HTMLElement, options?: ConstructorOptions, onStepCallback?: Callback, onFinishCallback?: Callback);
get string(): string;
get genPreviousString(): string;
get writerData(): WriterDataResponse;
get genPreviousString(): string;
emitStep(): void;
write(string: string, writeOptions?: WriteOptions): Promise<WriterDataResponse>;

@@ -36,3 +25,2 @@ play(playOptions?: PlayOptions): Promise<WriterDataResponse>;

private returnResult;
private toggleClass;
private createMatchingCharTable;

@@ -43,3 +31,4 @@ private createPreviousCharTable;

}
export declare const createGlitchedWriter: (htmlElement?: HTMLElement | undefined, options?: ConstructorOptions | undefined, onStepCallback?: StepCallback | undefined) => GlitchedWriter;
export declare function glitchWrite(string: string, htmlElement?: HTMLElement, options?: ConstructorOptions, onStepCallback?: StepCallback): Promise<WriterDataResponse>;
export declare const createGlitchedWriter: (htmlElement?: HTMLElement | undefined, options?: ConstructorOptions | undefined, onStepCallback?: Callback | undefined, onFinishCallback?: Callback | undefined) => GlitchedWriter;
export declare function glitchWrite(string: string, htmlElement?: HTMLElement, options?: ConstructorOptions, onStepCallback?: Callback, onFinishCallback?: Callback): Promise<WriterDataResponse>;
export { presets, glyphs, wait, ConstructorOptions, WriterDataResponse, Callback, };
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.glitchWrite = exports.createGlitchedWriter = exports.wait = exports.glyphs = exports.presets = void 0;
// eslint-disable-next-line import/no-cycle
exports.wait = exports.glyphs = exports.presets = exports.glitchWrite = exports.createGlitchedWriter = void 0;
const options_1 = require("./options");
const state_1 = require("./state");
// @ts-ignore
// eslint-disable-next-line import/no-cycle
const char_1 = require("./char");
// @ts-ignore
const emiter_1 = require("./emiter");
const utils_1 = require("./utils");

@@ -16,13 +13,11 @@ Object.defineProperty(exports, "wait", { enumerable: true, get: function () { return utils_1.wait; } });

Object.defineProperty(exports, "glyphs", { enumerable: true, get: function () { return presets_1.glyphs; } });
// @ts-ignore
class GlitchedWriter {
constructor(htmlElement, options, onStepCallback) {
constructor(htmlElement, options, onStepCallback, onFinishCallback) {
this.charTable = [];
this.previousString = '';
this.goalString = '';
this.htmlElement = htmlElement;
this.options = new options_1.default(this, options);
if (onStepCallback)
this.onStepCallback = onStepCallback;
this.state = new state_1.default();
this.htmlElement = htmlElement;
this.state = new state_1.default(this);
this.emiter = new emiter_1.default(this, onStepCallback, onFinishCallback);
}

@@ -37,2 +32,7 @@ get string() {

}
get genPreviousString() {
var _a;
const elTextContent = (_a = this.htmlElement) === null || _a === void 0 ? void 0 : _a.textContent;
return (elTextContent !== null && elTextContent !== void 0 ? elTextContent : this.previousString).trim();
}
get writerData() {

@@ -47,21 +47,2 @@ const writer = this, { options, state, string } = this;

}
get genPreviousString() {
var _a;
let elTextContent = (_a = this.htmlElement) === null || _a === void 0 ? void 0 : _a.textContent;
if (this.options.reverseOutput)
elTextContent && (elTextContent = utils_1.reverseString(elTextContent));
return (elTextContent !== null && elTextContent !== void 0 ? elTextContent : this.previousString).trim();
}
emitStep() {
const { htmlElement } = this;
let { string } = this;
if (this.options.reverseOutput)
string = utils_1.reverseString(string);
if (htmlElement)
htmlElement.textContent = string;
if (htmlElement)
htmlElement.setAttribute('data-string', string);
if (this.onStepCallback)
this.onStepCallback(string, this.getWriterData());
}
async write(string, writeOptions) {

@@ -76,2 +57,3 @@ var _a, _b;

this.state.nGhosts = 0;
this.options.setCharset();
if (this.options.startFrom === 'matching')

@@ -92,3 +74,2 @@ this.createMatchingCharTable();

this.state.play();
this.toggleClass(true);
if (this.options.oneAtATime) {

@@ -110,16 +91,10 @@ const reverse = (_a = playOptions === null || playOptions === void 0 ? void 0 : playOptions.reverse) !== null && _a !== void 0 ? _a : false;

catch (error) {
this.getWriterData('ERROR', 'Writer encountered an error.', error);
return this.getWriterData('ERROR', 'Writer encountered an error.', error);
}
return this.state.finished
? this.getWriterData('SUCCESS', `The writer finished typing.`)
: this.getWriterData('ERROR', `Writer failed to finish typing.`);
}
pause() {
this.toggleClass(false);
this.state.pause();
}
returnResult(finished) {
finished && this.state.finish();
this.emitStep();
this.toggleClass(false);
finished ? this.emiter.call('finish') : this.emiter.call('step');
return finished

@@ -129,8 +104,2 @@ ? this.getWriterData('SUCCESS', `The writer finished typing.`)

}
toggleClass(enable) {
const el = this.htmlElement, className = 'glitched-writer--writing';
if (!el)
return;
enable ? utils_1.animateWithClass(el, className) : el.classList.remove(className);
}
createMatchingCharTable() {

@@ -188,8 +157,10 @@ const { genPreviousString: previous, goalString: goal } = this, goalStringArray = makeGoalArray(previous, goal), maxDist = Math.ceil(this.options.genMaxGhosts / 2);

}
const createGlitchedWriter = (htmlElement, options, onStepCallback) => new GlitchedWriter(htmlElement, options, onStepCallback);
const createGlitchedWriter = (htmlElement, options, onStepCallback, onFinishCallback) => new GlitchedWriter(htmlElement, options, onStepCallback, onFinishCallback);
exports.createGlitchedWriter = createGlitchedWriter;
async function glitchWrite(string, htmlElement, options, onStepCallback) {
const writer = new GlitchedWriter(htmlElement, options, onStepCallback);
async function glitchWrite(string, htmlElement, options, onStepCallback, onFinishCallback) {
const writer = new GlitchedWriter(htmlElement, options, onStepCallback, onFinishCallback);
return writer.write(string);
}
exports.glitchWrite = glitchWrite;
// const Writer = new GlitchedWriter(undefined, {}, string => console.log(string))
// Writer.write('\tNothing\n\tspecial here!')

@@ -17,6 +17,6 @@ import { OptionsFields, ConstructorOptions, RangeOrNumber, AppendedText } from './types';

trailingText: AppendedText | undefined;
reverseOutput: boolean;
writer: GlitchedWriter;
ghostCharset: string;
constructor(writer: GlitchedWriter, options?: ConstructorOptions | PresetName);
get genSteps(): number;
get stepsLeft(): number;
get genInterval(): number;

@@ -29,2 +29,3 @@ get genInitDelay(): number;

getAppendedText(witch: 'trailing' | 'leading'): string;
setCharset(): void;
}

@@ -7,3 +7,3 @@ "use strict";

constructor(writer, options) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
this.steps = [1, 6];

@@ -21,3 +21,3 @@ this.interval = [50, 150];

this.trailingText = undefined;
this.reverseOutput = false;
this.ghostCharset = '';
if (typeof options === 'string')

@@ -34,2 +34,3 @@ options = presets_1.presets[options];

this.glyphs = utils_1.parseCharset(options.glyphs);
this.ghostCharset = this.glyphs;
this.glyphsFromString = (_g = options.glyphsFromString) !== null && _g !== void 0 ? _g : this.glyphsFromString;

@@ -40,29 +41,40 @@ this.oneAtATime = (_h = options.oneAtATime) !== null && _h !== void 0 ? _h : this.oneAtATime;

this.trailingText = (_l = options.trailingText) !== null && _l !== void 0 ? _l : this.trailingText;
this.reverseOutput = (_m = options.reverseOutput) !== null && _m !== void 0 ? _m : this.reverseOutput;
this.writer = writer;
}
get genSteps() {
return getRandomFromRange(this.steps);
get stepsLeft() {
return utils_1.getRandomFromRange(this.steps);
}
get genInterval() {
return getRandomFromRange(this.interval);
return utils_1.getRandomFromRange(this.interval);
}
get genInitDelay() {
return getRandomFromRange(this.initialDelay);
return utils_1.getRandomFromRange(this.initialDelay);
}
get genChangeChance() {
return getRandomFromRange(this.changeChance, false);
return utils_1.getRandomFromRange(this.changeChance, false);
}
get genGhostChance() {
return getRandomFromRange(this.ghostChance, false);
return utils_1.getRandomFromRange(this.ghostChance, false);
}
get genMaxGhosts() {
var _a;
const { maxGhosts: max } = this;
if (max === 'relative')
if (this.maxGhosts === 'relative')
return Math.round((((_a = this.writer.goalString) === null || _a === void 0 ? void 0 : _a.length) || 25) * 0.2);
return max;
return this.maxGhosts;
}
get genGhost() {
var _a;
return (_a = utils_1.randomChild(this.ghostCharset)) !== null && _a !== void 0 ? _a : '';
}
getAppendedText(witch) {
const text = witch === 'trailing' ? this.trailingText : this.leadingText;
if (!text)
return '';
if (text.display === 'always' ||
(text.display === 'when-typing' && this.writer.state.isTyping) ||
(text.display === 'when-not-typing' && !this.writer.state.isTyping))
return text.value;
return '';
}
setCharset() {
let charset = this.glyphs;

@@ -81,20 +93,5 @@ if (this.glyphsFromString !== 'none') {

}
return (_a = utils_1.randomChild(charset)) !== null && _a !== void 0 ? _a : '';
this.ghostCharset = charset;
}
getAppendedText(witch) {
const text = witch === 'trailing' ? this.trailingText : this.leadingText;
if (!text)
return '';
if (text.display === 'always' ||
(text.display === 'when-typing' && this.writer.state.isTyping) ||
(text.display === 'when-not-typing' && !this.writer.state.isTyping))
return text.value;
return '';
}
}
exports.default = Options;
function getRandomFromRange(range, round = true) {
return typeof range === 'number'
? range
: utils_1.random(...range, round ? 'round' : undefined);
}

@@ -23,3 +23,2 @@ "use strict";

trailingText: undefined,
reverseOutput: false,
},

@@ -26,0 +25,0 @@ nier: {

@@ -0,2 +1,4 @@

import GlitchedWriter from '.';
export default class State {
writer: GlitchedWriter;
nGhosts: number;

@@ -6,6 +8,7 @@ isTyping: boolean;

finished: boolean;
constructor(nGhosts?: number);
constructor(writer: GlitchedWriter);
play(): void;
pause(): void;
finish(): void;
toggleClass(enable: boolean): void;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("./utils");
class State {
constructor(nGhosts = 0) {
constructor(writer) {
this.nGhosts = 0;
this.isTyping = false;
this.isPaused = false;
this.finished = false;
this.nGhosts = nGhosts;
this.writer = writer;
}

@@ -14,2 +16,3 @@ play() {

this.finished = false;
this.toggleClass(true);
}

@@ -19,2 +22,3 @@ pause() {

this.isPaused = true;
this.toggleClass(false);
}

@@ -24,4 +28,11 @@ finish() {

this.finished = true;
this.toggleClass(false);
}
toggleClass(enable) {
const el = this.writer.htmlElement, className = 'glitched-writer--writing';
if (!el)
return;
enable ? utils_1.animateWithClass(el, className) : el.classList.remove(className);
}
}
exports.default = State;

@@ -0,1 +1,2 @@

import { RangeOrNumber } from './types';
export declare function random(min: number, max: number, math?: 'floor' | 'round' | 'ceil'): number;

@@ -14,1 +15,3 @@ export declare function randomChild<T>(array: Array<T>): T;

export declare const reverseString: (str: string) => string;
export declare function getRandomFromRange(range: RangeOrNumber, round?: boolean): number;
export declare const coinFlip: (p?: number) => boolean;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.reverseString = exports.animateWithClass = exports.isInRange = exports.arrayOfTheSame = exports.promiseWhile = exports.wait = exports.deleteRandom = exports.parseCharset = exports.filterDuplicates = exports.randomChild = exports.random = void 0;
exports.coinFlip = exports.getRandomFromRange = exports.reverseString = exports.animateWithClass = exports.isInRange = exports.arrayOfTheSame = exports.promiseWhile = exports.wait = exports.deleteRandom = exports.parseCharset = exports.filterDuplicates = exports.randomChild = exports.random = void 0;
/* eslint-disable no-unused-vars */

@@ -59,5 +59,3 @@ function random(min, max, math) {

exports.arrayOfTheSame = arrayOfTheSame;
const isInRange = (min, value, max) => {
return value >= min && value < max;
};
const isInRange = (min, value, max) => value >= min && value < max;
exports.isInRange = isInRange;

@@ -73,1 +71,9 @@ const animateWithClass = (element, className) => {

exports.reverseString = reverseString;
function getRandomFromRange(range, round = true) {
return typeof range === 'number'
? range
: random(...range, round ? 'round' : undefined);
}
exports.getRandomFromRange = getRandomFromRange;
const coinFlip = (p = 0.5) => Math.random() < p;
exports.coinFlip = coinFlip;
{
"name": "glitched-writer",
"version": "2.0.2",
"version": "2.0.3",
"description": "Glitched text-writer module, with highly customizable settings to get the effect You're looking for. Generally for web as a client dependency, but can be also used elswere.",

@@ -31,3 +31,3 @@ "author": "Damian Tarnawski @thetarnav <gthetarnav@gmail.com>",

"parcel-bundler": "^1.12.5",
"pug": "^2.0.4",
"pug": "^3.0.2",
"sass": "^1.32.8",

@@ -34,0 +34,0 @@ "ts-node": "^9.1.1",

@@ -15,9 +15,13 @@ # Glitched Writer

- Can be attached to a **HTML Element** or simply printed out, by providing callback function. Therefore it can be used anywhere.
- Highly customizable behavior. Set of options will help you achieve the effect you desire.
- Can be attached to a **HTML Element** for automatic text-displaying.
- Callback functions for every step and finish.
- Events **gw_finished** and **gw_step** are dispatched on the HTML Element.
- For styling purposes, while writing: attatches **glitched-writer--writing** class to the HTML Element and **data-string attribute** with current string state.
- Written in **typescript**.
- Written in **Typescript**.

@@ -53,6 +57,6 @@ ---

```js
// Default config and some attaching HTML Element:
const Writer = new GlitchedWriter(htmlElement)
// Calling GlitchedWriter constructor:
const Writer = new GlitchedWriter(htmlElement, options, onStepCallback, onFinishCallback)
// Same, but with custom options:
// Custom options:
const Writer = new GlitchedWriter(htmlElement, {

@@ -63,9 +67,9 @@ interval: [10, 70],

// Same, but with on-step-callback added:
// On-step-callback added:
const Writer = new GlitchedWriter(htmlElement, undefined, (string, writerData) => {
console.log(`Current string: ${string}`)
console.log('All the class data:' writerData)
console.log('All the class data:', writerData)
})
// Or by using alternative class-creating function:
// Using alternative class-creating function:
import { createGlitchedWriter } from 'glitched-writer'

@@ -78,3 +82,3 @@

Writing stuff with async / await.
Writing stuff and waiting with async / await.

@@ -84,6 +88,8 @@ ```js

// Wrap this in some async function:
// Or use .then() instead.
const res = await Writer.write('Welcome')
console.log(`Current string: ${res.string}`)
console.log('All the class data:' res.data)
console.log(`Finished writing: ${res.string}`)
console.log('All the writer data:', res)

@@ -95,2 +101,20 @@ await wait(1200) // additional simple promise to wait some time

### Text Input
Don't be afraid to call write method on top of each oder.
Newer will stop the ongoing one.
```js
import GlitchedWriter, { wait } from 'glitched-writer'
const Writer = new GlitchedWriter(textEl, {}, undefined, string => {
// do sth after each finished write
})
Writer.write('Some placeholder')
inputEl.addEventListener('input', () => {
Writer.write(inputEl.value)
})
```
### Pausing & Playing

@@ -117,8 +141,39 @@

For quick one-time writing.
```js
import { glitchWrite } from 'glitched-writer'
glitchWrite('Write this and DISAPER!', htmlElement, options, onStepCallback)
glitchWrite('Write this and DISAPER!', htmlElement, options, ...)
```
### Listening For Events
```js
textHtmlElement.addEventListener('gw_finished', e =>
console.log('finished writing:', e.detail.string),
)
textHtmlElement.addEventListener('gw_step', e =>
console.log('current step:', e.detail.string),
)
```
### Available imports
List of all things that can be imported from glitched-writer module.
```ts
import GlitchedWriter, { // <-- GlitchedWriter class
ConstructorOptions // <-- Options type
Callback // <-- Callback type
WriterDataResponse, // <-- Type of response in callbacks
createGlitchedWriter, // <-- Alternative to creating writer class instance
glitchWrite, // <-- One time write funcion
presets, // <-- Object with all prepared presets of options
glyphs, // <-- Same but for glyph charsets
wait, // <-- Ulitity async function, that can be used to wait some time
} from 'glitched-writer'
```
## Presets

@@ -138,3 +193,3 @@

### Importing objects
### Importing preset objects

@@ -155,15 +210,14 @@ You can import the option object of mentioned presets and tweak them, as well as some glyph sets.

{
steps?: RangeOrNumber // [1, 6]
interval?: RangeOrNumber // [50, 150]
initialDelay?: RangeOrNumber // [0, 1500]
changeChance?: RangeOrNumber // 0.6
ghostChance?: RangeOrNumber // 0.15
maxGhosts?: number | 'relative' // 'relative'
glyphs?: string | string[] | Set<string> // glyphs.full
glyphsFromString?: 'previous' | 'goal' | 'both' | 'none' // 'none'
oneAtATime?: boolean // false
startFrom?: 'matching' | 'previous' | 'erase' // 'matching'
leadingText?: AppendedText // undefined
trailingText?: AppendedText // undefined
reverseOutput?: boolean // false
steps?: RangeOrNumber, // [1, 6]
interval?: RangeOrNumber, // [50, 150]
initialDelay?: RangeOrNumber, // [0, 1500]
changeChance?: RangeOrNumber, // 0.6
ghostChance?: RangeOrNumber, // 0.15
maxGhosts?: number | 'relative', // 'relative'
glyphs?: string | string[] | Set<string>, // glyphs.full
glyphsFromString?: 'previous' | 'goal' | 'both' | 'none', // 'none'
oneAtATime?: boolean, // false
startFrom?: 'matching' | 'previous' | 'erase', // 'matching'
leadingText?: AppendedText, // undefined
trailingText?: AppendedText, // undefined
}

@@ -204,3 +258,2 @@

- display - _When_: 'always' or 'when-typing' or 'when-not-typing'
- **reverseOutput** - _should the string output be reversed or not. It's usefull for using the ::first-letter css selector for... well... the last letter_

@@ -207,0 +260,0 @@ ## Links:

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc