0.1.31 • Published 2 months ago

@substrate-system/util v0.1.31

Weekly downloads
-
License
SEE LICENSE IN LI...
Repository
github
Last release
2 months ago

util

tests types module semantic versioning dependencies install size license

Utility functions for the front end.

install

npm i -S @substrate-system/util

import

import util from '@substrate-system/util'

// or individual functions
import { attributesToString } from '@substrate-system/util'

API

toString

Convert an object into a string suitable for HTML attributes. The object should be like { attributeName: value }. value can be and array, string, or boolean. If it is a boolean, then this will add the attribute name only, eg

import { attributes } from '@substrate-system/util/to-string.js'

attributes({ disabled: true })
// => 'disabled'
import { attributes } from '@substrate-system/util/to-string.js'

const string = attributes({ hello: 'abc', ok: '123' })

// => 'hello="abc" ok="123"'
import { attributes } from '@substrate-system/util/to-string.js'

test('Create attributes with null and undefined', t => {
    const str = attributes({
        hello: 'abc',
        abc: undefined,
        def: null,
        ghi: false,
        jkl: ''
    })

    t.equal(str, 'hello="abc"')
})

lock & unlock scrolling

Prevents body scrolling, useful for things like "dialog" windows. Keeps track of which elements requested a lock so multiple levels of locking are possible without premature unlocking.

Originally seen in the shoelace library.

example

import {
    lockBodyScrolling,
    unlockBodyScrolling
} from '@substrate-system/util/scroll'

// stop scroll
lockBodyScrolling(document.body)

// ...sometime in the future...
unlockBodyScrolling(document.body)

lockBodyScrolling

Stop scrolling.

function lockBodyScrolling (lockingEl:HTMLElement):void

unlockBodyScrolling

Resume scrolling.

function unlockBodyScrolling (lockingEl:HTMLElement):void

Constants

Various special characters.

const EM_DASH = '\u2014'
const EN_DASH = '\u2013'
const NBSP = '\u00A0'
const PETABYTE = (2 ** 50)
const TERABYTE = (2 ** 40)
const GIGABYTE = (2 ** 30)
const MEGABYTE = (2 ** 20)
const KILOBYTE = (2 ** 10)
const ELLIPSIS = '\u2026'
const BULLET = '\u2022'
import { ELLIPSIS } from '@substrate-system/util/constants'

element.textContent = `${ELLIPSIS} something dramatic ${ELLIPSIS}`

HTML classes

Create a new class name string by concattenating the given input.

import { classes } from '@substrate-system/util/classes'
const className = classes('hello', '123', '100')
// => 'hello 123 100'

self

The self object for Node.

import { self } from '@substrate-system/util/node'

humanFilesize

Take the number of bytes, return a string abbreviated to common sizes (megabyte, kilobyte, etc).

Example

import { humanFilesize } from '@substrate-system/util/filesize'

const size = humanFilesize(10_000)
console.log(size)
// => 9.8 KiB

API

function humanFilesize (
    bytes:number,
    si:boolean = false,
    dp:number = 1
):string
arguments
  • bytes the byte count
  • si -- use SI, instead of EIC units (default false)
  • dp is the number of decimal places to show.

Queue

import { Queue } from '@substrate-system/util/queue'

Create a queue of promises. Promises will execute 1 at a time, in sequential order.

class Queue<T> {
    add (createP:()=>Promise<T>):Promise<T|void>
}

queue.add

Take a function that returns a promise. Return a promise that will resolve when the created promise resolves.

add (createP:()=>Promise<T>):Promise<T|void>

!NOTE
This will resolve promises in the order they were added to the queue.

example

import { test } from '@substrate-system/tapzero'
import { Queue } from '@substrate-system/util'

