refactor: add prettier and format

This commit is contained in:
Hufe921
2023-07-18 20:33:59 +08:00
parent 9c2bd33b7a
commit d464c50435
158 changed files with 3749 additions and 2265 deletions
+77 -29
View File
@@ -1,8 +1,17 @@
import { IEditorOption, IElement, ListStyle, ListType, RowFlex } from '..'
import { ZERO } from '../dataset/constant/Common'
import { INLINE_NODE_NAME, TEXTLIKE_ELEMENT_TYPE } from '../dataset/constant/Element'
import { listStyleCSSMapping, listTypeElementMapping } from '../dataset/constant/List'
import { titleNodeNameMapping, titleOrderNumberMapping } from '../dataset/constant/Title'
import {
INLINE_NODE_NAME,
TEXTLIKE_ELEMENT_TYPE
} from '../dataset/constant/Element'
import {
listStyleCSSMapping,
listTypeElementMapping
} from '../dataset/constant/List'
import {
titleNodeNameMapping,
titleOrderNumberMapping
} from '../dataset/constant/Title'
import { ControlComponent } from '../dataset/enum/Control'
import { ElementType } from '../dataset/enum/Element'
import { DeepRequired } from '../interface/Common'
@@ -37,13 +46,19 @@ export function writeClipboardItem(text: string, html: string) {
}
}
export function convertElementToDom(element: IElement, options: DeepRequired<IEditorOption>): HTMLElement {
export function convertElementToDom(
element: IElement,
options: DeepRequired<IEditorOption>
): HTMLElement {
let tagName: keyof HTMLElementTagNameMap = 'span'
if (element.type === ElementType.SUPERSCRIPT) {
tagName = 'sup'
} else if (element.type === ElementType.SUBSCRIPT) {
tagName = 'sub'
} else if (element.rowFlex === RowFlex.CENTER || element.rowFlex === RowFlex.RIGHT) {
} else if (
element.rowFlex === RowFlex.CENTER ||
element.rowFlex === RowFlex.RIGHT
) {
tagName = 'p'
}
const dom = document.createElement(tagName)
@@ -69,7 +84,10 @@ export function convertElementToDom(element: IElement, options: DeepRequired<IEd
return dom
}
export function writeElementList(elementList: IElement[], options: DeepRequired<IEditorOption>) {
export function writeElementList(
elementList: IElement[],
options: DeepRequired<IEditorOption>
) {
function buildDomFromElementList(payload: IElement[]): HTMLDivElement {
const clipboardDom = document.createElement('div')
for (let e = 0; e < payload.length; e++) {
@@ -105,12 +123,18 @@ export function writeElementList(elementList: IElement[], options: DeepRequired<
}
clipboardDom.append(a)
} else if (element.type === ElementType.TITLE) {
const h = document.createElement(`h${titleOrderNumberMapping[element.level!]}`)
const childDom = buildDomFromElementList(zipElementList(element.valueList!))
const h = document.createElement(
`h${titleOrderNumberMapping[element.level!]}`
)
const childDom = buildDomFromElementList(
zipElementList(element.valueList!)
)
h.innerHTML = childDom.innerHTML
clipboardDom.append(h)
} else if (element.type === ElementType.LIST) {
const list = document.createElement(listTypeElementMapping[element.listType!])
const list = document.createElement(
listTypeElementMapping[element.listType!]
)
if (element.listStyle) {
list.style.listStyleType = listStyleCSSMapping[element.listStyle]
}
@@ -134,7 +158,7 @@ export function writeElementList(elementList: IElement[], options: DeepRequired<
const listElementList = listElementListMap.get(curListIndex) || []
listElementList.push({
...zipElement,
value,
value
})
listElementListMap.set(curListIndex, listElementList)
}
@@ -166,9 +190,9 @@ export function writeElementList(elementList: IElement[], options: DeepRequired<
}
clipboardDom.append(checkbox)
} else if (
!element.type
|| element.type === ElementType.LATEX
|| TEXTLIKE_ELEMENT_TYPE.includes(element.type)
!element.type ||
element.type === ElementType.LATEX ||
TEXTLIKE_ELEMENT_TYPE.includes(element.type)
) {
let text = ''
if (element.type === ElementType.CONTROL) {
@@ -201,12 +225,15 @@ export function writeElementList(elementList: IElement[], options: DeepRequired<
writeClipboardItem(text, html)
}
export function convertTextNodeToElement(textNode: Element | Node): IElement | null {
export function convertTextNodeToElement(
textNode: Element | Node
): IElement | null {
if (!textNode || textNode.nodeType !== 3) return null
const parentNode = <HTMLElement>textNode.parentNode
const anchorNode = parentNode.nodeName === 'FONT'
? <HTMLElement>parentNode.parentNode
: parentNode
const anchorNode =
parentNode.nodeName === 'FONT'
? <HTMLElement>parentNode.parentNode
: parentNode
const rowFlex = getElementRowFlex(anchorNode)
const value = textNode.textContent
const style = window.getComputedStyle(anchorNode)
@@ -236,10 +263,13 @@ export function convertTextNodeToElement(textNode: Element | Node): IElement | n
}
interface IGetElementListByHTMLOption {
innerWidth: number;
innerWidth: number
}
export function getElementListByHTML(htmlText: string, options: IGetElementListByHTMLOption): IElement[] {
export function getElementListByHTML(
htmlText: string,
options: IGetElementListByHTMLOption
): IElement[] {
const elementList: IElement[] = []
function findTextNode(dom: Element | Node) {
if (dom.nodeType === 3) {
@@ -263,9 +293,11 @@ export function getElementListByHTML(htmlText: string, options: IGetElementListB
elementList.push({
type: ElementType.HYPERLINK,
value: '',
valueList: [{
value
}],
valueList: [
{
value
}
],
url: aElement.href
})
}
@@ -278,7 +310,10 @@ export function getElementListByHTML(htmlText: string, options: IGetElementListB
level: titleNodeNameMapping[node.nodeName],
valueList
})
if (node.nextSibling && !INLINE_NODE_NAME.includes(node.nextSibling.nodeName)) {
if (
node.nextSibling &&
!INLINE_NODE_NAME.includes(node.nextSibling.nodeName)
) {
elementList.push({
value: '\n'
})
@@ -294,7 +329,9 @@ export function getElementListByHTML(htmlText: string, options: IGetElementListB
listElement.listType = ListType.OL
} else {
listElement.listType = ListType.UL
listElement.listStyle = <ListStyle><unknown>listNode.style.listStyleType
listElement.listStyle = <ListStyle>(
(<unknown>listNode.style.listStyleType)
)
}
listNode.querySelectorAll('li').forEach(li => {
const liValueList = getElementListByHTML(li.innerHTML, options)
@@ -312,7 +349,7 @@ export function getElementListByHTML(htmlText: string, options: IGetElementListB
} else if (node.nodeName === 'HR') {
elementList.push({
value: '\n',
type: ElementType.SEPARATOR,
type: ElementType.SEPARATOR
})
} else if (node.nodeName === 'IMG') {
const { src, width, height } = node as HTMLImageElement
@@ -334,14 +371,19 @@ export function getElementListByHTML(htmlText: string, options: IGetElementListB
}
// 基础数据
tableElement.querySelectorAll('tr').forEach(trElement => {
const trHeightStr = window.getComputedStyle(trElement).height.replace('px', '')
const trHeightStr = window
.getComputedStyle(trElement)
.height.replace('px', '')
const tr: ITr = {
height: Number(trHeightStr),
tdList: []
}
trElement.querySelectorAll('th,td').forEach(tdElement => {
const tableCell = <HTMLTableCellElement>tdElement
const valueList = getElementListByHTML(tableCell.innerHTML, options)
const valueList = getElementListByHTML(
tableCell.innerHTML,
options
)
const td: ITd = {
colspan: tableCell.colSpan,
rowspan: tableCell.rowSpan,
@@ -358,7 +400,10 @@ export function getElementListByHTML(htmlText: string, options: IGetElementListB
})
if (element.trList!.length) {
// 列选项数据
const tdCount = element.trList![0].tdList.reduce((pre, cur) => pre + cur.colspan, 0)
const tdCount = element.trList![0].tdList.reduce(
(pre, cur) => pre + cur.colspan,
0
)
const width = Math.ceil(options.innerWidth / tdCount)
for (let i = 0; i < tdCount; i++) {
element.colgroup!.push({
@@ -367,7 +412,10 @@ export function getElementListByHTML(htmlText: string, options: IGetElementListB
}
elementList.push(element)
}
} else if (node.nodeName === 'INPUT' && (<HTMLInputElement>node).type === ControlComponent.CHECKBOX) {
} else if (
node.nodeName === 'INPUT' &&
(<HTMLInputElement>node).type === ControlComponent.CHECKBOX
) {
elementList.push({
type: ElementType.CHECKBOX,
value: '',
+88 -31
View File
@@ -4,7 +4,12 @@ import { LaTexParticle } from '../core/draw/particle/latex/LaTexParticle'
import { defaultCheckboxOption } from '../dataset/constant/Checkbox'
import { ZERO } from '../dataset/constant/Common'
import { defaultControlOption } from '../dataset/constant/Control'
import { EDITOR_ELEMENT_CONTEXT_ATTR, EDITOR_ELEMENT_ZIP_ATTR, TABLE_CONTEXT_ATTR, TEXTLIKE_ELEMENT_TYPE } from '../dataset/constant/Element'
import {
EDITOR_ELEMENT_CONTEXT_ATTR,
EDITOR_ELEMENT_ZIP_ATTR,
TABLE_CONTEXT_ATTR,
TEXTLIKE_ELEMENT_TYPE
} from '../dataset/constant/Element'
import { titleSizeMapping } from '../dataset/constant/Title'
import { ControlComponent, ControlType } from '../dataset/enum/Control'
import { ITd } from '../interface/table/Td'
@@ -22,17 +27,24 @@ export function unzipElementList(elementList: IElement[]): IElement[] {
}
interface IFormatElementListOption {
isHandleFirstElement?: boolean;
editorOptions: Required<IEditorOption>;
isHandleFirstElement?: boolean
editorOptions: Required<IEditorOption>
}
export function formatElementList(elementList: IElement[], options: IFormatElementListOption) {
export function formatElementList(
elementList: IElement[],
options: IFormatElementListOption
) {
const { isHandleFirstElement, editorOptions } = <IFormatElementListOption>{
isHandleFirstElement: true,
...options
}
const startElement = elementList[0]
if (isHandleFirstElement && startElement?.value !== ZERO && startElement?.value !== '\n') {
if (
isHandleFirstElement &&
startElement?.value !== ZERO &&
startElement?.value !== '\n'
) {
elementList.unshift({
value: ZERO
})
@@ -103,7 +115,10 @@ export function formatElementList(elementList: IElement[], options: IFormatEleme
const tr = el.trList[t]
const trId = getUUID()
tr.id = trId
if (!tr.minHeight || tr.minHeight < editorOptions.defaultTrMinHeight) {
if (
!tr.minHeight ||
tr.minHeight < editorOptions.defaultTrMinHeight
) {
tr.minHeight = editorOptions.defaultTrMinHeight
}
if (tr.height < tr.minHeight) {
@@ -163,7 +178,8 @@ export function formatElementList(elementList: IElement[], options: IFormatEleme
}
i--
} else if (el.type === ElementType.CONTROL) {
const { prefix, postfix, value, placeholder, code, type, valueSets } = el.control!
const { prefix, postfix, value, placeholder, code, type, valueSets } =
el.control!
const controlId = getUUID()
// 移除父节点
elementList.splice(i, 1)
@@ -198,7 +214,10 @@ export function formatElementList(elementList: IElement[], options: IFormatEleme
if (Array.isArray(valueSets) && valueSets.length) {
// 拆分valueList优先使用其属性
const valueStyleList = valueList.reduce(
(pre, cur) => pre.concat(cur.value.split('').map(v => ({ ...cur, value: v }))),
(pre, cur) =>
pre.concat(
cur.value.split('').map(v => ({ ...cur, value: v }))
),
[] as IElement[]
)
let valueStyleIndex = 0
@@ -241,9 +260,11 @@ export function formatElementList(elementList: IElement[], options: IFormatEleme
if (Array.isArray(valueSets) && valueSets.length) {
const valueSet = valueSets.find(v => v.code === code)
if (valueSet) {
valueList = [{
value: valueSet.value
}]
valueList = [
{
value: valueSet.value
}
]
}
}
}
@@ -299,7 +320,10 @@ export function formatElementList(elementList: IElement[], options: IFormatEleme
i++
}
i--
} else if ((!el.type || el.type === ElementType.TEXT) && el.value.length > 1) {
} else if (
(!el.type || el.type === ElementType.TEXT) &&
el.value.length > 1
) {
elementList.splice(i, 1)
const valueList = splitText(el.value)
for (let v = 0; v < valueList.length; v++) {
@@ -324,7 +348,10 @@ export function formatElementList(elementList: IElement[], options: IFormatEleme
}
}
export function isSameElementExceptValue(source: IElement, target: IElement): boolean {
export function isSameElementExceptValue(
source: IElement,
target: IElement
): boolean {
const sourceKeys = Object.keys(source)
const targetKeys = Object.keys(target)
if (sourceKeys.length !== targetKeys.length) return false
@@ -340,7 +367,7 @@ export function isSameElementExceptValue(source: IElement, target: IElement): bo
export function pickElementAttr(payload: IElement): IElement {
const element: IElement = {
value: payload.value === ZERO ? `\n` : payload.value,
value: payload.value === ZERO ? `\n` : payload.value
}
EDITOR_ELEMENT_ZIP_ATTR.forEach(attr => {
const value = payload[attr] as never
@@ -358,7 +385,11 @@ export function zipElementList(payload: IElement[]): IElement[] {
while (e < elementList.length) {
let element = elementList[e]
// 上下文首字符(占位符)
if (e === 0 && element.value === ZERO && (!element.type || element.type === ElementType.TEXT)) {
if (
e === 0 &&
element.value === ZERO &&
(!element.type || element.type === ElementType.TEXT)
) {
e++
continue
}
@@ -505,19 +536,20 @@ export function zipElementList(payload: IElement[]): IElement[] {
// 组合元素
const pickElement = pickElementAttr(element)
if (
!element.type
|| element.type === ElementType.TEXT
|| element.type === ElementType.SUBSCRIPT
|| element.type === ElementType.SUPERSCRIPT
!element.type ||
element.type === ElementType.TEXT ||
element.type === ElementType.SUBSCRIPT ||
element.type === ElementType.SUPERSCRIPT
) {
while (e < elementList.length) {
const nextElement = elementList[e + 1]
e++
if (
nextElement
&& isSameElementExceptValue(pickElement, pickElementAttr(nextElement))
nextElement &&
isSameElementExceptValue(pickElement, pickElementAttr(nextElement))
) {
const nextValue = nextElement.value === ZERO ? '\n' : nextElement.value
const nextValue =
nextElement.value === ZERO ? '\n' : nextElement.value
pickElement.value += nextValue
} else {
break
@@ -553,37 +585,62 @@ export function isTextLikeElement(element: IElement): boolean {
return !element.type || TEXTLIKE_ELEMENT_TYPE.includes(element.type)
}
export function getAnchorElement(elementList: IElement[], anchorIndex: number): IElement | null {
export function getAnchorElement(
elementList: IElement[],
anchorIndex: number
): IElement | null {
const anchorElement = elementList[anchorIndex]
if (!anchorElement) return null
const anchorNextElement = elementList[anchorIndex + 1]
// 非列表元素 && 当前元素是换行符 && 下一个元素不是换行符 则以下一个元素作为参考元素
return !anchorElement.listId && anchorElement.value === ZERO && anchorNextElement && anchorNextElement.value !== ZERO
return !anchorElement.listId &&
anchorElement.value === ZERO &&
anchorNextElement &&
anchorNextElement.value !== ZERO
? anchorNextElement
: anchorElement
}
export interface IFormatElementContextOption {
isBreakWhenWrap: boolean;
isBreakWhenWrap: boolean
}
export function formatElementContext(sourceElementList: IElement[], formatElementList: IElement[], anchorIndex: number, options?: IFormatElementContextOption) {
export function formatElementContext(
sourceElementList: IElement[],
formatElementList: IElement[],
anchorIndex: number,
options?: IFormatElementContextOption
) {
const copyElement = getAnchorElement(sourceElementList, anchorIndex)
if (!copyElement) return
const { isBreakWhenWrap = false } = options || {}
for (let e = 0; e < formatElementList.length; e++) {
const targetElement = formatElementList[e]
if (isBreakWhenWrap && !copyElement.listId && /^\n/.test(targetElement.value)) break
if (
isBreakWhenWrap &&
!copyElement.listId &&
/^\n/.test(targetElement.value)
) {
break
}
// 定位元素非列表,无需处理粘贴列表的上下文
if (!copyElement.listId && targetElement.type === ElementType.LIST) {
targetElement.valueList?.forEach((valueItem) => {
targetElement.valueList?.forEach(valueItem => {
cloneProperty<IElement>(TABLE_CONTEXT_ATTR, copyElement, valueItem)
})
continue
}
if (targetElement.valueList?.length) {
formatElementContext(sourceElementList, targetElement.valueList, anchorIndex)
formatElementContext(
sourceElementList,
targetElement.valueList,
anchorIndex
)
}
cloneProperty<IElement>(EDITOR_ELEMENT_CONTEXT_ATTR, copyElement, targetElement)
cloneProperty<IElement>(
EDITOR_ELEMENT_CONTEXT_ATTR,
copyElement,
targetElement
)
}
}
}
+1 -1
View File
@@ -2,4 +2,4 @@ import { isApple } from './ua'
export function isMod(evt: KeyboardEvent | MouseEvent) {
return isApple ? evt.metaKey : evt.ctrlKey
}
}
+66 -14
View File
@@ -18,9 +18,9 @@ export function deepClone<T>(obj: T): T {
if (Array.isArray(obj)) {
newObj = obj.map(item => deepClone(item))
} else {
Object.keys(obj as any).forEach((key) => {
Object.keys(obj as any).forEach(key => {
// @ts-ignore
return newObj[key] = deepClone(obj[key])
return (newObj[key] = deepClone(obj[key]))
})
}
return newObj
@@ -30,14 +30,16 @@ export function isBody(node: Element): boolean {
return node && node.nodeType === 1 && node.tagName.toLowerCase() === 'body'
}
export function findParent(node: Element, filterFn: Function, includeSelf: boolean) {
export function findParent(
node: Element,
filterFn: Function,
includeSelf: boolean
) {
if (node && !isBody(node)) {
node = includeSelf ? node : node.parentNode as Element
node = includeSelf ? node : (node.parentNode as Element)
while (node) {
if (!filterFn || filterFn(node) || isBody(node)) {
return filterFn && !filterFn(node) && isBody(node)
? null
: node
return filterFn && !filterFn(node) && isBody(node) ? null : node
}
node = node.parentNode as Element
}
@@ -49,7 +51,20 @@ export function getUUID(): string {
function S4(): string {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
}
return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4())
return (
S4() +
S4() +
'-' +
S4() +
'-' +
S4() +
'-' +
S4() +
'-' +
S4() +
S4() +
S4()
)
}
export function splitText(text: string): string[] {
@@ -71,13 +86,17 @@ export function threeClick(dom: HTMLElement, fn: (evt: MouseEvent) => any) {
nClickEvent(3, dom, fn)
}
function nClickEvent(n: number, dom: HTMLElement, fn: (evt: MouseEvent) => any) {
function nClickEvent(
n: number,
dom: HTMLElement,
fn: (evt: MouseEvent) => any
) {
let count = 0
let lastTime = 0
const handler = function (evt: MouseEvent) {
const currentTime = new Date().getTime()
count = (currentTime - lastTime < 300) ? count + 1 : 0
count = currentTime - lastTime < 300 ? count + 1 : 0
lastTime = new Date().getTime()
if (count >= n - 1) {
fn(evt)
@@ -119,8 +138,37 @@ export function nextTick(fn: Function) {
}
export function convertNumberToChinese(num: number) {
const chineseNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
const chineseUnit = ['', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万', '十', '百', '千', '亿']
const chineseNum = [
'零',
'一',
'二',
'三',
'四',
'五',
'六',
'七',
'八',
'九'
]
const chineseUnit = [
'',
'十',
'百',
'千',
'万',
'十',
'百',
'千',
'亿',
'十',
'百',
'千',
'万',
'十',
'百',
'千',
'亿'
]
if (!num || isNaN(num)) return '零'
const numStr = num.toString().split('')
let result = ''
@@ -138,7 +186,11 @@ export function convertNumberToChinese(num: number) {
return result
}
export function cloneProperty<T>(properties: (keyof T)[], sourceElement: T, targetElement: T) {
export function cloneProperty<T>(
properties: (keyof T)[],
sourceElement: T,
targetElement: T
) {
for (let i = 0; i < properties.length; i++) {
const property = properties[i]
const value = sourceElement[property]
@@ -156,4 +208,4 @@ export function convertStringToBase64(input: string) {
const charArray = Array.from(data, byte => String.fromCharCode(byte))
const base64 = window.btoa(charArray.join(''))
return base64
}
}
+15 -7
View File
@@ -1,4 +1,8 @@
export function printImageBase64(base64List: string[], width: number, height: number) {
export function printImageBase64(
base64List: string[],
width: number,
height: number
) {
const iframe = document.createElement('iframe')
// 离屏渲染
iframe.style.visibility = 'hidden'
@@ -28,10 +32,14 @@ export function printImageBase64(base64List: string[], width: number, height: nu
contentWindow.print()
doc.close()
// 移除iframe
window.addEventListener('mouseover', () => {
iframe?.remove()
}, {
once: true
})
window.addEventListener(
'mouseover',
() => {
iframe?.remove()
},
{
once: true
}
)
})
}
}
+2 -1
View File
@@ -1 +1,2 @@
export const isApple = typeof navigator !== 'undefined' && /Mac OS X/.test(navigator.userAgent)
export const isApple =
typeof navigator !== 'undefined' && /Mac OS X/.test(navigator.userAgent)