网络用户 QQ
常见类型Script网络工具
目录
开始
运行以下命令开始使用 web-utils 在您的项目中:
npm i @alessiofrittoli/web-utils
或使用 pnpm
pnpm i @alessiofrittoli/web-utils
变了什么
最新版本的更新 QQ
- 删除已贬值
getTypedMap现在属于@alessiofrittoli/typed-map。 。 。 . - 移动
openBrowserPopUp改为/browser-popup子路径导出 . - 移动
Document Picture-in-Picture改为/picture-in-picture子路径导出 . - 移动
Cookie类 改为/cookie子路径导出 . - 移动
LocalStorage类 改为/storage子路径导出 . - 移动
SessionStorage类 改为/storage子路径导出 . - 移动
getDimensions改为/sizes子路径导出 .
旧更新 :
- 添加
normalizeIndex函数。 见 API 参考 需要更多信息. - 添加
getPreviousIndex函数。 见 API 参考 需要更多信息. - 添加
getNextIndex函数。 见 API 参考 需要更多信息. - 添加
insertAfter函数。 见 API 参考 需要更多信息. - 添加
deferTask。见 API 参考 需要更多信息. - 添加
deferCallback。见 API 参考 需要更多信息. - 添加
parameterized函数。 见 API 参考 需要更多信息. - 添加文档 Picture 工具 。 见 文档图片 需要更多信息.
发展
运行以下开始开发
nvm use
pnpm i
地方发展
运行以下
pnpm dev
这将生成未忽略的输出代码, 源图并启用源文件监视器 .
生产建设
运行以下来创建本地生产建筑
pnpm build
这将生成没有源代码的已修改输出代码 .
单位测试
通过运行下列程序运行所有定义的测试套件 :
# Run tests and watch file changes.
pnpm test:watch
# Run tests in a CI environment.
pnpm test:ci
进行覆盖测试
然后开始使用 HTTP 服务器服务覆盖文件 ./coverage 文件夹.
您可以在您第一次运行此命令时看到空白页 。 只需刷新浏览器即可看到更新 .
pnpm test:coverage:serve
捐款
献礼真受欢迎!
请参看 贡献文件 了解如何开始为该项目作出贡献的更多信息.
帮助更新此项目 GitHub 赞助商。 。 。 .
警卫
如果你认为你发现了安全漏洞 我们鼓励你 负责地披露此事,不公开问题我们将调查所有合法的报告。 电子邮件 [email protected] 披露任何安全弱点.
API 参考
阵列公用事业
arrayUnique
从数组中删除重复值.
参数
| 参数 | 类型 | 说明 |
|---|---|---|
array | T[] | 输入阵列 . |
回返
类型 : T[]
被过滤的阵列 .
使用量
从数组中删除重复
import { arrayUnique } from '@alessiofrittoli/web-utils'
const pointer = {}
console.log(arrayUnique([pointer, 'b', pointer, 'c', 'b']))
// Outputs: [ {}, 'b', 'c' ]
arrayObjectUnique
从引用对象密钥的数组中删除重复条目.
参数
| 参数 | 类型 | 说明 |
|---|---|---|
array | T[] | 一系列对象. |
property | keyof T | 要提到的对象属性 . |
回返
类型 : T[]
被过滤的阵列 .
使用量
删除相同正则值的数组重复
import { arrayObjectUnique } from '@alessiofrittoli/web-utils'
const arr = [
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
{ id: 1, name: 'c' }, // duplicate `id`
{ id: 3, name: 'd' },
{ id: 4, name: 'a' }, // duplicate `name`
]
console.log(arrayObjectUnique(arr, 'id'))
// Outputs: [
// { id: 1, name: 'a' },
// { id: 2, name: 'b' },
// { id: 3, name: 'd' },
// { id: 4, name: 'a' },
// ]
console.log(arrayObjectUnique(arr, 'name'))
// Outputs: [
// { id: 1, name: 'a' },
// { id: 2, name: 'b' },
// { id: 1, name: 'c' },
// { id: 3, name: 'd' },
// ]
listToArray
将字符串化的矩阵转换为矩阵对象 .
参数
| 参数 | 类型 | 说明 |
|---|---|---|
string | string | 一系列对象. |
回返
类型 : string[]
转换为串行对象的矩阵 .
使用量
基本用途
import { listToArray } from '@alessiofrittoli/web-utils'
console.log(listToArray('1,2, 3, 4').map(Number))
// Outputs: [ 1, 2, 3, 4 ]
chunkInto
将阵列分割成块 .
类型参数
| 参数 | 默认 | 说明 |
|---|---|---|
T | unknown[] | 投入 array 类型. |
参数
| 参数 | 类型 | 说明 |
|---|---|---|
array | T[] | 原始阵. |
options | ChunkIntoOptions | 定义分割标准的对象. |
options.size | number | 将分割给定的阵列,以确保每个块长度尽可能与给定的值相等. |
options.count | number | 将分割给定的矩阵, 以确保 n 块作为给定值 . |
回返
类型 : T[]
一大堆块.
使用量
基本用途
import { chunkInto } from '@alessiofrittoli/web-utils'
console.log(chunkInto([1, 2, 3, 4, 5], { count: 2 }))
// Output: [ [ 1, 2, 3 ], [ 4, 5 ] ]
console.log(chunkInto([1, 2, 3, 4, 5], { size: 2 }))
// Output: [ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]
shuffle
使用 Fisher- Yates 算法。 。 。 .
请注意,此函数修改了原给定的 array。 。 。 .
类型参数
| 参数 | 说明 |
|---|---|
T | 数组中自动推断的元素类型. |
参数
| 参数 | 类型 | 说明 |
|---|---|---|
array | Array<T> | 要洗牌的阵列 . |
回返
类型 : Array<T>
已修改的洗牌阵列 .
示例
import { shuffle } from '@alessiofrittoli/web-utils'
console.log(shuffle([1, 2, 3, 4, 5]))
shuffleCopy
使用 Fisher- Yates 算法。 。 。 .
同样的 API shuffle ,但此函数 不修改 给定的原件 array。 。 。 .
normalizeIndex
将负指数规范为正值.
参数
| 参数 | 类型 | 说明 |
|---|---|---|
index | number | 索引. |
length | number | 阵列长度 . |
回返
类型 : number
正常指数.
实例
import { normalizeIndex } from '@alessiofrittoli/web-utils'
const array = [0, 1, 2, 3]
console.log(normalizeIndex(2, array.length)) // Outputs: 2
console.log(normalizeIndex(-1, array.length)) // Outputs: 3
console.log(normalizeIndex(-3, array.length)) // Outputs: 1
getPreviousIndex
获得上个索引.
参数
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
length | number | - 说吧 | 阵列长度 . |
index | number | 0 | 索引. |
回返
类型 : number
上个索引.
实例
import { getPreviousIndex } from '@alessiofrittoli/web-utils'
const array = [0, 1, 2, 3]
console.log(getPreviousIndex(array.length, 2)) // Outputs: 1
console.log(getPreviousIndex(array.length, -1)) // Outputs: 2
console.log(getPreviousIndex(array.length, -3)) // Outputs: 0
getNextIndex
获得下个索引.
参数
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
length | number | - 说吧 | 阵列长度 . |
index | number | 0 | 索引. |
回返
类型 : number
下个索引.
实例
import { getNextIndex } from '@alessiofrittoli/web-utils'
const array = [0, 1, 2, 3]
console.log(getNextIndex(array.length, 2)) // Outputs: 3
console.log(getNextIndex(array.length, -1)) // Outputs: 0
console.log(getNextIndex(array.length, -3)) // Outputs: 2
insertAfter
在指定的索引位置将一个或多个项目插入数组.
类型参数
T数组中的元素类型.
参数
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
array | T[] | - 说吧 | 插入项的原始数组 . |
item | T|T[] | 0 个 | 要插入的单个项目或一系列项目. |
index | number | -1 | 插入项目后的索引. |
回返
类型 : T[]
在指定位置插入项的新阵列 .
实例
import { insertAfter } from '@alessiofrittoli/web-utils'
console.log(insertAfter([1, 2, 3, 4], 5)) // Outputs: [ 1, 2, 3, 4, 5 ]
console.log(insertAfter(['a', 'c'], 'b', 0)) // Outputs: [ 'a', 'b', 'c' ]
console.log(insertAfter(['a', 'b', 'c', 'e'], 'd', -2)) // Outputs: [ 'a', 'b', 'c', 'd', 'e' ]
findIndexBy
查找首个对象的索引,该对象的选定字段严格等于所提供的值.
类型参数
T存储在阵列中的对象类型 .U关键T用于比较.
参数
| 参数 | 类型 | 说明 |
|---|---|---|
options | FindInxeByOptions<T, U> | 搜索选项 . |
options.items | T[] | 取所取所取来取取取. |
options.field | U | 要比较的对象字段 value。 。 。 . |
options.value | T[U] | 必须匹配选定字段的值 . |
回返
类型 : number
匹配项的索引,或 -1 当找不到匹配时.
实例
import { findIndexBy } from '@alessiofrittoli/web-utils'
const users = [
{ id: 1, name: 'Ada' },
{ id: 2, name: 'Grace' },
{ id: 3, name: 'Linus' },
]
console.log(findIndexBy({ items: users, field: 'id', value: 2 })) // Outputs: 1
console.log(findIndexBy({ items: users, field: 'name', value: 'Linus' })) // Outputs: 2
console.log(findIndexBy({ items: users, field: 'id', value: 9 })) // Outputs: -1
公用事业
downloadBlob
创建并下载 blob 对象 .
参数
| 参数 | 类型 | 说明 |
|---|---|---|
filename | string | 下载文件名. |
data | BodyInit | 下载文件数据 . |
init | ResponseInit | (可选)应答Init对象. |
使用量
从 HTTP 响应下载文件
import { downloadBlob } from '@alessiofrittoli/web-utils'
fetch( ... )
.then( response => response.formData() )
.then( async data => {
await Promise.all(
Array.from( data.entries() )
.map( async ( [, file ] ) => {
if ( ! ( file instanceof File ) ) return
await downloadBlob( file.name, file )
} )
)
} )
.catch( error => {
console.error( error )
} )
多姆公用事业
滚动公用事业
blockScroll
防止元素流出.
它计算出滚动条宽度,由此产生的值被应用到目标元素右上贴-右上来防止宽度增大.
它还适用 --scrollbar-size CSS变量,可用于对目标内的位置固定元素应用贴补右.
参数
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
target | HTMLElement | Document.documentElement | (可选)目标元素. |
使用量
弹出时屏蔽文档 HTML 滚动
import { blockScroll } from '@alessiofrittoli/web-utils/dom'
const openPopUpHandler = () => {
blockScroll()
// ... handle popup
}
.modal-wrapper {
position: fixed;
inset: 0;
padding-right: var(--scrollbar-size, 0);
}
特定 HTML 元素的块滚动
import { blockScroll } from '@alessiofrittoli/web-utils/dom'
const element = document.querySelector('.css-selector')
if (element) {
blockScroll(element)
}
restoreScroll
还原元素多流.
参数
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
target | HTMLElement | Document.documentElement | (可选)目标元素. |
使用量
弹出关闭时恢复文档 HTML 滚动
import { restoreScroll } from '@alessiofrittoli/web-utils/dom'
const closePopUpHandler = () => {
// ... handle close
restoreScroll()
}
恢复特定 HTML 元素的滚动
import { restoreScroll } from '@alessiofrittoli/web-utils/dom'
const element = document.querySelector('.css-selector')
if (element) {
restoreScroll(element)
}
样式表工具
类型
乌尔斯图表
代表一个 URL 样式表作为简单的 URL 输入, URL 对象或带有 URL 和获取配置选项的对象.
type UrlStylesheet =
| UrlInput
| {
/**
* The URL string or a URL object of the stylesheet to load.
*
*/
url: UrlInput
/**
* Indicates whether to fetch the given URL.
*
* @default false
*/
fetch?: boolean
}
样式
代表样式输入 .
type Style = UrlStylesheet | HTMLStyleElement | CSSStyleSheet | StyleSheetList
样式
代表单一样式对象或样式对象的数组.
type Styles = Style | Style[]
cloneStyleSheetList
CLones a StyleSheetList 或 CSSStyleSheets 的数组为一组 HTMLStyleElement 对象.
此函数从每个样式表提取 CSS 规则并创建相应的 <style>
包含序列化 CSS 文本的元素。 如果处理样式表时发生错误,
错误被记录,样式表被跳过.
参数
| 参数 | 类型 | 说明 |
|---|---|---|
styles | StyleSheetList|CSSStyleSheet[] | 来源 StyleSheetList 或数组 CSSStyleSheet 要复制的对象. |
回返
类型 : HTMLStyleElement[]
- 数组
HTMLStyleElement对象,每个对象包含来自源样式表的 CSS 规则. - 失败的样式表被过滤出而不包含在结果中 .
实例
import { cloneStyleSheetList } from '@alessiofrittoli/web-utils/stylesheet'
const styles = cloneStyleSheetList(document.styleSheets)
// do something with cloned stylesheets
// styles.forEach( style => shadowRoot.appendChild( style ) )
cloneStyleSheets
各种来源的克伦斯样式表变成新 HTMLStyleElement 节点.
- 当 URL 样式表有
fetch: true,样式表内容被取出并嵌入为内置 CSS. - 何时
fetch: false(默认),将生成链接元素. - URL 解析是通过
Url用于支持字符串和UrlInput对象格式.
参数
| 参数 | 类型 | 说明 |
|---|---|---|
styles | Styles | 样式源或样式源的数组. |
- 看到没 Styles 类型,用于列出可能的值. |
回返
类型 : Promise<CloneStyleSheetsReturn>
- 一个承诺,解决 一系列克隆
HTMLStyleElement财务报告和审定财务报表HTMLLinkElement节点. - 对于内行样式和样式SheetLists,返回
HTMLStyleElement节点. - 对于基于 URL 的样式表,返回
HTMLLinkElement节点(或HTMLStyleElement如果获取是true) (中文(简体) ). - 失败的操作被默默地忽略.
实例
克隆 StyleSheetList
import { cloneStyleSheets } from '@alessiofrittoli/web-utils/stylesheet'
const styles = await cloneStyleSheets(document.styleSheets)
// do something with cloned dcoument stylesheets
// styles.forEach( style => shadowRoot.appendChild( style ) )
从 URL 复制样式表
import { cloneStyleSheets } from '@alessiofrittoli/web-utils/stylesheet'
const styles = await cloneStyleSheets('/path-to-stylesheet-file.css')
const styles = await cloneStyleSheets({
url: '/path-to-stylesheet-file-2.css',
fetch: true,
})
const styles = await cloneStyleSheets([
'/path-to-stylesheet-file-3.css',
{ url: '/path-to-stylesheet-file-4.css', fetch: true },
])
发电机水电费
isGeneratorFunction
检查一个函数是否是一个 GeneratorFunction 或者说 AsyncGeneratorFunction。 。 。 .
参数
| 参数 | 类型 | 说明 |
|---|---|---|
reference | unknown | 要检查的功能 . |
回返
类型 : reference 实值 GeneratorFunction | AsyncGeneratorFunction
true如果给定reference是一个GeneratorFunction或者说AsyncGeneratorFunction。 。 。 .false否则.
isDefaultGeneratorFunction
检查一个函数是否是一个 GeneratorFunction。 。 。 .
参数
| 参数 | 类型 | 说明 |
|---|---|---|
reference | unknown | 要检查的功能 . |
回返
类型 : reference 实值 GeneratorFunction
true如果给定reference是一个GeneratorFunction。 。 。 .false否则.
isAsyncGeneratorFunction
检查一个函数是否是 AsyncGeneratorFunction。 。 。 .
参数
| 参数 | 类型 | 说明 |
|---|---|---|
reference | unknown | 要检查的功能 . |
回返
类型 : reference 实值 AsyncGeneratorFunction
true如果给定reference是一个AsyncGeneratorFunction。 。 。 .false否则.
isGeneratorObject<T>
检查引用是否为 a Generator 或者说 AsyncGenerator。 。 。 .
参数
| 参数 | 类型 | 说明 |
|---|---|---|
reference | unknown | 查询的参考文献. |
回返
类型 : reference 实值 Generator<T> | AsyncGenerator<T>
true如果给定reference是一个Generator或者说AsyncGenerator。 。 。 .false否则.
isDefaultGeneratorObject<T>
检查引用是否为 a Generator。 。 。 .
参数
| 参数 | 类型 | 说明 |
|---|---|---|
reference | unknown | 查询的参考文献. |
回返
类型 : reference 实值 Generator<T>
true如果给定reference是一个Generator。 。 。 .false否则.
isAsyncGeneratorObject<T>
检查引用是否为 AsyncGenerator。 。 。 .
参数
| 参数 | 类型 | 说明 |
|---|---|---|
reference | unknown | 查询的参考文献. |
回返
类型 : reference 实值 AsyncGenerator<T>
true如果给定reference是一个AsyncGenerator。 。 。 .false否则.
承诺公用事业
sleep
等待一个空洞的保证,在给定的时间之后解决.
参数
| 参数 | 类型 | 说明 |
|---|---|---|
time | number | 承诺完成后 以毫秒计的入睡时间. |
回返
类型 : Promise<void>
新的承诺,在指定时间之后得到解决.
使用量
import { sleep } from '@alessiofrittoli/web-utils'
const fn = async () => {
// ...
await sleep(2000)
// ...
}
deferTask
Defer任务所以主行脚不被屏蔽,以便快速地涂装并响应用户交互.
类型参数
| 参数 | 说明 |
|---|---|
T | 任务函数定义 . unknown 类型将由函数类型定义继承. |
U | 任务函数参数 . unknown 类型将由函数类型继承. |
参数
| 参数 | 类型 | 说明 |
|---|---|---|
task | T | 可调用的任务函数 . |
...args | U | 给定的参数 task 函数. |
回返
类型 : Promise<Awaited<ReturnType<T>>>
返回新承诺 task 结果一旦实现.
使用量
基本用途
import { deferTask } from '@alessiofrittoli/web-utils'
const myLongTask = () => {
...
}
button.addEventListener( 'click', () => {
deferTask( myLongTask )
} )
带有自定义参数
import { deferTask } from '@alessiofrittoli/web-utils'
const myLongTask = ( target: HTMLButtonElement ) => {
...
}
button.addEventListener( 'click', event => {
const target = event.target as HTMLButtonElement
deferTask( myLongTask, target )
} )
deferCallback
延后任务处理器如此主行不被屏蔽,以便能快速地作画并响应用户交互.
类型参数
| 参数 | 说明 |
|---|---|
T | 任务函数定义 . unknown 类型将由函数类型定义继承. |
U | 任务函数参数 . unknown 类型将由函数类型继承. |
参数
| 参数 | 类型 | 说明 |
|---|---|---|
task | T | 可调用的任务函数 . |
回返
类型 : ( ...args: U ) => Promise<Awaited<ReturnType<T>>>
一个新的处理器,它返回一个新的承诺,返回 task 结果一旦实现.
使用量
import { deferCallback } from '@alessiofrittoli/web-utils'
const myLongTask = ( event: Event ) => {
...
}
button.addEventListener( 'click', deferCallback( myLongTask ) )
字符串公用事业
ucFirst
写出第一个字母大写 .
参数
| 参数 | 类型 | 说明 |
|---|---|---|
input | string | 要转换的输入字符串 . |
回返
类型 : string
处理过的字符串 .
使用量
import { ucFirst } from '@alessiofrittoli/web-utils'
console.log(ucFirst('String value')) // Outputs: 'String value'
console.log(ucFirst('string value')) // Outputs: 'String value'
lcFirst
使第一个字母小写.
参数
| 参数 | 类型 | 说明 |
|---|---|---|
input | string | 要转换的输入字符串 . |
回返
类型 : string
处理过的字符串 .
使用量
import { lcFirst } from '@alessiofrittoli/web-utils'
console.log(lcFirst('String value')) // Outputs: 'string value'
console.log(lcFirst('string value')) // Outputs: 'string value'
toCamelCase
将字符串转换为骆驼Case .
参数
| 参数 | 类型 | 说明 |
|---|---|---|
input | string | 要转换的输入字符串 . |
回返
类型 : string
转换为骆驼Case的字符串 .
使用量
import { toCamelCase } from '@alessiofrittoli/web-utils'
console.log(toCamelCase('font-family')) // Outputs: 'fontFamily'
console.log(toCamelCase('background-color')) // Outputs: 'backgroundColor'
console.log(toCamelCase('-webkit-align-content')) // Outputs: 'WebkitAlignContent'
console.log(toCamelCase('some value')) // Outputs: 'someValue'
console.log(toCamelCase('some_value')) // Outputs: 'someValue'
console.log(toCamelCase('some value_with mixed_Cases')) // Outputs: 'someValueWithMixedCases'
console.log(toCamelCase('-string@with#special$characters')) // Outputs: 'StringWithSpecialCharacters'
toKebabCase
将字符串转换为 kebab- case 字符串 .
参数
| 参数 | 类型 | 说明 |
|---|---|---|
input | string | 要转换的输入字符串 . |
回返
类型 : string
转换为 kebab 的字符串 .
使用量
import { toKebabCase } from '@alessiofrittoli/web-utils'
console.log(toKebabCase('fontFamily')) // Outputs: 'font-family'
console.log(toKebabCase('backgroundColor')) // Outputs: 'background-color'
console.log(toKebabCase('string with spaces')) // Outputs: 'string-with-spaces'
console.log(toKebabCase('string_with_underscores')) // Outputs: 'string-with-underscores'
console.log(toKebabCase('WebkitAlignContent')) // Outputs: '-webkit-align-content'
console.log(toKebabCase('some value_with mixed_Cases')) // Outputs: 'some-value-with-mixed-cases'
console.log(toKebabCase('-string@with#special$characters')) // Outputs: '-string-with-special-characters
stringifyValue
字符串值 .
参数
| 参数 | 类型 | 说明 |
|---|---|---|
input | any | 字符串的值 . |
回返
类型 : string
字符串 input。 。 。 .
使用量
import { stringifyValue } from '@alessiofrittoli/web-utils'
console.log(stringifyValue(new Date('Sat, 20 Apr 2025 16:20:00 GMT')))
// Outputs: '2025-04-20T16:20:00.000Z'
console.log(stringifyValue(null))
// Outputs: 'null'
console.log(stringifyValue({ prop: 'value', prop2: true }))
// Outputs: '{"prop":"value","prop2":true}'
console.log(stringifyValue([1, 2, true, null, () => {}]))
// Outputs: '[1,2,true,null,null]'
console.log(
stringifyValue(
new Map([
['key', 'value'],
['key2', 'value'],
]),
),
)
// Outputs: '[["key","value"],["key2","value"]]'
console.log(
stringifyValue(
new Headers({
key: 'value',
key2: 'value',
}),
),
)
// Outputs: '[["key","value"],["key2","value"]]'
console.log(stringifyValue(true)) // Outputs: 'true'
console.log(stringifyValue(false)) // Outputs: 'false'
console.log(stringifyValue(0)) // Outputs: '0'
console.log(stringifyValue(420)) // Outputs: '420'
console.log(stringifyValue(undefined)) // Outputs: ''
console.log(stringifyValue(() => {})) // Outputs: ''
console.log(stringifyValue(new Promise<void>(resolve => resolve()))) // Outputs: ''
parseValue
解析字符串值 .
类型参数
| 参数 | 说明 |
|---|---|
T | 预期返回的值类型 . |
参数
| 参数 | 类型 | 说明 |
|---|---|---|
input | string | 分析的价值. |
回返
类型 : T | undefined
- 解析
input。 。 。 . undefined若无input或为空string给出.
使用量
import { parseValue } from '@alessiofrittoli/web-utils'
console.log(parseValue<Date>(stringifyValue(new Date())))
// Outputs: current Date object.
console.log(parseValue<number>('12345')) // Outputs: 12345
console.log(parseValue()) // Outputs: undefined
console.log(parseValue(' ')) // Outputs: undefined
console.log(parseValue<true>(stringifyValue(true)))
// Outputs: true
console.log(parseValue(stringifyValue({ key: 'value' })))
// Outputs: { key: 'value' }
console.log(parseValue(stringifyValue([1, 2, 3, 4, 5])))
// Outputs: [ 1, 2, 3, 4, 5 ]
console.log(parseValue('String value')) // Outputs: 'String value'
parameterized
创建一个带有占位符值的参数化字符串.
类型
ParameterizedValue
表示字符串操作中可以用作参数的值.
type ParameterizedValue = string | boolean | number | bigint
Parameterized
以相应的数值表示参数化字符串.
type Parameterized = [string, ParameterizedValue[]]
实例
import { parameterized } from '@alessiofrittoli/web-utils'
const data = {
value: 'parameterized',
}
console.log(parameterized`My string with ${data.value} values.`) // [ 'My string with ? values.', [ 'parameterized' ] ]
公用事业类型
医生马上就来了
核证公用事业
医生马上就来了
公用事业
医生马上就来了
浏览器 API 工具
getMediaMatches
安全执行 window.matchMedia() 在服务器和浏览器环境中.
参数
| 参数 | 类型 | 说明 |
|---|---|---|
query | string | 媒体查询字符串要检查 . |
回返
类型 : boolean
false若为window未定义或如果document目前不匹配给定的query。 。 。 .true否则.
使用量
检查当前设备是否面向地貌
import { getMediaMatches } from '@alessiofrittoli/web-utils'
console.log(!getMediaMatches('(orientation:portrait)'))
openBrowserPopUp
在浏览器 PopUp 中打开网页.
这个 openBrowserPopUp 用途 Window.open() 但提供默认选项 让你的工作更容易.
[尖叫声]
需要安装以下软件包:
参数
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
options | OpenBrowserPopUpOptions | - 说吧 | 定义自定义弹出选项的对象 . |
options.url | UrlInput | - 说吧 | 要加载的资源的 URL 或路径 。 见 用户输入 需要更多关于公认格式的信息. |
options.width | number | 600 | 弹出宽度. |
options.height | number | 800 | 弹出地高. |
options.context | string | - 说吧 | 一个字符串,没有空白,指定正在装入资源的浏览上下文的名称. |
options.features | OptionsFeatures | - 说吧 | 额外的自定义 PopUp 特性 . |
回返
类型 : WindowProxy | null
- (单位:千美元)
WindowProxy如果浏览器成功打开了新的浏览上下文,则返回对象. null如果浏览器无法打开新的浏览上下文, 则返回, 例如因为它被浏览器弹出屏蔽.
使用量
重聚焦先前打开的弹出
import { openBrowserPopUp } from '@alessiofrittoli/web-utils/browser-popup'
let windowProxy: WindowProxy | null = null
const clickHandler = () => {
if (windowProxy && !windowProxy.closed) {
return windowProxy.focus()
}
windowProxy = openBrowserPopUp({
url: {
pathname: '/',
query: { key: 'value' },
},
})
}
重新使用弹出
import { openBrowserPopUp } from '@alessiofrittoli/web-utils/browser-popup'
const clickHandler = () => {
openBrowserPopUp({
context: 'some-context-name',
url: {
pathname: '/',
query: { key: 'value' },
},
})
}
const clickHandler2 = () => {
openBrowserPopUp({
context: 'some-context-name',
url: '/other-path',
})
}
文档图片
[尖叫声]
需要安装以下软件包:
类型
OpenDocumentPictureInPictureOptions
定义打开文档相册窗口的配置选项.
属性
| 财产 | 类型 | 默认 | 说明 |
|---|---|---|---|
sizes | InputDimensions | [ 250, 250 ] | 表示要设置的宽度和高度的非负数的倒数 |
| 为 Picture 窗口的取景口,以像素为单位. | |||
- 看到没 InputDimensions 类型,用于列出可能的值. | |||
disallowReturnToOpener | boolean | false | 提示浏览器它不应显示允许 |
| 用户返回原标签并关闭 Picture 窗口. | |||
preferInitialWindowPlacement | boolean | false | 定义 Picture 窗口是否总是出现在 |
| 它最初开放的位置和大小,在关闭后重新开放. | |||
相反,如果 preferInitialWindowPlacement 实值 false 页:1 | |||
| 关闭时会记住图片内窗口的大小和位置 | |||
| 并重新开放——它将按以前的立场和规模重新开放, | |||
| 例如用户设置的. | |||
styles | Styles | - 说吧 | 自定义在 Picture 窗口内加载的样式 . |
- 看到没 Styles 类型,用于列出可能的值. | |||
| QQ 为了与您的网页应用程序保持一致的样式,文档样式会自动被克隆. | |||
onQuit | () => void | - 说吧 | 当 Picture- in- Picture 窗口关闭时, 要执行的回调 . |
OpenDocumentPictureInPicture
定义打开文档相册窗口的返回结果.
属性
| 财产 | 类型 | 说明 |
|---|---|---|
window | Window | 文档 Picture 窗口内的浏览上下文 . |
isDocumentPictureInPictureSupported
检查文档 Picture API 是否得到当前浏览器的支持 .
回返
类型 : boolean
true如果支持文档中的图片.false否则.
实例
import { isDocumentPictureInPictureSupported } from "@alessiofrittoli/web-utils/picture-in-picture";
if ( isDocumentPictureInPictureSupported() ) {
...
}
requiresDocumentPictureInPictureAPI
验证文档 Picture API 由当前浏览器支持 .
- 扔出一个新的
Exception有代码ErrorCode.DOCUMENT_PIP_NOT_SUPPORTED如果文档中的图片不支持 API.
实例
import { Exception } from "@alessiofrittoli/exception";
import { requiresDocumentPictureInPictureAPI, ErrorCode } from "@alessiofrittoli/web-utils/picture-in-picture";
const myFunction = () => {
requiresDocumentPictureInPictureAPI()
...
}
try {
myFunction()
} catch ( _err ) {
const err = _err as Error
const error = (
Exception.isException<string, ErrorCode>(err)
? err
: (
new Exception(
err.message,
{
code : ErrorCode.UNKNOWN,
name : err.name,
cause : err,
}
)
)
)
switch ( error.code ) {
case ErrorCode.DOCUMENT_PIP_NOT_SUPPORTED:
console.warn( 'Document Picture-in-Picture is not supported.' )
break
default:
console.error( 'Unknown error', error )
}
}
openDocumentPictureInPicture
打开文档中图片窗口.
- 扔出一个新的
Exception有代码ErrorCode.DOCUMENT_PIP_NOT_SUPPORTED如果文档中的图片不支持 API.
参数
| 参数 | 类型 | 说明 |
|---|---|---|
options | OpenDocumentPictureInPictureOptions | 打开新文档相册窗口的配置选项 . |
回返
类型 : Promise<OpenDocumentPictureInPicture>
- 一个新的承诺,解决文件图片和图片结果
window的上下文.
实例
简单使用
import { openDocumentPictureInPicture, ErrorCode } from '@alessiofrittoli/web-utils/picture-in-picture'
import { Exception } from '@alessiofrittoli/exception'
const openPictureInPicture = async () => {
try {
const content = document.createElement('div')
const { window } = await openDocumentPictureInPicture()
window.document.body.appendChild(content)
} catch (_err) {
const err = _err as Error
const error = Exception.isException<string, ErrorCode>(err)
? err
: new Exception(err.message, {
code: ErrorCode.UNKNOWN,
name: err.name,
cause: err,
})
switch (error.code) {
case ErrorCode.DOCUMENT_PIP_NOT_SUPPORTED:
console.warn('Document Picture-in-Picture is not supported.')
break
default:
console.error('Unknown error', error)
}
}
}
装入渲染屏蔽样式
import { openDocumentPictureInPicture, ErrorCode } from '@alessiofrittoli/web-utils/picture-in-picture'
import { Exception } from '@alessiofrittoli/exception'
const openPictureInPicture = async () => {
try {
const content = document.createElement('div')
const { window } = await openDocumentPictureInPicture({
styles: {
url: '/important-stylesheet-fetched-before-opening.css',
fetch: true,
},
})
window.document.body.appendChild(content)
} catch (error) {
// ...
}
}
设备公用事业
isPortrait
检查设备是否在肖像取向中 .
回返
类型 : boolean
true如果设备在执行此函数时处于肖像取向.false否则.
使用量
检查当前设备是否面向地貌
import { isPortrait } from '@alessiofrittoli/web-utils'
console.log(!isPortrait())
网络信息
类型
Connection 接口
缺陷网络状态和 NetworkInformation。 。 。 .
属性
| 财产 | 类型 | 说明 |
|---|---|---|
network | NetworkInformation | 这个 NetworkInformation 接口 网络信息 API |
| 提供设备用于通信的连接信息 | ||
| 与网络连接,并提供一个在连接类型发生变化时通知脚本的手段. | ||
| * 可用性有限 见完全兼容 | ||
onLine | boolean | 显示设备是否连接到网络. |
| - 看到没 正在监听网络状态的变化。 。 。 . |
getConnection
获取当前网络状态和信息 .
实例
import { getConnection } from '@alessiofrittoli/web-utils'
const { network } = getConnection()
console.log(network?.effectiveType)
储存公用事业
Cookie 类
[尖叫声]
需要安装以下软件包:
导入enum和类型
import type { RawCookie, ParsedCookie, ParsedCookieMap } from '@alessiofrittoli/web-utils/cookie'
import { Priority, SameSite } from '@alessiofrittoli/web-utils/cookie'
数字
Priority 数字
Cookie优先级.
| 常数 | 数值 | 说明 |
|---|---|---|
Low | 低级 | 低优先级. |
Medium | 中型 | 中等优先权(默认). |
High | 高级 | 高优先级. |
SameSite 数字
控制是否发送有跨地点请求的饼干,为防范跨地点请求的伪造袭击提供某种保护(中国证监会) (中文(简体) ).
| 常数 | 数值 | 说明 |
|---|---|---|
Strict | 严格 | 浏览器只为同一站点请求发送饼干. |
Lax | 蜡 | 饼干不是根据跨站点请求发送的,比如关于加载图像或帧的请求,而是在用户从外部站点导航到发源地时发送. |
None | 无 | 浏览器发送的饼干同时带有跨站点和同站点请求. |
类型
RawCookie<K, V>
在解析前代表 Cookie 属性的接口 .
属性
| 财产 | 类型 | 说明 |
|---|---|---|
name | K | 饼干的名字. |
value | V | Cookie的价值. |
domain | string | 定义寄出饼干的主机. |
expires | string | number | Date | 表示饼干的最大寿命. |
httpOnly | boolean | 禁止 JavaScript 访问 cookie, 例如通过 Document.cookie 属性. |
maxAge | number | 表示到饼干到期为止的秒数。 如果设定, expires 被忽略. |
partitioned | boolean | 表示饼干应该使用分块存储来存储. |
path | string | 指定浏览器发送时必须在请求的 URL 中存在的路径 Cookie 头曰. |
sameSite | SameSite | 控制是否发送有跨地点请求的饼干,为防范跨地点请求的伪造袭击提供某种保护(中国证监会) (中文(简体) ). |
secure | boolean | 指出饼干只有在与 https: scheme 请求时才会发送到服务器. |
priority | Priority | 定义 Cookie 优先级 . |
ParsedCookie<K, V>
解析后代表 Cookie 属性的界面 .
ParsedCookieMap<K, V>
地图上的Cookie.
静态方法
Cookie.parse<K, V>()
将给定的饼干参数分析为 Cookie 地图 .
类型参数
| 参数 | 说明 |
|---|---|
K | 被打的饼干名称. |
V | 饼干值的类型 . |
参数
| 参数 | 类型 | 说明 |
|---|---|---|
options | RawCookie<K, V> | ParsedCookieMap<K, V> | 饼干选项或解析的Cookie地图. |
回返
类型 : ParsedCookieMap<K, V>
解析的Cookie地图.
使用量
import { Cookie } from '@alessiofrittoli/web-utils/cookie'
const cookie = Cookie.parse({
name: 'cookiename',
value: { test: 'value' },
path: '/specific-path',
priority: Priority.High,
expires: Date.now() + 20 * 60 * 1000,
domain: 'example.com',
secure: true,
httpOnly: true,
sameSite: SameSite.Lax,
maxAge: Date.now() + 30 * 60 * 1000,
partitioned: true,
})
Cookie.toString<K, V>()
将准备保存的 Cookie 绑定.
类型参数
| 参数 | 说明 |
|---|---|
K | 被打的饼干名称. |
V | 饼干值的类型 . |
参数
| 参数 | 类型 | 说明 |
|---|---|---|
options | RawCookie<K, V> | ParsedCookieMap<K, V> | 饼干选项或解析的Cookie地图. |
回返
类型 : string
已串起的 Cookie 准备储存 .
使用量
import { Cookie } from '@alessiofrittoli/web-utils/cookie'
document.cookie = Cookie.toString({
name: 'cookiename',
value: { test: 'value' },
path: '/specific-path',
priority: Priority.High,
expires: Date.now() + 20 * 60 * 1000,
domain: 'example.com',
secure: true,
httpOnly: false,
sameSite: SameSite.Lax,
maxAge: Date.now() + 30 * 60 * 1000,
partitioned: true,
})
Cookie.fromString<K, V>()
把饼干串分析成饼干地图.
类型参数
| 参数 | 说明 |
|---|---|
K | 被打的饼干名称. |
V | 预期的饼干价值类型 . |
参数
| 参数 | 类型 | 说明 |
|---|---|---|
cookie | string | 饼干串. |