test('queue of 3 items', t => {
    const q = new Queue<string>()

    // [p1, p2, p3]
    const returned = [false, false, false]

    const p1 = q.add(() => {
        return new Promise<string>(resolve => {
            setTimeout(() => resolve('p1'), 300)
        })
    })

    const p2 = q.add(() => {
        return new Promise<string>(resolve => {
            setTimeout(() => resolve('p2'), 200)
        })
    })

    const p3 = q.add(() => {
        return new Promise<string>(resolve => {
            setTimeout(() => resolve('p3'), 100)
        })
    })

    // p1 takes the longest
    p1.then((value) => {
        t.equal(value, 'p1', '"p1" string is ok')
        returned[0] = true
        t.ok(!returned[2], 'p2 should not have returned yet')
        t.ok(!returned[1], 'p1 should not have returned yet')
    })

    p2.then(value => {
        t.equal(value, 'p2', 'should get string "p2"')
        returned[1] = true
        t.ok(returned[0], 'should have p1 b/c it was added first')
        t.ok(!returned[2], 'should not have 3 yet b/c it was addded last')
    })

    // p3 is the fastest
    p3.then(value => {
        t.equal(value, 'p3', 'should get string "p3"')
        returned[2] = true
        t.ok(returned[0], 'should have p1 because it was added first')
        t.ok(returned[1], 'should have p2 because it was added next')
    })

    // return 3 so the test knows when to end,
    // because they resolve in order,
    // even though the ms are backwards
    return p3
})

sleep

Import sleep from here to reduce duplication.

function sleep (ms?:number):Promise<void>
import { sleep } from '@substrate-system/util'

await sleep(500)  // 1/2 second

isEmailValid(maybeEmail:string)

Validate an email address.

function isEmailValid (maybeEmail:string):boolean

example

import { isEmailValid } from '@substrate-system/util/email'

isEmailValid('aaa@bbb.com')
// => true

parseForm

Parse a form and return a plain object. If a form control with the same name appears more than once, the property will be converted to an array.

function parseForm (form:HTMLFormElement):Record<string, unknown>

attributesToString

Take an array of attributes, and transform them into a string format. This can be useful for creating web components.

function attributesToString (attrs:Attr[]):string {

example

import { attributesToString } from '@substrate-system/util'

const el = document.getElementById('example')
const str = attributesToString(Array.from(el!.attributes))
console.log(str)
// => 'type="text" id="example" required'

setAttributes

Set the given attributes from an object. Will handle boolean attributes like required.

function setAttributes (el:HTMLElement, attrs:Record<string, string|boolean>)
import { attributesToString, setAttributes } from '@substrate-system/util'

const input = document.getElementById('test') as HTMLInputElement

setAttributes(input, {
    id: 'test',
    required: true,
    name: 'fooo',
    class: 'testing'
})

console.log(attributesToString(Array.from(input.attributes)))
// => 'id="test" class="testing" name="fooo" required',

attributesAsObject

Return an object of { key: value } from an array of attributes. If an attribute is a boolean value, then it will be { name: true }.

function attributesAsObject (attrs:Attr[]):Record<string, string|true>
import { attributesAsObject } from '@substrate-system/util'

const el = document.querySelector('input')
const attrs = Array.from(el!.attributes)
const obj = attributesAsObject(attrs)
console.log(obj)
// => {
//   "type": "text",
//   "required": true,
//   "name": "example",
//   "foo": "bar"
// }

objectToString

Take an object, as from attributesAsObject, and stringify it for use in HTML.

function objectToString (obj:Record<string, string|true>):string
import { objectToString } from '@substrate-system/util'

const obj =  {
    type: "text",
    required: true,
    name: "example",
    foo: "bar"
}
const str = objectToString(obj)
console.log(str)
// => 'type="text" required name="example" foo="bar"'

CONSTANTS

Expose unicode characters.

import * as CONSTANTS from '@substrate-system/util/CONSTANTS'
// CONSTANTS.ts
export const EM_DASH = '\u2014'
export const EN_DASH = '\u2013'
export const NBSP = '\u00A0'
0.1.31

2 months ago

0.1.27

4 months ago

0.1.29

2 months ago

0.1.25

4 months ago

0.1.26

4 months ago

0.1.23

5 months ago

0.1.22

6 months ago

0.1.20

7 months ago

0.1.21

6 months ago

0.1.13

9 months ago

0.1.14

9 months ago

0.1.15

9 months ago

0.1.16

8 months ago

0.1.17

8 months ago

0.1.18

8 months ago

0.1.19

8 months ago

0.1.11

10 months ago

0.1.10

10 months ago

0.1.8

1 year ago

0.1.7

1 year ago

0.1.6

1 year ago

0.1.5

1 year ago

0.1.4

1 year ago

0.1.3

1 year ago

0.1.2

1 year ago

0.1.0

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago

0.0.0

1 year ago