file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
.fatherrc.js
JavaScript
export default { cjs: 'babel', esm: { type: 'babel', importLibToEs: true }, preCommit: { eslint: true, prettier: true, }, };
zombieJ/malfurion
0
A svg control lib
TypeScript
zombieJ
二货爱吃白萝卜
alipay
assets/index.less
LESS
@footer-prefix-cls: rc-footer; .@{footer-prefix-cls} { position: relative; clear: both; color: rgba(255, 255, 255, 0.4); font-size: 14px; line-height: 1.5; background-color: #000; a { transition: all 0.3s; color: rgba(255, 255, 255, 0.9); text-decoration: none; &:hover { color: #40a9ff; } } &-container { width: 100%; max-width: 1200px; padding: 80px 0 20px; margin: auto; } &-columns { display: flex; justify-content: space-around; } &-column { margin-bottom: 60px; h2 { position: relative; margin: 0 auto 24px; font-weight: 500; font-size: 16px; color: #fff; } &-icon { margin-right: 0.5em; width: 22px; display: inline-block; vertical-align: middle; top: -1px; position: relative; text-align: center; > span, > svg, img { width: 100%; display: block; } } } &-item { margin: 12px 0; &-icon { margin-right: 0.4em; width: 16px; display: inline-block; vertical-align: middle; top: -1px; position: relative; text-align: center; > span, > svg, img { width: 100%; display: block; } } &-separator { margin: 0 0.3em; } } &-bottom { &-container { border-top: 1px solid rgba(255, 255, 255, 0.25); width: 100%; max-width: 1200px; text-align: center; margin: 0 auto; padding: 16px 0; line-height: 32px; font-size: 16px; } } &-light { background-color: transparent; color: rgba(0, 0, 0, 0.85); h2, a { color: rgba(0, 0, 0, 0.85); } } &-light &-bottom-container { border-top-color: #e8e8e8; } &-light &-item-separator, &-light &-item-description { color: rgba(0, 0, 0, 0.45); } } @media only screen and (max-width: 767.99px) { .@{footer-prefix-cls} { text-align: center; &-container { padding: 40px 0; } &-columns { display: block; } &-column { display: block; margin-bottom: 40px; &:last-child { margin-bottom: 0; } } } }
zombieJ/malfurion
0
A svg control lib
TypeScript
zombieJ
二货爱吃白萝卜
alipay
examples/basic.tsx
TypeScript (TSX)
import '../assets/index.less'; import React from 'react'; // import plantTXT from './svg/Plant'; import Malfurion from '../src'; import useElementSelection from './hooks/useElementSelection'; import Selection from './components/Selection'; // const svgText = plantTXT; // const svgText = ` // <svg> // <g transform="translate(150, 100)"> // <g transform="rotate(45 0 0)"> // <rect x="0" y="0" width="100" height="100" fill="green" /> // <circle cx="50" cy="50" r="10" fill="yellow" /> // </g> // </g> // <circle cx="50" cy="50" r="20" fill="red" /> // </svg> // `; const svgText = ` <svg> <defs> <radialGradient id="myGradient"> <stop offset="0%" stop-color="pink" /> <stop offset="100%" stop-color="black" /> </radialGradient> </defs> <circle cx="80" cy="80" r="20" fill="yellow" /> <g id="分组" transform="translate(150 100) scale(1.5)"> <rect id="方块1" x="0" y="0" width="40" height="100" fill="#00FF00" /> <rect x="0" y="80" width="50" height="20" fill="url(#myGradient)" stroke="#F00" opacity="0.5" /> </g> <text x="20" y="20" dominant-baseline="hanging" text-anchor="end">fg</text> </svg> `; const SC = '[{"path":[0],"rotate":30},{"path":[0,1],"rotate":27.72411817330965},{"path":[0,1,0],"rotate":315.9457209584655,"scaleX":2.9937769231279017,"scaleY":0.5168243503792648,"translateX":62.38341114458523,"translateY":-48.54876214439338}]'; const plant = new Malfurion(svgText); plant.debug = true; export default function App() { const svgRef = React.useRef<SVGSVGElement>(null); const [record, setRecord] = React.useState(SC); const selection = useElementSelection(); const hover = useElementSelection(selection.proxyRef); React.useEffect(() => { plant.addEventListener('click', ({ target }, instance) => { selection.updateSelection(instance, target); }); // plant.addEventListener('elementEnter', ({ target }, instance) => { // hover.updateSelection(instance, target); // }); // plant.addEventListener('elementLeave', (_, instance) => { // hover.updateSelection(instance, null); // }); svgRef.current!.appendChild(plant.getSVG()); }, []); return ( <div> <button type="button" onClick={() => { selection.transformCurrentPath((instance, path) => { instance.originX(path, Math.random()); instance.originY(path, Math.random()); }); }} > Random Origin </button> <button type="button" onClick={() => { selection.transformCurrentPath((instance, path) => { instance.rotate(path, origin => origin - 30); }); }} > RotateUp </button> <button type="button" onClick={() => { selection.transformCurrentPath((instance, path) => { instance.rotate(path, origin => origin + 30); }); }} > RotateDown </button> <button type="button" onClick={() => { selection.transformCurrentPath((instance, path) => { instance.scaleX(path, origin => origin + 0.1); }); }} > LargerX </button> <button type="button" onClick={() => { selection.transformCurrentPath((instance, path) => { instance.scaleY(path, origin => origin + 0.1); }); }} > LargerY </button> <button type="button" onClick={() => { selection.transformCurrentPath((instance, path) => { instance.translateX(path, origin => origin + 10); }); }} > TranslateX </button> <button type="button" onClick={() => { selection.transformCurrentPath((instance, path) => { instance.opacity(path, origin => (origin + 0.1) % 1); }); }} > Opacity </button> <button type="button" onClick={() => { const transform = plant.serializeTransform(); console.log(transform); setRecord(JSON.stringify(transform)); }} > Serialize </button> <button type="button" onClick={() => { plant.deserializeTransform(JSON.parse(record)); }} > Deserialize </button> <button type="button" onClick={() => { plant.reset(); }} > Reset </button> <button type="button" onClick={() => { console.log('Hierarchy:', plant.getHierarchy()); }} > Hierarchy </button> <button type="button" onClick={() => { selection.transformCurrentPath((instance, path) => { instance.fill(path, 'orange'); instance.stroke(path, 'cyan'); }); }} > Random Color </button> <br /> <svg width={500} height={500} viewBox="0 0 500 500" style={{ width: 500, height: 500, display: 'inline-block', background: 'rgba(255, 0, 0, 0.1)', }} > <g ref={svgRef} dangerouslySetInnerHTML={{ __html: '' }} /> <rect stroke="rgba(100, 100, 100, 0.5)" fill="rgba(255, 255, 255, 0.1)" style={{ pointerEvents: 'none' }} {...hover.boundingBox} /> <Selection selection={selection} /> </svg> <textarea value={record} style={{ width: 500, height: 300, verticalAlign: 'top' }} onChange={e => { setRecord(e.target.value); }} /> </div> ); }
zombieJ/malfurion
0
A svg control lib
TypeScript
zombieJ
二货爱吃白萝卜
alipay
examples/components/Selection/OperatePoint.tsx
TypeScript (TSX)
import React from 'react'; import { Point } from '../../../src/interface'; export type Position = 'lt' | 'rt' | 'lb' | 'rb'; export interface OperatePointProps { point: Point; size: number; stroke: string; position: Position; onMouseDown: (e: React.MouseEvent<SVGElement>, position: Position) => void; } export default ({ point, size, stroke, position, onMouseDown, }: OperatePointProps) => ( <circle style={{ cursor: 'pointer' }} fill="transparent" vectorEffect="non-scaling-stroke" cx={point.x} cy={point.y} r={size / 2} stroke={stroke} onMouseDown={e => { onMouseDown(e, position); }} /> );
zombieJ/malfurion
0
A svg control lib
TypeScript
zombieJ
二货爱吃白萝卜
alipay
examples/components/Selection/OriginPoint.tsx
TypeScript (TSX)
import React from 'react'; import { Point } from '../../../src/interface'; export interface OriginPointProps { point: Point; size: number; stroke: string; } export function OriginPoint({ point, size, stroke }: OriginPointProps) { const half = size / 2; return ( <g> <line x1={point.x - half} x2={point.x + half} y1={point.y} y2={point.y} stroke={stroke} strokeWidth={1} vectorEffect="non-scaling-stroke" /> <line x1={point.x} x2={point.x} y1={point.y - half} y2={point.y + half} stroke={stroke} strokeWidth={1} vectorEffect="non-scaling-stroke" /> </g> ); }
zombieJ/malfurion
0
A svg control lib
TypeScript
zombieJ
二货爱吃白萝卜
alipay
examples/components/Selection/RotateHandler.tsx
TypeScript (TSX)
import React from 'react'; import { Point } from '../../../src/interface'; export interface RotateHandlerProps { origin: Point; length: number; size: number; stroke: string; rotate: number; onMouseDown: React.MouseEventHandler<SVGElement>; } function RotateHandler( { origin, length, stroke, size, rotate, onMouseDown }: RotateHandlerProps, ref: React.RefObject<SVGRectElement | null>, ) { const centerRef = React.useRef<SVGRectElement>(null); React.useImperativeHandle(ref, () => centerRef.current); return ( <g transform={`rotate(${rotate} ${origin.x} ${origin.y})`}> <line x1={origin.x} y1={origin.y} x2={origin.x} y2={origin.y - length} stroke={stroke} style={{ pointerEvents: 'none' }} /> <circle cx={origin.x} cy={origin.y - length - size / 2} r={size / 2} fill="transparent" stroke={stroke} style={{ cursor: 'pointer' }} onMouseDown={onMouseDown} /> <rect x={origin.x} y={origin.y} width={1} height={1} fill="red" ref={centerRef} /> </g> ); } export default React.forwardRef(RotateHandler);
zombieJ/malfurion
0
A svg control lib
TypeScript
zombieJ
二货爱吃白萝卜
alipay
examples/components/Selection/index.tsx
TypeScript (TSX)
import React from 'react'; import { throttle } from 'lodash'; import { Matrix, Line } from '../../../src'; import useElementSelection from '../../hooks/useElementSelection'; import OperatePoint, { Position } from './OperatePoint'; import { OriginPoint } from './OriginPoint'; import RotateHandler from './RotateHandler'; export interface SelectionProps { selection: ReturnType<typeof useElementSelection>; originSize?: number; pointSize?: number; handlerSize?: number; stroke?: string; onTransform?: (matrix: Matrix) => {}; } interface Point { x: number; y: number; } interface SelectionState { startPoint: { x: number; y: number; } | null; // Origin origin: Point; // Operate position leftTop: Point; rightTop: Point; leftBottom: Point; rightBottom: Point; /** * Record user operation to render transform matrix. * This is same as matrix from `rotate` `scale` and `translate` * */ transformMatrix: Matrix; /** Control point */ control: null | 'lt' | 'rt' | 'lb' | 'rb' | 'rotate'; } class Selection extends React.Component<SelectionProps, SelectionState> { state: SelectionState = { startPoint: null, leftTop: { x: 0, y: 0 }, rightTop: { x: 0, y: 0 }, leftBottom: { x: 0, y: 0 }, rightBottom: { x: 0, y: 0 }, origin: { x: 0, y: 0 }, transformMatrix: Matrix.fromTranslate(), control: null, }; rotateRef = React.createRef<SVGRectElement>(); static getDerivedStateFromProps({ selection }: SelectionProps) { const newState: Partial<SelectionState> = {}; if (selection.boundingBox) { const { x, y, width, height, originX, originY } = selection.boundingBox; const transformMatrix = Matrix.fromTransformText( selection.boundingBox.mergedTransform!, ); // Origin newState.origin = transformMatrix.transformPosition( x + width * originX!, y + height * originY!, ); // Points newState.leftTop = transformMatrix.transformPosition(x, y); newState.rightTop = transformMatrix.transformPosition(x + width, y); newState.leftBottom = transformMatrix.transformPosition(x, y + height); newState.rightBottom = transformMatrix.transformPosition( x + width, y + height, ); } return newState; } constructor(props: SelectionProps) { super(props); this.onMouseMove = throttle(this.onMouseMove, 100); } componentDidMount() { document.addEventListener('mousemove', this.onMouseMove); document.addEventListener('mouseup', this.onMouseUp); } componentWillUnmount() { document.removeEventListener('mousemove', this.onMouseMove); document.removeEventListener('mouseup', this.onMouseUp); } onPointMouseDown = ( { clientX, clientY }: React.MouseEvent<SVGElement>, position: Position, ) => { this.setState({ control: position, startPoint: { x: clientX, y: clientY }, }); }; onRotateMouseDown: React.MouseEventHandler<SVGElement> = () => { if (this.rotateRef.current) { const { x, y } = this.rotateRef.current.getBoundingClientRect(); this.setState({ control: 'rotate', startPoint: { x, y }, }); } }; onMouseMove = ({ clientX, clientY }: MouseEvent) => { const { startPoint, leftTop, rightTop, // leftBottom, rightBottom, control, } = this.state; const { selection } = this.props; if (!startPoint || !selection.boundingBox) { return; } const offsetX = clientX - startPoint.x; const offsetY = clientY - startPoint.y; const { x, y, width, height } = selection.boundingBox; if (control === 'rotate') { const w = clientX - startPoint.x; const h = startPoint.y - clientY; let newRotate: number = 0; if (clientX === startPoint.x) { newRotate = clientY < startPoint.y ? 0 : 180; } else { newRotate = (Math.atan(w / h) / Math.PI) * 180; newRotate = (newRotate + 180) % 180; newRotate = clientX > startPoint.x ? newRotate : newRotate + 180; } selection.transformCurrentPath((instance, path) => { instance.rotate(path, newRotate); }); } else { const positionList = []; const topLine = Line.fromPoints(leftTop, rightTop); // const bottomLine = Line.fromPoints(leftBottom, rightBottom); // const leftLine = Line.fromPoints(leftTop, leftBottom); const rightLine = Line.fromPoints(rightTop, rightBottom); switch (control) { case 'rb': { // LT positionList.push({ source: { x, y }, target: leftTop, }); // RT const newRightLine = rightLine.translate(offsetX, offsetY); const crossPoint = topLine.crossPoint(newRightLine); positionList.push({ source: { x: x + width, y }, target: { x: crossPoint.x, y: crossPoint.y }, }); // RB positionList.push({ source: { x: x + width, y: y + height }, target: { x: rightBottom.x + offsetX, y: rightBottom.y + offsetY }, }); break; } default: // Do nothing } const transformMatrix = Matrix.backFromPosition(positionList); this.updateTransform(transformMatrix); this.setState({ startPoint: { x: clientX, y: clientY, }, }); } }; onMouseUp = () => { this.setState({ startPoint: null, control: null }); }; updateTransform = (transformMatrix: Matrix) => { const { selection } = this.props; const { startPoint } = this.state; if (selection.boundingBox && startPoint) { const { pureMergedTransform, x, y, width, height, originX, originY, rotate, } = selection.boundingBox; const source = Matrix.fromTransformText(pureMergedTransform!); const target = transformMatrix; // Get mixed transform matrix // source * mixTransformMatrix = target const mixTransformMatrix = target.leftDivide(source); const shapeInfo = { x, y, width, height, originX: originX!, originY: originY!, }; // console.warn('=> MixSrc:', mixTransformMatrix.toTransform()); // Get scaleX & scaleY const [a, b, c, d] = mixTransformMatrix.toTransform(); let scaleX = 0; let scaleY = 0; if (rotate === 90) { scaleX = b; scaleY = -c; } else if (rotate === 270) { scaleX = -b; scaleY = c; } else { const cosA = Math.cos((rotate! / 180) * Math.PI); scaleX = a / cosA; scaleY = d / cosA; } const scaleMatrix = Matrix.fromScale(scaleX, scaleY, shapeInfo); // Get translate // Translate * Rotate * Scale const rotateMatrix = Matrix.fromRotate(rotate!, shapeInfo); const translateRotateMatrix = mixTransformMatrix.rightDivide(scaleMatrix); const translateMatrix = translateRotateMatrix.rightDivide(rotateMatrix); const [, , , , translateX, translateY] = translateMatrix.toTransform(); // Test usage, not use in real case // const mixMatrix = Matrix.fromMixTransform({ // translateX, // translateY, // rotate: rotate!, // scaleX, // scaleY, // originX: originX!, // originY: originY!, // x, // y, // width, // height, // }); // console.warn('=> MixMok:', mixMatrix.toTransform()); selection.transformCurrentPath((instance, path) => { instance.scaleX(path, scaleX); instance.scaleY(path, scaleY); instance.translateX(path, translateX); instance.translateY(path, translateY); }); } }; render() { const { origin, leftTop, rightTop, leftBottom, rightBottom, // transformMatrix, } = this.state; const { selection, originSize = 10, pointSize = 6, handlerSize = 100, stroke = '#000', } = this.props; if (!selection.boundingBox) { return null; } // Box const boxProps = { x: selection.boundingBox.x, y: selection.boundingBox.y, width: selection.boundingBox.width, height: selection.boundingBox.height, transform: selection.boundingBox.mergedTransform, }; // Points const pointProps = { size: pointSize, stroke, fill: 'transparent', onMouseDown: this.onPointMouseDown, }; return ( <> {/* Selection Rect */} <rect stroke={stroke} strokeWidth={1} fill="transparent" style={{ pointerEvents: 'none' }} vectorEffect="non-scaling-stroke" {...boxProps} /> {/* <rect stroke="red" strokeWidth={1} fill="transparent" style={{ pointerEvents: 'none' }} vectorEffect="non-scaling-stroke" {...boxProps} transform={transformMatrix.toString()} /> */} {/* Origin Point */} <OriginPoint size={originSize} point={origin} stroke={stroke} /> {/* Rotate Handler */} <RotateHandler origin={origin} size={pointSize} length={handlerSize} stroke={stroke} rotate={selection.boundingBox.rotate || 0} onMouseDown={this.onRotateMouseDown} ref={this.rotateRef} /> {/* Points */} <OperatePoint {...pointProps} position="lt" point={leftTop} /> <OperatePoint {...pointProps} position="rt" point={rightTop} /> <OperatePoint {...pointProps} position="lb" point={leftBottom} /> <OperatePoint {...pointProps} position="rb" point={rightBottom} /> </> ); } } export default Selection;
zombieJ/malfurion
0
A svg control lib
TypeScript
zombieJ
二货爱吃白萝卜
alipay
examples/hooks/useElementSelection.ts
TypeScript
import React from 'react'; import Malfurion, { BoundingBox } from '../../src'; interface ProxyRef { current: Malfurion | null; currentPath: number[]; } export default function useElementSelection( overwriteProxyRef: React.RefObject<ProxyRef> = { current: null }, ) { const [boundingBox, setBoundingBox] = React.useState<BoundingBox | null>( null, ); const [current, setCurrent] = React.useState<Malfurion | null>(null); const [currentPath, setCurrentPath] = React.useState<number[]>([]); const proxyRef = React.useRef({ current, currentPath }); proxyRef.current = { current, currentPath, ...overwriteProxyRef.current, }; React.useEffect(() => { if (current) { setBoundingBox(current.getBox(currentPath)!); } }, [current, currentPath]); function updateSelection( instance: Malfurion, target: SVGGraphicsElement | null, ) { if (proxyRef.current.current !== instance) { setCurrent(instance); setCurrentPath([0]); } else { const path = instance.getPath(target) || []; // Need to get common shared path const commonPath = []; for (let i = 0; i < proxyRef.current.currentPath.length; i += 1) { const pos = proxyRef.current.currentPath[i]; if (pos === path[i]) { commonPath.push(pos); } else { break; } } setCurrentPath(path.slice(0, commonPath.length + 1)); } } function transformCurrentPath( callback: (instance: Malfurion, path: number[]) => void, ) { if (current && currentPath) { callback(current, currentPath); setBoundingBox(current.getBox(currentPath)!); } } return { boundingBox, updateSelection, proxyRef, transformCurrentPath, }; }
zombieJ/malfurion
0
A svg control lib
TypeScript
zombieJ
二货爱吃白萝卜
alipay
examples/svg/Plant.ts
TypeScript
/* eslint-disable max-len */ // export default ` // <?xml version="1.0" encoding="UTF-8"?> // <svg width="493px" height="841px" viewBox="0 0 493 841" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> // <!-- Generator: Sketch 63.1 (92452) - https://sketch.com --> // <title>通用/色彩/仙人掌盆栽</title> // <desc>植物,绿色</desc> // <g id="盆栽"> // <g id="叶子-5" transform="translate(0.000000, 383.049288)"> // <path d="M0.244140625,138.010226 C0.244140625,138.010226 -9.75585938,58.0102264 98.2441406,22.0102264 C206.244141,-13.9897736 230.244141,5.01022644 230.244141,5.01022644 L220.244141,37.0102264 C220.244141,37.0102264 203.244141,117.010226 125.244141,128.010226 C47.2441406,139.010226 17.2441406,123.010226 0.244140625,138.010226" id="Fill-1" fill="#7CB305"></path> // <path d="M218.664624,8.78339021 L221.823657,11.2370627 L221.562135,11.5648454 C221.448018,11.7054199 221.306922,11.8769517 221.138739,12.0783718 L220.639228,12.6691842 C220.28823,13.0795147 219.90122,13.5224903 219.478039,13.9965146 L219.15387,14.3578295 C216.95924,16.7920417 214.310858,19.4988517 211.201845,22.4097534 C202.340593,30.7063548 191.555432,38.9954165 178.791872,46.7274307 C153.160027,62.2549 122.894521,73.5416205 87.8322482,78.7975778 L86.5314519,78.9894819 C62.9312024,82.4153246 44.1247153,90.2550953 29.556905,101.163814 C22.5684542,106.396931 17.0223251,111.99495 12.7713039,117.581547 C11.2916081,119.52613 10.0809908,121.326176 9.12132463,122.934221 L8.80799692,123.468182 C8.66056649,123.72398 8.52692324,123.962838 8.40678383,124.184014 L8.07166596,124.824893 L8.0516163,124.866399 L4.43666495,123.154054 L4.54698756,122.928123 C4.77587113,122.471075 5.15188912,121.780158 5.68649892,120.88435 C6.7215491,119.149989 8.01576739,117.225638 9.58808517,115.159334 C14.0571027,109.286251 19.864428,103.424591 27.1593165,97.9620072 C42.0446522,86.8155175 61.1388503,78.78522 84.9199208,75.1847184 L85.9568351,75.0309701 C121.026964,69.9402491 151.217885,58.7547108 176.719347,43.3062264 C189.237541,35.7228522 199.803098,27.6025691 208.467979,19.4898258 C211.291438,16.8462815 213.718023,14.3823096 215.752959,12.1533906 L216.183024,11.6793831 C216.81561,10.9777388 217.367495,10.3452727 217.839184,9.78736121 L218.367211,9.15347178 L218.664624,8.78339021 Z" id="Stroke-3" fill="#BAE637" fill-rule="nonzero"></path> // <path d="M217.244141,192.010226 L230.244141,192.010226 L230.244141,5.01022644 L217.244141,5.01022644 L220.747141,62.4682264 C221.744141,78.8172264 221.853141,95.2092264 221.075141,111.570226 L217.244141,192.010226 Z" id="Fill-5" fill="#7CB305"></path> // </g> // </g> // </svg> // `; export default ` <?xml version="1.0" encoding="UTF-8"?> <svg width="493px" height="841px" viewBox="0 0 493 841" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- Generator: Sketch 63.1 (92452) - https://sketch.com --> <title>通用/色彩/仙人掌盆栽</title> <desc>植物,绿色</desc> <g id="盆栽"> <g id="叶子-5" transform="translate(0.000000, 383.049288)"> <path d="M0.244140625,138.010226 C0.244140625,138.010226 -9.75585938,58.0102264 98.2441406,22.0102264 C206.244141,-13.9897736 230.244141,5.01022644 230.244141,5.01022644 L220.244141,37.0102264 C220.244141,37.0102264 203.244141,117.010226 125.244141,128.010226 C47.2441406,139.010226 17.2441406,123.010226 0.244140625,138.010226" id="Fill-1" fill="#7CB305"></path> <path d="M218.664624,8.78339021 L221.823657,11.2370627 L221.562135,11.5648454 C221.448018,11.7054199 221.306922,11.8769517 221.138739,12.0783718 L220.639228,12.6691842 C220.28823,13.0795147 219.90122,13.5224903 219.478039,13.9965146 L219.15387,14.3578295 C216.95924,16.7920417 214.310858,19.4988517 211.201845,22.4097534 C202.340593,30.7063548 191.555432,38.9954165 178.791872,46.7274307 C153.160027,62.2549 122.894521,73.5416205 87.8322482,78.7975778 L86.5314519,78.9894819 C62.9312024,82.4153246 44.1247153,90.2550953 29.556905,101.163814 C22.5684542,106.396931 17.0223251,111.99495 12.7713039,117.581547 C11.2916081,119.52613 10.0809908,121.326176 9.12132463,122.934221 L8.80799692,123.468182 C8.66056649,123.72398 8.52692324,123.962838 8.40678383,124.184014 L8.07166596,124.824893 L8.0516163,124.866399 L4.43666495,123.154054 L4.54698756,122.928123 C4.77587113,122.471075 5.15188912,121.780158 5.68649892,120.88435 C6.7215491,119.149989 8.01576739,117.225638 9.58808517,115.159334 C14.0571027,109.286251 19.864428,103.424591 27.1593165,97.9620072 C42.0446522,86.8155175 61.1388503,78.78522 84.9199208,75.1847184 L85.9568351,75.0309701 C121.026964,69.9402491 151.217885,58.7547108 176.719347,43.3062264 C189.237541,35.7228522 199.803098,27.6025691 208.467979,19.4898258 C211.291438,16.8462815 213.718023,14.3823096 215.752959,12.1533906 L216.183024,11.6793831 C216.81561,10.9777388 217.367495,10.3452727 217.839184,9.78736121 L218.367211,9.15347178 L218.664624,8.78339021 Z" id="Stroke-3" fill="#BAE637" fill-rule="nonzero"></path> <path d="M217.244141,192.010226 L230.244141,192.010226 L230.244141,5.01022644 L217.244141,5.01022644 L220.747141,62.4682264 C221.744141,78.8172264 221.853141,95.2092264 221.075141,111.570226 L217.244141,192.010226 Z" id="Fill-5" fill="#7CB305"></path> </g> <g id="叶子-4" transform="translate(17.022941, 212.351603)"> <path d="M0,34.9071117 C0,34.9071117 39.805,-25.6218883 134.637,12.7311117 C229.468,51.0831117 234.221,81.7081117 234.221,81.7081117 L209.306,94.1151117 C209.306,94.1151117 151.041,138.903112 91.296,100.948112 C31.552,62.9931117 20.369,34.5621117 0,34.9071117" id="Fill-7" fill="#7CB305"></path> <path d="M221.2212,414.707912 L231.2212,414.707912 L235.1392,84.6039117 C235.1872,80.5329117 232.5052,76.9319117 228.5902,75.8129117 L221.2212,73.7079117 C221.2212,73.7079117 223.7322,104.379912 223.2212,142.706912 C222.7322,179.371912 219.2212,222.999912 219.2212,255.312912 C219.2212,346.707912 221.2212,414.707912 221.2212,414.707912" id="Fill-9" fill="#7CB305"></path> <path d="M135.221,32.7081117 C178.375,66.2001117 222.221,87.7081117 222.221,87.7081117 L209.306,94.1151117 C209.306,94.1151117 151.041,138.903112 91.296,100.948112 C31.552,62.9931117 20.369,34.5621117 0,34.9071117 C0,34.9071117 68.221,-19.2918883 135.221,32.7081117 Z" id="Fill-11" fill="#389E0D"></path> </g> <g id="叶子-3" transform="translate(326.000041, 367.000515)" fill="#7CB305"> <path d="M1,23.4293856 C1,23.4293856 27.8515206,-17.1972148 91.8229663,8.54502451 C155.793738,34.2865926 159,54.8418577 159,54.8418577 L142.192925,63.1693409 C142.192925,63.1693409 102.88872,93.2307028 62.586143,67.755598 C22.2842401,42.2804933 14.7404503,23.1978242 1,23.4293856" id="Fill-7" transform="translate(80.000000, 39.000000) scale(-1, 1) translate(-80.000000, -39.000000) "></path> <path d="M1.38202813,280 L8.29216879,280 L10.9995619,57.3492082 C11.0327306,54.6033724 9.17943086,52.1745455 6.47411079,51.4197947 L1.38202813,50 C1.38202813,50 3.11716445,70.6878592 2.76405626,96.538915 C2.42615039,121.268974 0,150.695484 0,172.490176 C0,234.134897 1.38202813,280 1.38202813,280" id="Fill-9" transform="translate(5.500000, 165.000000) scale(-1, 1) translate(-5.500000, -165.000000) "></path> </g> <g id="叶子-2" transform="translate(257.325507, 135.351603)"> <path d="M235.139834,34.9071117 C235.139834,34.9071117 195.334834,-25.6218883 100.502834,12.7311117 C5.67183399,51.0831117 0.918833988,81.7081117 0.918833988,81.7081117 L25.833834,94.1151117 C25.833834,94.1151117 84.098834,138.903112 143.843834,100.948112 C203.587834,62.9931117 214.770834,34.5621117 235.139834,34.9071117" id="Fill-13" fill="#7CB305"></path> <path d="M13.918634,427.707912 L3.91863399,427.707912 L0.000633987837,84.6039117 C-0.0473660122,80.5329117 2.63463399,76.9319117 6.54963399,75.8129117 L13.918634,73.7079117 C13.918634,73.7079117 11.407634,104.379912 11.918634,142.706912 C12.407634,179.371912 15.918634,222.999912 15.918634,255.312912 C15.918634,346.707912 13.918634,427.707912 13.918634,427.707912" id="Fill-15" fill="#7CB305"></path> <path d="M235.139834,34.9071117 C235.139834,34.9071117 166.918834,-19.2918883 99.918834,32.7081117 C56.764834,66.2001117 12.918834,87.7081117 12.918834,87.7081117 L25.833834,94.1151117 C25.833834,94.1151117 84.098834,138.903112 143.843834,100.948112 C203.587834,62.9931117 214.770834,34.5621117 235.139834,34.9071117" id="Fill-17" fill="#389E0D"></path> </g> <g id="叶子1" transform="translate(97.937541, 0.000000)"> <path d="M191.3066,560.059515 L208.3066,560.059515 L215.0306,347.539515 L202.2246,146.955515 C202.2726,142.884515 199.5906,139.283515 195.6756,138.164515 L188.3066,136.059515 C188.3066,136.059515 204.3066,295.351515 204.3066,327.664515 C204.3066,419.059515 191.3066,560.059515 191.3066,560.059515" id="Fill-19" fill="#7CB305"></path> <path d="M2.84217094e-14,23.8305146 C2.84217094e-14,23.8305146 36.307,-29.9404854 122.307,24.0595146 C208.938,78.4555146 202.923,149.814515 202.923,149.814515 L175.239,152.695515 C175.239,152.695515 104.966,174.199515 62.331,117.699515 C19.696,61.1995146 19.195,30.6525146 2.84217094e-14,23.8305146" id="Fill-21" fill="#7CB305"></path> <path d="M7.10542736e-14,23.8305146 C7.10542736e-14,23.8305146 39.084,-4.98048542 72.307,36.0595146 C89.307,57.0595146 119.383,72.8925146 132.307,85.0595146 C165.88,116.669515 189.581,151.224515 189.581,151.224515 L175.239,152.695515 C175.239,152.695515 104.966,174.199515 62.331,117.699515 C19.696,61.1995146 19.195,30.6525146 7.10542736e-14,23.8305146" id="Fill-23" fill="#389E0D"></path> </g> <path d="M384.000041,840.059515 L152.000041,840.059515 C138.745041,840.059515 128.000041,829.314515 128.000041,816.059515 L128.000041,584.059515 C128.000041,570.804515 138.745041,560.059515 152.000041,560.059515 L384.000041,560.059515 C397.255041,560.059515 408.000041,570.804515 408.000041,584.059515 L408.000041,816.059515 C408.000041,829.314515 397.255041,840.059515 384.000041,840.059515" id="花盆" fill="#253369"></path> </g> </svg> `; // export default ` // <?xml version="1.0" encoding="UTF-8"?> // <svg width="1024px" height="1024px" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> // <!-- Generator: Sketch 61.2 (89653) - https://sketch.com --> // <title>3.通用组件/彩色版/盆栽02</title> // <desc>Created with Sketch.</desc> // <defs> // <polygon id="path-1" points="0.0762258814 0.389734513 310.705093 0.389734513 310.705093 516.294073 0.0762258814 516.294073"></polygon> // <polygon id="path-3" points="0 0.0973035679 276.381447 0.0973035679 276.381447 444.176979 0 444.176979"></polygon> // <polygon id="path-5" points="0.390584071 0.90700885 310.68085 0.90700885 310.68085 241.061947 0.390584071 241.061947"></polygon> // </defs> // <g id="3.通用组件/彩色版/盆栽02" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> // <g id="分组-2" transform="translate(235.000000, 62.000000)"> // <g id="分组"> // <g transform="translate(240.000000, 0.672212)"> // <mask id="mask-2" fill="white"> // <use xlink:href="#path-1"></use> // </mask> // <g id="Clip-2"></g> // <path d="M158.073664,12.9438584 C277.776319,-43.6759646 349.118973,104.817133 288.918265,187.496071 C215.453841,288.389522 177.821628,404.481558 156.865168,439.458903 C139.186938,468.965097 90.7610973,540.900319 32.448531,507.744212 C-21.2169558,477.23023 8.03224779,357.47023 8.03224779,357.47023 C8.03224779,357.47023 10.4025133,82.792354 158.073664,12.9438584 Z" id="Fill-1" fill="#389E0D" mask="url(#mask-2)"></path> // </g> // <path d="M465.856885,489.527469 C419.82892,543.466938 353.408389,651.973487 311.797062,613.970655 C286.577947,590.940212 320.292637,481.870832 412.579009,422.527115 C491.079186,372.048531 511.885912,435.588 465.856885,489.527469 Z" id="Fill-3" fill="#BAE637"></path> // <path d="M38.0270442,485.358796 C-2.66782301,430.45508 -17.5265841,351.664991 27.8960708,331.460389 C71.4454513,312.090478 143.584566,359.784637 176.998726,451.576142 C210.411823,543.366584 229.689345,609.362336 197.004743,620.836673 C143.379611,639.662867 91.7774867,557.874903 38.0270442,485.358796" id="Fill-5" fill="#389E0D"></path> // <g transform="translate(0.000000, 103.681062)"> // <mask id="mask-4" fill="white"> // <use xlink:href="#path-3"></use> // </mask> // <g id="Clip-8"></g> // <path d="M25.4106903,11.5332743 C42.9136991,-0.242654867 64.9342301,-2.93256637 85.0252035,3.50283186 C113.06485,12.4837168 155.616,39.2246018 197.729628,115.978938 C252.711929,216.189558 281.334584,326.047965 275.676531,395.636283 C271.97777,441.144956 215.912283,460.764425 184.547681,427.582832 C170.143434,412.342832 154.902372,388.852566 139.990513,353.215752 C79.9788319,209.807257 23.8719292,119.94 17.1806018,110.916637 C-0.671787611,86.8380531 -13.4363894,37.6709735 25.4106903,11.5332743" id="Fill-7" fill="#BAE637" mask="url(#mask-4)"></path> // </g> // <path d="M141.099204,500.012443 C142.298209,498.86896 144.197171,498.91397 145.340654,500.112974 L145.88929,500.705266 L146.304909,501.16564 C147.061398,502.009712 147.935196,503.01708 148.916495,504.187376 C151.705021,507.512967 154.805694,511.485676 158.14,516.102544 C167.642308,529.259974 177.135445,544.95723 185.990174,563.17016 C211.259382,615.145361 226.414619,676.879728 226.414619,748.147327 C226.414619,749.804182 225.071474,751.147327 223.414619,751.147327 C221.757765,751.147327 220.414619,749.804182 220.414619,748.147327 C220.414619,677.820104 205.477998,616.976263 180.594109,565.793609 C171.895255,547.901291 162.580979,532.499789 153.275876,519.615419 C150.218663,515.382231 147.370993,511.715082 144.798071,508.616766 L144.318883,508.042498 C143.588843,507.171853 142.924135,506.399091 142.329364,505.724408 L141.57727,504.881899 C141.298477,504.573815 141.104077,504.364414 140.998674,504.253893 C139.85519,503.054888 139.9002,501.155927 141.099204,500.012443 Z" id="Stroke-9" fill="#253369" fill-rule="nonzero"></path> // <path d="M367.748974,521.010348 C368.740226,519.682724 370.620046,519.41004 371.94767,520.401292 C373.275294,521.392544 373.547977,523.272365 372.556725,524.599989 C361.630259,539.234247 351.546598,554.968774 342.273538,571.647902 C322.670572,606.907073 307.514836,644.709138 296.265725,682.51358 C292.328554,695.745074 289.161802,708.028562 286.696718,719.046687 L286.197621,721.304853 C285.609373,724.000253 285.100601,726.457438 284.667904,728.660769 L284.388748,730.10227 L283.890685,732.82323 C283.615614,734.457091 282.068118,735.558607 280.434257,735.283535 C278.800396,735.008463 277.69888,733.460968 277.973952,731.827107 L278.144493,730.861031 C278.285477,730.081512 278.457554,729.163373 278.661815,728.111555 L279.157705,725.613994 C279.640304,723.232985 280.200411,720.602023 280.841471,717.736693 L281.386811,715.328377 C283.797051,704.809239 286.821042,693.216238 290.51492,680.802368 C301.880647,642.606019 317.195414,604.407293 337.029513,568.732393 C346.42875,551.826313 356.656517,535.866923 367.748974,521.010348 Z" id="Stroke-11" fill="#253369" fill-rule="nonzero"></path> // <path d="M420.173895,146.722519 C421.322319,147.823004 421.405564,149.6172 420.396179,150.817363 L420.264313,150.964196 C420.205421,151.025654 420.078582,151.160171 419.885984,151.367802 L419.148514,152.17295 L418.719611,152.648778 C417.42871,154.087941 415.927275,155.820874 414.232809,157.848007 C409.375153,163.659347 403.955295,170.652779 398.113216,178.83176 C381.394725,202.237847 364.66599,230.428647 349.045879,263.43258 C323.038705,318.383471 302.783728,381.056464 290.507728,451.513642 C275.601207,537.068491 273.132635,630.530663 285.334493,731.967091 C285.53237,733.612087 284.359249,735.106031 282.714254,735.303909 C281.069258,735.501786 279.575314,734.328665 279.377437,732.68367 C267.105653,630.665929 269.589765,536.615367 284.596777,450.483756 C296.967362,379.48372 317.38887,316.295446 343.622605,260.865852 C359.399254,227.531168 376.309905,199.033807 393.230801,175.344351 L394.542007,173.518518 C399.758804,166.293587 404.636512,160.009406 409.076561,154.663326 L409.629281,153.999952 C411.223873,152.0923 412.656778,150.432864 413.914488,149.021279 L414.253146,148.642447 C414.645738,148.204764 414.997311,147.818163 415.306596,147.482609 L415.932218,146.812937 C417.078557,145.616662 418.97762,145.57618 420.173895,146.722519 Z" id="Stroke-13" fill="#253369" fill-rule="nonzero"></path> // <path d="M160.49864,324.626859 C161.915621,323.76818 163.760408,324.220773 164.619088,325.637755 L164.920376,326.143372 C165.16027,326.549571 165.442394,327.03365 165.765237,327.595134 L166.236124,328.41852 C167.040854,329.832981 167.944704,331.458053 168.940681,333.291539 L169.765526,334.818607 C172.816739,340.499044 176.16056,347.071886 179.731098,354.516439 L180.219389,355.537007 C191.864638,379.935697 203.5046,408.466909 214.365398,440.887625 C244.775686,531.665793 263.276243,634.699209 263.968574,748.128915 C263.978514,749.785739 262.64359,751.137055 260.986766,751.147335 C259.329943,751.157276 257.978626,749.822351 257.968516,748.165527 C257.280406,635.399719 238.892146,532.991711 208.676141,442.793501 C198.090993,411.19563 186.766781,383.335599 175.434134,359.44465 L174.804539,358.12146 C170.9309,350.005556 167.325259,342.923606 164.073034,336.902641 L163.093535,335.101842 C162.15417,333.387328 161.308583,331.881275 160.563761,330.585894 L160.210003,329.973537 L159.487744,328.747307 C158.629065,327.330326 159.081658,325.485539 160.49864,324.626859 Z" id="Stroke-15" fill="#253369" fill-rule="nonzero"></path> // <path d="M65.6594336,172.415257 C66.2530619,179.496319 60.9943009,185.717204 53.9143009,186.310832 C46.8332389,186.905522 40.612354,181.646761 40.0176637,174.565699 C39.4240354,167.485699 44.6827965,161.264814 51.7638584,160.670124 C58.8438584,160.076496 65.0647434,165.335257 65.6594336,172.415257" id="Fill-17" fill="#FFFFFF"></path> // <path d="M174.938867,227.345628 C175.533558,234.425628 170.274796,240.647575 163.193735,241.241204 C156.112673,241.835894 149.891788,236.577133 149.297097,229.496071 C148.703469,222.416071 153.96223,216.195186 161.043292,215.600496 C168.123292,215.006867 174.345239,220.265628 174.938867,227.345628" id="Fill-19" fill="#FFFFFF"></path> // <path d="M156.623363,373.600779 C157.304071,381.709805 151.28177,388.834407 143.172743,389.514053 C135.063717,390.194761 127.939115,384.17246 127.259469,376.063434 C126.578761,367.955469 132.601062,360.830867 140.710088,360.150159 C148.818053,359.469451 155.942655,365.491752 156.623363,373.600779" id="Fill-21" fill="#FFFFFF"></path> // <path d="M492.275894,155.028531 C492.275894,166.53685 482.947752,175.866053 471.439434,175.866053 C459.931115,175.866053 450.602973,166.53685 450.602973,155.028531 C450.602973,143.521274 459.931115,134.192071 471.439434,134.192071 C482.947752,134.192071 492.275894,143.521274 492.275894,155.028531" id="Fill-23" fill="#FFFFFF"></path> // <path d="M324.535965,218.657735 C324.535965,230.164991 315.206761,239.494195 303.699504,239.494195 C292.191186,239.494195 282.863044,230.164991 282.863044,218.657735 C282.863044,207.150478 292.191186,197.821274 303.699504,197.821274 C315.206761,197.821274 324.535965,207.150478 324.535965,218.657735" id="Fill-25" fill="#FFFFFF"></path> // <path d="M378.862195,360.097805 C378.862195,364.907363 374.962726,368.806832 370.153168,368.806832 C365.343611,368.806832 361.444142,364.907363 361.444142,360.097805 C361.444142,355.287186 365.343611,351.387717 370.153168,351.387717 C374.962726,351.387717 378.862195,355.287186 378.862195,360.097805" id="Fill-27" fill="#FFFFFF"></path> // <line x1="174.618372" y1="855.678584" x2="364.480673" y2="855.678584" id="Fill-29" fill="#A3B5D6"></line> // <path d="M441.605204,471.476177 C441.605204,478.581664 435.844142,484.341664 428.739717,484.341664 C421.633168,484.341664 415.87423,478.581664 415.87423,471.476177 C415.87423,464.37069 421.633168,458.61069 428.739717,458.61069 C435.844142,458.61069 441.605204,464.37069 441.605204,471.476177" id="Fill-31" fill="#FFFFFF"></path> // <g transform="translate(106.194690, 655.893451)"> // <mask id="mask-6" fill="white"> // <use xlink:href="#path-5"></use> // </mask> // <g id="Clip-34"></g> // <path d="M285.194124,241.062053 L25.8773097,241.062053 C11.8596106,241.062053 0.390584071,229.593027 0.390584071,215.575327 L0.390584071,26.3937345 C0.390584071,12.3749735 11.8596106,0.90700885 25.8773097,0.90700885 L285.194124,0.90700885 C299.210761,0.90700885 310.68085,12.3749735 310.68085,26.3937345 L310.68085,215.575327 C310.68085,229.593027 299.210761,241.062053 285.194124,241.062053" id="Fill-33" fill="#253369" mask="url(#mask-6)"></path> // </g> // </g> // </g> // </g> // </svg> // `;
zombieJ/malfurion
0
A svg control lib
TypeScript
zombieJ
二货爱吃白萝卜
alipay
index.js
JavaScript
module.exports = require('./src/');
zombieJ/malfurion
0
A svg control lib
TypeScript
zombieJ
二货爱吃白萝卜
alipay
jest.config.js
JavaScript
module.exports = { snapshotSerializers: [require.resolve('enzyme-to-json/serializer')], };
zombieJ/malfurion
0
A svg control lib
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/index.ts
TypeScript
import { getBox, analysisSVG } from './utils/svgUtil'; import { SVGEntity, SVGNodeEntity, SVGBox, SVGNodeRecord, MalfurionEventHandler, MalfurionEventType, BoundingBox, SerializeTransform, TransformConfig, HierarchyInfo, } from './interface'; import Matrix from './utils/matrix'; import { Line } from './utils/mathUtil'; import { PathCache } from './utils/cacheUtil'; export { BoundingBox, Matrix, Line }; export const MALFURION_INSTANCE = '__Malfurion_Instance__'; const DEFAULT_ORIGIN = 0.5; class Malfurion { public debug: boolean = false; private entity: SVGEntity; private svg: SVGSVGElement | null = null; private debugHolder: SVGElement | null = null; private pathCache: PathCache = new PathCache(); private changedEntities = new Set<SVGNodeEntity>(); private clickEventHandlers = new Set<MalfurionEventHandler>(); private mouseEnterEventHandlers = new Set<MalfurionEventHandler>(); private mouseLeaveEventHandlers = new Set<MalfurionEventHandler>(); private elementEnterEventHandlers = new Set<MalfurionEventHandler>(); private elementLeaveEventHandlers = new Set<MalfurionEventHandler>(); static getInstance = (svg: SVGSVGElement): Malfurion => (svg as any)[MALFURION_INSTANCE]; static getElement = (svg: any, path: number[]): SVGElement => { let element: any = svg; path.forEach(index => { if (element) { element = element.children[index]; } }); return element; }; constructor(source: string) { const holder = document.createElement('div'); holder.innerHTML = source; const svg = holder.querySelector('svg')!; document.body.appendChild(svg); // Calculate rect this.entity = analysisSVG(svg.children, getBox(svg)); // Clean up document.body.removeChild(svg); } addEventListener = ( event: MalfurionEventType, callback: MalfurionEventHandler, ) => { switch (event) { case 'click': this.clickEventHandlers.add(callback); break; case 'mouseEnter': this.mouseEnterEventHandlers.add(callback); break; case 'mouseLeave': this.mouseLeaveEventHandlers.add(callback); break; case 'elementEnter': this.elementEnterEventHandlers.add(callback); break; case 'elementLeave': this.elementLeaveEventHandlers.add(callback); break; default: console.warn(`Malfurion do not support '${event}' type.`); } }; private generateDebugHolder = () => { if (!this.svg) { return; } if (this.debugHolder) { this.svg.removeChild(this.debugHolder); } if (!this.debug) { return; } const debugHolder = document.createElementNS( 'http://www.w3.org/2000/svg', 'g', ); this.pathCache.getPathList().forEach(path => { const mergedTransform = this.getMergedTransform(path); const box = this.getOriginBox(path); const entity = this.getNodeEntity(path); if (box && entity) { const { originX = DEFAULT_ORIGIN, originY = DEFAULT_ORIGIN } = entity; const center = document.createElementNS( 'http://www.w3.org/2000/svg', 'circle', ); center.style.pointerEvents = 'none'; center.setAttribute('cx', `${box.x + box.width * originX}`); center.setAttribute('cy', `${box.y + box.height * originY}`); center.setAttribute('r', '2'); center.setAttribute('fill', 'blue'); center.setAttribute('fill-opacity', '0.5'); center.setAttribute('transform', mergedTransform); debugHolder.appendChild(center); } }); this.debugHolder = debugHolder; this.svg.appendChild(this.debugHolder); }; private idCacheList: [string, string][] | null = null; private getIdCacheList = () => { if (!this.idCacheList) { this.idCacheList = Object.keys(this.entity.ids) .sort((id1, id2) => id2.length - id1.length) .map(id => [id, this.entity.ids[id]]); } return this.idCacheList; }; private replaceId = (str: string) => { if (str === undefined) { return str; } let replaced = str; if (replaced.includes('#')) { this.getIdCacheList().forEach(([id, replaceId]) => { replaced = replaced.replace(`#${id}`, `#${replaceId}`); }); } return replaced; }; getSVG = () => { if (!this.svg) { if (this.debug) { console.time('getSVG'); } // Render svg const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); const defs = document.createElementNS( 'http://www.w3.org/2000/svg', 'defs', ); this.svg = svg; (svg as any)[MALFURION_INSTANCE] = this; svg.appendChild(defs); const fillNodes = ( holder: Element, nodes: SVGNodeRecord[] | SVGNodeEntity[], path: false | number[] = [], ) => { nodes.forEach((node, index) => { const entity = node as SVGNodeEntity; const { tagName, attributes, children, innerHTML } = entity; const ele = document.createElementNS( 'http://www.w3.org/2000/svg', tagName, ); entity.element = ele; // Fill path data const elePath = path ? [...path, index] : path; if (elePath) { ele.setAttribute('data-path', elePath.join('-')); this.pathCache.set(ele, elePath, entity); } // Attributes Object.keys(attributes).forEach(key => { let value = attributes[key]; // Replace value with real id value = this.replaceId(value); if (key.includes('xlink:')) { ele.setAttributeNS( 'http://www.w3.org/1999/xlink', 'xlink:href', value, ); } else { ele.setAttribute(key, value); } }); // Children if (innerHTML) { // Text children ele.innerHTML = innerHTML; } else { // Node Children fillNodes(ele, children, elePath); } // Append node holder.appendChild(ele); }); }; fillNodes(defs, this.entity.defs, false); fillNodes(svg, this.entity.nodes); if (this.debug) { this.generateDebugHolder(); console.timeEnd('getSVG'); } // Events svg.addEventListener('click', (e: any) => { this.clickEventHandlers.forEach(callback => callback(e, this)); }); svg.addEventListener('mouseenter', (e: any) => { this.mouseEnterEventHandlers.forEach(callback => callback(e, this)); }); svg.addEventListener('mouseleave', (e: any) => { this.mouseLeaveEventHandlers.forEach(callback => callback(e, this)); }); svg.addEventListener('mouseover', (e: any) => { this.elementEnterEventHandlers.forEach(callback => callback(e, this)); }); svg.addEventListener('mouseout', (e: any) => { this.elementLeaveEventHandlers.forEach(callback => callback(e, this)); }); } return this.svg; }; /** List all the svg elements */ getHierarchy = (): HierarchyInfo[] => { const idCache = new Map<string, string>(); Object.keys(this.entity.ids).forEach(originId => { idCache.set(this.entity.ids[originId], originId); }); const dig = ( nodes: SVGNodeEntity[], path: number[] = [], ): HierarchyInfo[] => nodes.map(({ tagName, attributes, children = [] }, index) => { const mergedPath = [...path, index]; const info: HierarchyInfo = { path: mergedPath, tagName, }; const element = this.pathCache.getElement(mergedPath); if (element) { info.element = element as SVGElement; } if (attributes.id) { info.id = attributes.id; info.originId = idCache.get(attributes.id); } if (children.length) { info.children = dig(children, mergedPath); } // Colors if (attributes.fill) { info.fill = attributes.fill; } if (attributes.stroke) { info.stroke = attributes.stroke; } return info; }); return dig(this.entity.nodes); }; getPath = (element: any): number[] | null => this.pathCache.getPath(element); getElement = (path: number[]): SVGGraphicsElement | null => this.pathCache.getElement(path) as SVGGraphicsElement; private getNodeEntity = (path?: number[]) => { if (!path || !path.length) { return null; } let { nodes } = this.entity; for (let i = 0; i < path.length; i += 1) { const index = i === 0 ? 0 : path[i]; const current = nodes[index]; if (i === path.length - 1) { return current; } nodes = current.children; } return null; }; /** * Return svg origin box related to the container. * When `pure` to `true`, return origin box related to context. */ getOriginBox = (path: number[]): SVGBox | null => { const entity = this.getNodeEntity(path); if (entity) { return entity.box; } return null; }; /** * Return box info with current path. * This also provides current node data for quick access. */ getBox = (path: number[]): BoundingBox | null => { const entity = this.getNodeEntity(path); if (entity) { const mergedTransform = this.getMergedTransform(path); const pureMergedTransform = this.getMergedTransform(path, true); return { x: 0, y: 0, width: 0, height: 0, ...this.getOriginBox(path), originX: entity.originX !== undefined ? entity.originX : DEFAULT_ORIGIN, originY: entity.originY !== undefined ? entity.originY : DEFAULT_ORIGIN, translateX: entity.translateX || 0, translateY: entity.translateY || 0, rotate: entity.rotate || 0, opacity: entity.opacity || 1, scaleX: entity.scaleX || 1, scaleY: entity.scaleY || 1, mergedTransform, pureMergedTransform, fill: entity.fill, stroke: entity.stroke, }; } return null; }; getMergedTransform = ( path: number[], ignoreCurrentMalfurion = false, ): string => { let mergedTransform = ''; const endNodeEntity = this.getNodeEntity(path); let entity = endNodeEntity; while (entity) { const { attributes } = entity; // Skip if ignoreCurrentMalfurion let malfurionTransform = ''; if (!ignoreCurrentMalfurion || endNodeEntity !== entity) { malfurionTransform = this.getMatrix( this.pathCache.getPath(entity)!, ).toString(); } mergedTransform = `${attributes.transform || ''} ${malfurionTransform} ${mergedTransform}` .replace(/\s+/, ' ') .trim(); entity = entity.parent; } return mergedTransform; }; private internalTransform = ( path: number[], prop: keyof SVGNodeEntity, initialValue: number | string | null, value?: number | string | ((origin: number | string) => number | string), postUpdate?: (val: number | string) => number, ): number => { const entity = this.getNodeEntity(path); if (entity && value !== undefined) { const target = typeof value === 'function' ? value((entity[prop] as any) || initialValue) : value; (entity[prop] as any) = postUpdate ? postUpdate(target) : target; this.refresh(path); this.changedEntities.add(entity); } this.generateDebugHolder(); return (entity && (entity[prop] as any)) || initialValue; }; fill = (path: number[], value?: string | ((origin: string) => string)) => this.internalTransform(path, 'fill', null, value as any); stroke = (path: number[], value?: string | ((origin: string) => string)) => this.internalTransform(path, 'stroke', null, value as any); originX = (path: number[], value?: number | ((origin: number) => number)) => this.internalTransform(path, 'originX', DEFAULT_ORIGIN, value as any); originY = (path: number[], value?: number | ((origin: number) => number)) => this.internalTransform(path, 'originY', DEFAULT_ORIGIN, value as any); rotate = (path: number[], value?: number | ((origin: number) => number)) => this.internalTransform( path, 'rotate', 0, value as any, (val: any) => ((val % 360) + 360) % 360, ); scaleX = (path: number[], value?: number | ((origin: number) => number)) => this.internalTransform(path, 'scaleX', 1, value as any); scaleY = (path: number[], value?: number | ((origin: number) => number)) => this.internalTransform(path, 'scaleY', 1, value as any); translateX = ( path: number[], value?: number | ((origin: number) => number), ) => this.internalTransform(path, 'translateX', 0, value as any); translateY = ( path: number[], value?: number | ((origin: number) => number), ) => this.internalTransform(path, 'translateY', 0, value as any); opacity = (path: number[], value?: number | ((origin: number) => number)) => this.internalTransform(path, 'opacity', 1, value as any); getMatrix = (path: number[]) => { const entity = this.getNodeEntity(path); if (!entity) { return Matrix.fromTranslate(); } const { x, y, width, height } = this.getOriginBox(path)!; const { rotate = 0, scaleX = 1, scaleY = 1, translateX = 0, translateY = 0, originX = DEFAULT_ORIGIN, originY = DEFAULT_ORIGIN, } = entity; return Matrix.fromMixTransform({ translateX, translateY, rotate, scaleX, scaleY, originX, originY, x, y, width, height, }); }; reset = () => { this.changedEntities.forEach(entity => { /* eslint-disable no-param-reassign */ delete entity.opacity; delete entity.rotate; delete entity.originX; delete entity.originY; delete entity.scaleX; delete entity.scaleY; delete entity.translateX; delete entity.translateY; delete entity.opacity; delete entity.fill; delete entity.stroke; /* eslint-enable no-param-reassign */ function setAttribute(prop: string, value: string) { if (value !== undefined) { entity.element?.setAttribute(prop, value); } else { entity.element?.removeAttribute(prop); } } // Transform setAttribute('transform', entity.attributes.transform); // Opacity setAttribute('opacity', entity.attributes.opacity); // Color setAttribute('fill', this.replaceId(entity.attributes.fill)); setAttribute('stroke', this.replaceId(entity.attributes.stroke)); }); this.changedEntities = new Set(); }; refresh = (path: number[]) => { const entity = this.getNodeEntity(path); if (entity) { const ele = this.getElement(path); const { attributes, opacity, fill, stroke } = entity; const matrix = this.getMatrix(path); // Transform ele!.setAttribute( 'transform', `${attributes.transform || ''} ${matrix.toString()}`, ); // Opacity if (opacity !== undefined) { const mergedOpacity = Number(attributes.opacity || 1) * opacity; ele!.setAttribute('opacity', `${mergedOpacity}`); } else if (attributes.opacity) { ele!.setAttribute('opacity', attributes.opacity); } else { ele!.removeAttribute('opacity'); } // Color if (fill !== undefined) { ele!.setAttribute('fill', fill); } if (stroke !== undefined) { ele!.setAttribute('stroke', stroke); } } }; serializeTransform = (): SerializeTransform[] => { const list: SerializeTransform[] = []; function dig(nodes: SVGNodeEntity[], parentPath: number[] = []) { (nodes || []).forEach((node, index) => { const { children } = node; const path = [...parentPath, index]; let updated = false; const record: SerializeTransform = { path, }; function recordIfNeeded( prop: keyof TransformConfig, defaultValue: any, ) { const val = node[prop]; if (val !== undefined && val !== defaultValue) { record[prop] = val as any; updated = true; } } recordIfNeeded('rotate', 0); recordIfNeeded('originX', DEFAULT_ORIGIN); recordIfNeeded('originY', DEFAULT_ORIGIN); recordIfNeeded('scaleX', 1); recordIfNeeded('scaleY', 1); recordIfNeeded('translateX', 0); recordIfNeeded('translateY', 0); recordIfNeeded('opacity', 1); recordIfNeeded('fill', undefined); recordIfNeeded('stroke', undefined); if (updated) { list.push(record); } dig(children, path); }); } dig(this.entity.nodes); return list; }; deserializeTransform = (records: SerializeTransform[]) => { this.reset(); records.forEach(({ path, ...restProps }) => { const entity = this.getNodeEntity(path); if (entity) { Object.keys(restProps).forEach((prop: any) => { (entity as any)[prop] = (restProps as any)[prop]; }); this.refresh(path); this.changedEntities.add(entity); } }); }; } export default Malfurion;
zombieJ/malfurion
0
A svg control lib
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/interface.ts
TypeScript
import Malfurion from '.'; export interface SVGBox { x: number; y: number; width: number; height: number; } export interface ShapeInfo extends SVGBox { originX?: number; originY?: number; } export interface BoundingBox extends Omit<ShapeInfo, 'originX' | 'originY'>, Omit<Required<TransformConfig>, 'fill' | 'stroke'> { mergedTransform?: string; pureMergedTransform?: string; // Color fill?: string; stroke?: string; } export interface SVGNodeRecord { tagName: string; attributes: Record<string, string>; children: SVGNodeRecord[]; } export interface TransformConfig { rotate?: number; originX?: number; originY?: number; scaleX?: number; scaleY?: number; translateX?: number; translateY?: number; opacity?: number; // Color fill?: string; stroke?: string; } export interface SVGNodeEntity extends SVGNodeRecord, TransformConfig { parent: SVGNodeEntity | null; children: SVGNodeEntity[]; box: SVGBox; element?: SVGElement; /** Only used for element that has string children only like text element */ innerHTML?: string; } export interface SVGEntity { defs: SVGNodeRecord[]; nodes: SVGNodeEntity[]; ids: Record<string, string>; } interface MockEvent { target: SVGGraphicsElement | SVGSVGElement; currentTarget: SVGGraphicsElement | SVGSVGElement; } export type MalfurionEventHandler = (e: MockEvent, instance: Malfurion) => void; export type MalfurionEventType = | 'click' | 'mouseEnter' | 'mouseLeave' | 'elementEnter' | 'elementLeave'; export interface Point { x: number; y: number; } export interface SerializeTransform extends TransformConfig { path: number[]; } export interface HierarchyInfo { path: number[]; id?: string; originId?: string; tagName: string; element?: SVGElement; children?: HierarchyInfo[]; // Color fill?: string; stroke?: string; }
zombieJ/malfurion
0
A svg control lib
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/utils/cacheUtil.ts
TypeScript
import { SVGNodeEntity } from '../interface'; function convertStringPath(path: string) { return path.split('-').map(pos => Number(pos)); } export class PathCache { private elementPathMap = new Map<Element, string>(); private pathElementMap = new Map<string, Element>(); private entityPathMap = new Map<SVGNodeEntity, string>(); public set = (element: Element, path: number[], entity: SVGNodeEntity) => { const strPath = path.join('-'); this.elementPathMap.set(element, strPath); this.pathElementMap.set(strPath, element); this.entityPathMap.set(entity, strPath); }; public getElement = (path: number[]) => this.pathElementMap.get(path.join('-')) || null; public getPath = (e: Element | SVGNodeEntity) => { const path1 = this.elementPathMap.get(e as any); const path2 = this.entityPathMap.get(e as any); const path = path1 || path2; return path ? convertStringPath(path) : null; }; public getEntityList = () => [...this.entityPathMap.keys()]; public getPathList = () => [...this.pathElementMap.keys()].map(convertStringPath); }
zombieJ/malfurion
0
A svg control lib
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/utils/mathUtil.ts
TypeScript
import { Point } from '../interface'; // Minimum 0.0000000000001, leave 1 digit. const PRECISION = 0.000000000001; /** * * @param list [x, y, z][] * @returns [a, b,c ] */ export function resolveTernary(list: [number, number, number][]) { const z0 = list[0][2]; const z1 = list[1][2]; const z2 = list[2][2]; const x0 = list[0][0]; const x1 = list[1][0]; const x2 = list[2][0]; const y0 = list[0][1]; const y1 = list[1][1]; const y2 = list[2][1]; const aLeft = (z0 - z1) * (y1 - y2) - (z1 - z2) * (y0 - y1); const aRight = (x0 - x1) * (y1 - y2) - (x1 - x2) * (y0 - y1); const a = aLeft / aRight; let b: number; if (y0 !== y1) { b = (z0 - z1 - (x0 - x1) * a) / (y0 - y1); } else { b = (z1 - z2 - (x1 - x2) * a) / (y1 - y2); } const c = z0 - a * x0 - b * y0; return [a, b, c]; } export class Line { /** * * @param p1 Point * @param p2 Point * @returns [a, b] */ static fromPoints = (p0: Point, p1: Point): Line => { // Vertical if (Math.abs(p0.x - p1.x) <= PRECISION) { return new Line(null, null, p0.x, null); } // Horizontal if (Math.abs(p0.y - p1.y) <= PRECISION) { return new Line(null, null, null, p0.y); } const a = (p0.y - p1.y) / (p0.x - p1.x); const b = p0.y - a * p0.x; return new Line(a, b); }; a: number | null; b: number | null; x: number | null; y: number | null; constructor( a: number | null, b: number | null, x: number | null = null, y: number | null = null, ) { this.a = a; this.b = b; this.x = x; this.y = y; } translate = (x: number = 0, y: number = 0) => { if (this.isVertical()) { return new Line(this.a, this.b, this.x! + x, this.y); } if (this.isHorizontal()) { return new Line(this.a, this.b, this.x, this.y! + y); } return new Line(this.a, this.b! + y - this.a! * x, this.x, this.y); }; isVertical = () => this.x !== null; isHorizontal = () => this.y !== null; crossPoint = (line: Line): Point => { if (this.isVertical()) { return { x: this.x!, y: line.isHorizontal() ? line.y! : line.a! * this.x! + line.b!, }; } if (this.isHorizontal()) { return { x: line.isVertical() ? line.x! : (this.y! - line.b!) / line.a!, y: this.y!, }; } const crossX = (line.b! - this.b!) / (this.a! - line.a!); return { x: crossX, y: this.a! * crossX + this.b!, }; }; getPerpendicular = ({ x, y }: Point) => { if (this.isVertical()) { return new Line(null, null, null, y); } if (this.isHorizontal()) { return new Line(null, null, x, null); } const pa = -1 / this.a!; const pb = y - pa * x; return new Line(pa, pb, null, null); }; toUnits = () => [this.a, this.b, this.x, this.y]; toString = () => { if (this.isVertical()) { return `x = ${this.x};`; } if (this.isHorizontal()) { return `y = ${this.y};`; } return `y = ${this.a}x + ${this.b}`; }; }
zombieJ/malfurion
0
A svg control lib
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/utils/matrix.ts
TypeScript
import { multiply, divide, inv } from 'mathjs'; import { Point, ShapeInfo } from '../interface'; import { parseTransformMatrix } from './svgUtil'; import { resolveTernary } from './mathUtil'; export default class Matrix { protected matrix: number[][]; public static fromArray(matrixArr: number[][]) { const instance = new Matrix(1, 1); instance.matrix = matrixArr; return instance; } public static fromTransform( a: number, b: number, c: number, d: number, e: number, f: number, ) { const instance = new Matrix(3, 3); instance.set(0, 0, a); instance.set(0, 1, b); instance.set(1, 0, c); instance.set(1, 1, d); instance.set(2, 0, e); instance.set(2, 1, f); instance.set(2, 2, 1); return instance; } public static fromTranslate(x: number = 0, y: number = 0) { return Matrix.fromTransform(1, 0, 0, 1, x, y); } public static fromTransformText(str: string) { const matrix = parseTransformMatrix(str); if (matrix) { const { a, b, c, d, e, f } = matrix; return Matrix.fromTransform(a, b, c, d, e, f); } return Matrix.fromTranslate(); } public static backFromPosition( list: { source: Point; target: Point; }[], ) { const [a, c, e] = resolveTernary([ [list[0].source.x, list[0].source.y, list[0].target.x], [list[1].source.x, list[1].source.y, list[1].target.x], [list[2].source.x, list[2].source.y, list[2].target.x], ]); const [b, d, f] = resolveTernary([ [list[0].source.x, list[0].source.y, list[0].target.y], [list[1].source.x, list[1].source.y, list[1].target.y], [list[2].source.x, list[2].source.y, list[2].target.y], ]); return Matrix.fromTransform(a, b, c, d, e, f); } public static fromRotate( rotate: number, { x, y, width, height, originX, originY }: Required<ShapeInfo>, ) { const deg = (rotate / 180) * Math.PI; const transX = x + width * originX; const transY = y + height * originY; const transToMatrix = Matrix.fromTranslate(transX, transY); const transBackMatrix = Matrix.fromTranslate(-transX, -transY); const rotateMatrix = Matrix.fromTransform( Math.cos(deg), Math.sin(deg), -Math.sin(deg), Math.cos(deg), 0, 0, ); return transToMatrix.multiple(rotateMatrix).multiple(transBackMatrix); } public static fromScale( scaleX: number, scaleY: number, { x, y, width, height, originX, originY }: Required<ShapeInfo>, ) { const transX = x + width * originX; const transY = y + height * originY; const transToMatrix = Matrix.fromTranslate(transX, transY); const transBackMatrix = Matrix.fromTranslate(-transX, -transY); const scaleMatrix = Matrix.fromTransform(scaleX, 0, 0, scaleY, 0, 0); return transToMatrix.multiple(scaleMatrix).multiple(transBackMatrix); } public static fromMixTransform(mixTransform: { translateX: number; translateY: number; rotate: number; scaleX: number; scaleY: number; originX: number; originY: number; x: number; y: number; width: number; height: number; }) { const { translateX, translateY, rotate, scaleX, scaleY } = mixTransform; let mergeMatrix = Matrix.fromTranslate(); // Translate if (translateX || translateY) { const translateMatrix = Matrix.fromTranslate(translateX, translateY); mergeMatrix = mergeMatrix.multiple(translateMatrix); } // Rotate matrix if (rotate !== 0) { mergeMatrix = mergeMatrix.multiple( Matrix.fromRotate(rotate, mixTransform), ); } // Scale matrix if (scaleX !== 1 || scaleY !== 1) { mergeMatrix = mergeMatrix.multiple( Matrix.fromScale(scaleX, scaleY, mixTransform), ); } return mergeMatrix; } constructor(x: number, y: number, values?: number[]) { this.matrix = []; for (let i = 0; i < y; i += 1) { this.matrix[i] = []; for (let j = 0; j < x; j += 1) { this.matrix[i][j] = 0; } } if (values) { this.fill(values); } } public fill = (values: number[]) => { let i = 0; const targetX = this.getX(); const targetY = this.getY(); for (let y = 0; y < targetY; y += 1) { for (let x = 0; x < targetX; x += 1) { this.set(x, y, values[i] || 0); i += 1; } } }; set = (x: number, y: number, value: number) => { this.matrix[y][x] = value; }; get = (x: number, y: number): number => this.matrix[y][x]; getX = () => this.matrix[0].length; getY = () => this.matrix.length; getMatrix = () => this.matrix; multiple = (instance: Matrix) => { const rets = multiply(this.getMatrix(), instance.getMatrix()); return Matrix.fromArray(rets); }; /** * A * X = B, X = B\A */ leftDivide = (instance: Matrix) => { const inverseA = Matrix.fromArray(inv(instance.getMatrix())); return inverseA.multiple(this); }; /** * X * A = B, X = B/A = A * inv(B) */ rightDivide = (instance: Matrix) => Matrix.fromArray(divide(this.getMatrix(), instance.getMatrix()) as any); transformPosition = (x: number, y: number) => { const matrix = new Matrix(1, 3, [x, y, 1]); const ret = this.multiple(matrix); return { x: ret.get(0, 0), y: ret.get(0, 1), }; }; toTransform = (): [number, number, number, number, number, number] => [ this.get(0, 0), this.get(0, 1), this.get(1, 0), this.get(1, 1), this.get(2, 0), this.get(2, 1), ]; toString = () => { const transform = this.toTransform(); return `matrix(${transform.join(',')})`; }; }
zombieJ/malfurion
0
A svg control lib
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/utils/svgUtil.ts
TypeScript
import { SVGNodeRecord, SVGEntity, SVGNodeEntity, SVGBox } from '../interface'; import Matrix from './matrix'; function getColor(str: string = '') { const { style } = new Option(); style.color = str; if (style.color) { return style.color; } return null; } export function getAttributes({ attributes, }: { attributes: NamedNodeMap; }): Record<string, string> { const attrs: Record<string, string> = {}; Array.from(attributes).forEach(({ name, value }) => { attrs[name] = value; }); return attrs; } interface AbstractNode { tagName: string; attributes: NamedNodeMap; children?: HTMLCollection; } /** * * @param node svg element * @param loopChildren only used for defs element * @param postRecord some additional work */ export function getNodeRecord( node: AbstractNode, loopChildren: boolean, postRecord?: (record: SVGNodeRecord) => void, ): SVGNodeRecord { let subRecords: SVGNodeRecord[] = []; if (loopChildren) { subRecords = Array.from(node.children || []).map(subNode => getNodeRecord(subNode, true), ); } // Get attributes const attributes = getAttributes(node); const record = { tagName: node.tagName, attributes, children: subRecords, }; if (postRecord) { postRecord(record); } return record; } export function getBox(ele: SVGGraphicsElement, pure: boolean = false) { const { x, y, width, height } = ele.getBBox(); if (pure) { return { x, y, width, height }; } const { a, b, c, d, e, f } = ele.getCTM()!; const matrix: Matrix = Matrix.fromTransform(a, b, c, d, e, f); const leftTop = matrix.transformPosition(x, y); const rightTop = matrix.transformPosition(x + width, y); const leftBottom = matrix.transformPosition(x, y + height); const rightBottom = matrix.transformPosition(x + width, y + height); const xs = [leftTop.x, rightTop.x, leftBottom.x, rightBottom.x]; const ys = [leftTop.y, rightTop.y, leftBottom.y, rightBottom.y]; const left = Math.min(...xs); const right = Math.max(...xs); const top = Math.min(...ys); const bottom = Math.max(...ys); return { x: left, y: top, width: right - left, height: bottom - top }; } let uuid = 0; export function analysisNodes( parent: SVGNodeEntity | null, nodes: SVGGraphicsElement[], entity: SVGEntity, isDefs: boolean = false, ): SVGNodeEntity[] { const nodeEntities: SVGNodeEntity[] = []; function postRecord(record: SVGNodeRecord) { /* eslint-disable no-param-reassign */ // Replace any id content if (record.attributes.id) { const newId = `MALFURION_${uuid}`; entity.ids[record.attributes.id] = newId; record.attributes.id = newId; uuid += 1; } // Normalize colors const fillColor = getColor(record.attributes.fill); if (fillColor) { record.attributes.fill = fillColor; } const strokeColor = getColor(record.attributes.stroke); if (strokeColor) { record.attributes.stroke = strokeColor; } /* eslint-enable */ } nodes.forEach(node => { const { tagName, children, childNodes } = node; switch (tagName) { case 'title': case 'desc': return; case 'mask': entity.defs.push(getNodeRecord(node, true, postRecord)); return; case 'defs': analysisNodes( null, Array.from(children) as SVGGraphicsElement[], entity, true, ); return; default: if (isDefs) { entity.defs.push(getNodeRecord(node, true, postRecord)); } else { const nodeEntity: SVGNodeEntity = { ...getNodeRecord(node, false, postRecord), parent, box: getBox(node, true), children: [], }; nodeEntity.children = analysisNodes( nodeEntity, Array.from(children) as SVGGraphicsElement[], entity, ); // Handle additional text children if (childNodes.length && !children.length) { nodeEntity.innerHTML = node.innerHTML; } nodeEntities.push(nodeEntity); } } }); return nodeEntities; } export function analysisSVG(list: any, rootRect: SVGBox): SVGEntity { const entity: SVGEntity = { ids: {}, defs: [], nodes: [], }; const elements: SVGGraphicsElement[] = Array.from(list); let rootNodes = analysisNodes(null, elements, entity); if (rootNodes.length > 1) { const rootNode: SVGNodeEntity = { parent: null, tagName: 'g', box: rootRect, attributes: {}, children: rootNodes, }; rootNodes.forEach(node => { node.parent = rootNode; }); rootNodes = [rootNode]; } entity.nodes = rootNodes; return entity; } export function parseTransformMatrix(transform: string) { const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); const g = document.createElementNS('http://www.w3.org/2000/svg', 'g'); svg.appendChild(g); document.body.appendChild(svg); g.setAttribute('transform', transform); const matrix = g.getCTM(); document.body.removeChild(svg); return matrix; }
zombieJ/malfurion
0
A svg control lib
TypeScript
zombieJ
二货爱吃白萝卜
alipay
tests/utils.test.tsx
TypeScript (TSX)
import Matrix from '../src/utils/matrix'; import { Line } from '../src/utils/mathUtil'; describe('Utils', () => { describe('Matrix', () => { it('fill', () => { const m = new Matrix(2, 3); m.fill([1, 2, 3, 4, 5, 6]); expect(m.getMatrix()).toEqual([[1, 2], [3, 4], [5, 6]]); expect(m.get(0, 0)).toEqual(1); expect(m.get(1, 0)).toEqual(2); expect(m.get(0, 1)).toEqual(3); expect(m.get(1, 1)).toEqual(4); expect(m.get(0, 2)).toEqual(5); expect(m.get(1, 2)).toEqual(6); m.set(0, 2, 9); expect(m.get(0, 2)).toEqual(9); }); it('fromTransform', () => { const m = Matrix.fromTransform(1, 2, 3, 4, 5, 6); expect(m.getMatrix()).toEqual([[1, 3, 5], [2, 4, 6], [0, 0, 1]]); }); it('multiple', () => { const m1 = new Matrix(3, 2); const m2 = new Matrix(2, 3); m1.fill([1, 2, 3, 4, 5, 6]); m2.fill([1, 2, 3, 4, 5, 6]); const result = m1.multiple(m2); expect(result.getMatrix()).toEqual([[22, 28], [49, 64]]); }); it('leftDivide', () => { const m1 = new Matrix(2, 2, [1, 2, 3, 4]); const m2 = new Matrix(2, 2, [5, 6, 7, 8]); const multiple = m1.multiple(m2); expect(multiple.leftDivide(m1).getMatrix()).toEqual(m2.getMatrix()); }); it('rightDivide', () => { const m1 = new Matrix(2, 2, [1, 2, 3, 4]); const m2 = new Matrix(2, 2, [5, 6, 7, 8]); const multiple = m1.multiple(m2); expect(multiple.rightDivide(m2).getMatrix()).toEqual(m1.getMatrix()); }); }); describe('Line', () => { it('fromPoints', () => { expect(Line.fromPoints({ x: 1, y: 2 }, { x: 1, y: 3 }).toUnits()).toEqual( [null, null, 1, null], ); expect(Line.fromPoints({ x: 1, y: 2 }, { x: 3, y: 2 }).toUnits()).toEqual( [null, null, null, 2], ); expect(Line.fromPoints({ x: 1, y: 2 }, { x: 2, y: 3 }).toUnits()).toEqual( [1, 1, null, null], ); }); it('crossPoint', () => { const verticalLine = Line.fromPoints({ x: 1, y: 2 }, { x: 1, y: 3 }); const horizontalLine = Line.fromPoints({ x: 1, y: 2 }, { x: 9, y: 2 }); const line1 = Line.fromPoints({ x: 0, y: 1 }, { x: 1, y: 2 }); const line2 = Line.fromPoints({ x: 0, y: 1 }, { x: -1, y: 2 }); expect(verticalLine.crossPoint(horizontalLine)).toEqual({ x: 1, y: 2 }); expect(horizontalLine.crossPoint(verticalLine)).toEqual({ x: 1, y: 2 }); expect(verticalLine.crossPoint(line1)).toEqual({ x: 1, y: 2 }); expect(horizontalLine.crossPoint(line1)).toEqual({ x: 1, y: 2 }); expect(line1.crossPoint(line2)).toEqual({ x: 0, y: 1 }); }); it('translate', () => { const verticalLine = Line.fromPoints({ x: 1, y: 2 }, { x: 1, y: 3 }); const horizontalLine = Line.fromPoints({ x: 1, y: 2 }, { x: 9, y: 2 }); const line1 = Line.fromPoints({ x: 0, y: 1 }, { x: 1, y: 3 }); expect(verticalLine.translate(1, 1).toUnits()).toEqual([ null, null, 2, null, ]); expect(horizontalLine.translate(1, 1).toUnits()).toEqual([ null, null, null, 3, ]); expect(line1.toUnits()).toEqual([2, 1, null, null]); expect(line1.translate(0, 1).toUnits()).toEqual([2, 2, null, null]); expect(line1.translate(1, 1).toUnits()).toEqual([2, 0, null, null]); }); it('getPerpendicular', () => { const verticalLine = Line.fromPoints({ x: 1, y: 2 }, { x: 1, y: 3 }); const horizontalLine = Line.fromPoints({ x: 1, y: 2 }, { x: 9, y: 2 }); const line1 = Line.fromPoints({ x: 0, y: 1 }, { x: 1, y: 3 }); const point = { x: -2, y: 2 }; expect(verticalLine.getPerpendicular(point).toUnits()).toEqual([ null, null, null, 2, ]); expect(horizontalLine.getPerpendicular(point).toUnits()).toEqual([ null, null, -2, null, ]); expect(line1.getPerpendicular(point).toUnits()).toEqual([ -0.5, 1, null, null, ]); }); }); });
zombieJ/malfurion
0
A svg control lib
TypeScript
zombieJ
二货爱吃白萝卜
alipay
.eslintrc.js
JavaScript
const base = require('@umijs/fabric/dist/eslint'); module.exports = { ...base, rules: { ...base.rules, 'default-case': 0, 'react/sort-comp': 0, 'react/no-array-index-key': 0, 'react/no-access-state-in-setstate': 0, 'no-plusplus': 0, 'no-param-reassign': 0, 'react/require-default-props': 0, 'no-underscore-dangle': 0, 'react/no-find-dom-node': 0, 'no-mixed-operators': 0, 'prefer-destructuring': 0, 'react/no-unused-prop-types': 0, 'max-len': 0, 'max-classes-per-file': 0, 'import/no-extraneous-dependencies': [ 'error', { devDependencies: true, optionalDependencies: false, peerDependencies: false }, ], 'brace-style': 0, 'no-unused-expressions': 0, '@typescript-eslint/no-unused-expressions': 1, }, };
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
.fatherrc.js
JavaScript
export default { cjs: 'babel', esm: { type: 'babel', importLibToEs: true }, preCommit: { eslint: true, prettier: true, }, runtimeHelpers: true, };
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
assets/dropdown.less
LESS
@tabs-prefix-cls: rc-tabs; .@{tabs-prefix-cls}-dropdown { position: absolute; background: #fefefe; border: 1px solid black; max-height: 200px; overflow: auto; &-hidden { display: none; } &-menu { margin: 0; padding: 0; list-style: none; &-item { padding: 4px 8px; &-selected { background: red; } &-disabled { opacity: 0.3; cursor: not-allowed; } } } }
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
assets/index.less
LESS
@import './dropdown.less'; @import './panels.less'; @import './position.less'; @import './rtl.less'; @tabs-prefix-cls: rc-tabs; @easing-in-out: cubic-bezier(0.35, 0, 0.25, 1); @effect-duration: 0.3s; .@{tabs-prefix-cls} { border: 1px solid gray; font-size: 14px; overflow: hidden; // ========================== Navigation ========================== &-nav { display: flex; flex: none; position: relative; &-measure, &-wrap { transform: translate(0); position: relative; display: inline-block; flex: auto; white-space: nowrap; overflow: hidden; display: flex; &-ping-left::before, &-ping-right::after { content: ''; position: absolute; top: 0; bottom: 0; } &-ping-left::before { left: 0; border-left: 1px solid red; } &-ping-right::after { right: 0; border-right: 1px solid red; } &-ping-top::before, &-ping-bottom::after { content: ''; position: absolute; left: 0; right: 0; } &-ping-top::before { top: 0; border-top: 1px solid red; } &-ping-bottom::after { bottom: 0; border-top: 1px solid red; } } &-list { display: flex; position: relative; transition: transform 0.3s; } // >>>>>>>> Operations &-operations { display: flex; &-hidden { position: absolute; visibility: hidden; pointer-events: none; } } &-more { border: 1px solid blue; background: rgba(255, 0, 0, 0.1); } &-add { border: 1px solid green; background: rgba(0, 255, 0, 0.1); } } &-tab { border: 0; font-size: 20px; background: rgba(255, 255, 255, 0.5); margin: 0; display: flex; outline: none; cursor: pointer; position: relative; font-weight: lighter; align-items: center; &-btn, &-remove { border: 0; background: transparent; } &-btn { font-weight: inherit; line-height: 32px; } &-remove { &:hover { color: red; } } &-active { // padding-left: 30px; font-weight: bolder; } } &-ink-bar { position: absolute; background: red; pointer-events: none; &-animated { transition: all 0.3s; } } &-extra-content { flex: none; } }
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
assets/panels.less
LESS
@tabs-prefix-cls: rc-tabs; .@{tabs-prefix-cls} { &-content { &-holder { flex: auto; } display: flex; width: 100%; &-animated { transition: margin 0.3s; } } &-tabpane { width: 100%; flex: none; } }
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
assets/position.less
LESS
@tabs-prefix-cls: rc-tabs; .@{tabs-prefix-cls} { display: flex; // ========================== Vertical ========================== &-top, &-bottom { flex-direction: column; .@{tabs-prefix-cls}-ink-bar { height: 3px; } } &-top { .@{tabs-prefix-cls}-ink-bar { bottom: 0; } } &-bottom { .@{tabs-prefix-cls}-nav { order: 1; } .@{tabs-prefix-cls}-content { order: 0; } .@{tabs-prefix-cls}-ink-bar { top: 0; } } // ========================= Horizontal ========================= &-left, &-right { &.@{tabs-prefix-cls}-editable .@{tabs-prefix-cls}-tab { padding-right: 32px; } .@{tabs-prefix-cls}-nav-wrap { flex-direction: column; } .@{tabs-prefix-cls}-ink-bar { width: 3px; } .@{tabs-prefix-cls}-nav { flex-direction: column; min-width: 50px; &-list { flex-direction: column; } &-operations { flex-direction: column; } } } &-left { .@{tabs-prefix-cls}-ink-bar { right: 0; } } &-right { .@{tabs-prefix-cls}-nav { order: 1; } .@{tabs-prefix-cls}-content { order: 0; } .@{tabs-prefix-cls}-ink-bar { left: 0; } } }
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
assets/rtl.less
LESS
@tabs-prefix-cls: rc-tabs; .@{tabs-prefix-cls} { &-rtl { direction: rtl; } &-dropdown-rtl { direction: rtl; } }
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
examples/basic.tsx
TypeScript (TSX)
import React from 'react'; import Tabs, { TabPane } from '../src'; import '../assets/index.less'; export default () => { const [destroy, setDestroy] = React.useState(false); const [children, setChildren] = React.useState([ <TabPane key="light" tab="light"> Light </TabPane>, <TabPane key="bamboo" tab="bamboo"> Bamboo </TabPane>, <TabPane key="cute" tab="cute" disabled> Cute </TabPane>, ]); if (destroy) { return null; } return ( <React.StrictMode> <Tabs tabBarExtraContent="extra">{children}</Tabs> <button type="button" onClick={() => { setChildren([ <TabPane key="Yo" tab="yo"> Yo! </TabPane>, ]); }} > Change children </button> <button type="button" onClick={() => { setDestroy(true); }} > Destroy </button> </React.StrictMode> ); };
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
examples/extra.tsx
TypeScript (TSX)
/* eslint-disable jsx-a11y/label-has-for, jsx-a11y/label-has-associated-control */ import React from 'react'; import Tabs, { TabPane } from '../src'; import '../assets/index.less'; const tabs: React.ReactElement[] = []; for (let i = 0; i < 50; i += 1) { tabs.push( <TabPane key={i} tab={`Tab ${i}`}> Content of {i} </TabPane>, ); } type P = 'default' | 'left' | 'right'; type Content<T> = Record<P, T>; const content: Content<React.ReactNode> = { default: 'default', left: 'left', right: 'right', }; export default () => { const [isDefault, setIsDefault] = React.useState(true); const [position, setPosition] = React.useState<P[]>([]); const checkRef = React.useRef<any>(null); const extra = React.useMemo(() => { if (isDefault) { return content.default; } if (position.length === 0) { return undefined; } return position.reduce((acc, cur: P) => { return { ...acc, [cur]: content[cur], }; }, {}); }, [isDefault, position]); const setBothSide = () => { if (position.length < 2) { setPosition(['left', 'right']); } }; const handleCheck = (pos: P) => { const nextPos = () => { const add = position.indexOf(pos) === -1; if (add) { return [...position, pos]; } return position.filter(item => item !== pos); }; setPosition(nextPos()); }; const overall = React.useMemo(() => { if (position.length === 0) { return { checked: false, indeterminate: false, }; } if (position.length === 2) { return { checked: true, indeterminate: false, }; } return { checked: false, indeterminate: true, }; }, [position]); React.useEffect(() => { checkRef.current.indeterminate = overall.indeterminate; }, [overall]); React.useEffect(() => { if (isDefault) { setPosition([]); } }, [isDefault]); React.useEffect(() => { if (position.length > 0) { setIsDefault(false); } }, [position]); return ( <div style={{ maxWidth: 550 }}> <Tabs tabBarExtraContent={extra} defaultActiveKey="8" moreIcon="..."> {tabs} </Tabs> <div style={{ display: 'flex' }}> <div> <input id="default-position" type="radio" checked={isDefault} onChange={() => { setIsDefault(true); }} /> <label htmlFor="default-position">default position(right)</label> </div> <div style={{ marginLeft: '15px' }}> <input id="coustom-position" ref={checkRef} type={overall.indeterminate ? 'checkbox' : 'radio'} checked={overall.checked} onChange={setBothSide} /> <label htmlFor="coustom-position">coustom position</label> <ul> <li> <input id="left" type="checkbox" checked={position.indexOf('left') !== -1} onChange={() => { handleCheck('left'); }} /> <label htmlFor="left">left</label> </li> <li> <input id="right" type="checkbox" checked={position.indexOf('right') !== -1} onChange={() => { handleCheck('right'); }} /> <label htmlFor="right">right</label> </li> </ul> </div> </div> </div> ); };
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
examples/mix.tsx
TypeScript (TSX)
/* eslint-disable jsx-a11y/label-has-for, jsx-a11y/label-has-associated-control */ import React from 'react'; import Tabs, { TabPane } from '../src'; import '../assets/index.less'; function getTabPanes(count = 50) { const tabs: React.ReactElement[] = []; for (let i = 0; i < count; i += 1) { tabs.push( <TabPane key={i} tab={`Tab ${i}`} disabled={i === 3} closable={i === 5 ? false : undefined}> Content of {i} </TabPane>, ); } return tabs; } export default () => { const [activeKey, setActiveKey] = React.useState<string>(undefined); const [position, setPosition] = React.useState<any>('top'); const [gutter, setGutter] = React.useState(false); const [fixHeight, setFixHeight] = React.useState(true); const [rtl, setRTL] = React.useState(false); const [editable, setEditable] = React.useState(true); const [destroyInactiveTabPane, setDestroyInactiveTabPane] = React.useState(false); const [destroy, setDestroy] = React.useState(false); const [animated, setAnimated] = React.useState(true); const [tabPanes, setTabPanes] = React.useState(getTabPanes(10)); const editableConfig = editable ? { onEdit: ( type: string, info: { key?: string; event: React.MouseEvent | React.KeyboardEvent }, ) => { if (type === 'remove') { setTabPanes(tabs => tabs.filter(tab => tab.key !== info.key)); } else { setTabPanes(tabs => { const lastTab = tabs[tabs.length - 1]; const num = Number(lastTab.key) + 1; return [ ...tabs, <TabPane key={num} tab={`Tab ${num}`}> Content of {num} </TabPane>, ]; }); } }, } : null; return ( <div style={{ minHeight: 2000 }}> <div> {/* tabBarGutter */} <label> <input type="checkbox" checked={gutter} onChange={() => setGutter(val => !val)} /> Set `tabBarGutter` </label> {/* animated */} <label> <input type="checkbox" checked={animated} onChange={() => setAnimated(val => !val)} /> Set `animated.tabPane` </label> {/* fixHeight */} <label> <input type="checkbox" checked={fixHeight} onChange={() => setFixHeight(val => !val)} /> Set fixed height </label> {/* editable */} <label> <input type="checkbox" checked={editable} onChange={() => setEditable(val => !val)} /> Set Editable </label> {/* editable */} <label> <input type="checkbox" checked={destroyInactiveTabPane} onChange={() => setDestroyInactiveTabPane(val => !val)} /> Destroy Inactive TabPane </label> {/* direction */} <label> <input type="checkbox" checked={rtl} onChange={() => setRTL(val => !val)} /> Set `direction=rtl` </label> {/* Change children */} <button type="button" onClick={() => { const counts = [50, 10, 0]; const count = counts[(counts.indexOf(tabPanes.length) + 1) % counts.length]; console.log('>>>', count); setTabPanes(getTabPanes(count)); }} > Change TabPanes </button> {/* Active random */} <button type="button" onClick={() => { const { key } = tabPanes[Math.floor(tabPanes.length * Math.random())]; // setActiveKey('29'); setActiveKey(String(key)); console.log('Random Key:', key); }} > Active Random </button> {/* Position */} <select value={position} onChange={e => setPosition(e.target.value)}> <option>left</option> <option>right</option> <option>top</option> <option>bottom</option> </select> {/* destroy */} <button type="button" onClick={() => { setDestroy(!destroy); }} > Destroy </button> </div> {!destroy && ( <React.StrictMode> <Tabs activeKey={activeKey} onChange={key => { if (activeKey !== undefined) { setActiveKey(key); } }} onTabScroll={info => { console.log('Scroll:', info); }} destroyInactiveTabPane={destroyInactiveTabPane} animated={{ tabPane: animated }} editable={editableConfig} direction={rtl ? 'rtl' : null} tabPosition={position} tabBarGutter={gutter ? 32 : null} tabBarExtraContent="extra" defaultActiveKey="30" moreIcon="..." // moreTransitionName="233" style={{ height: fixHeight ? 300 : null }} > {tabPanes} </Tabs> </React.StrictMode> )} </div> ); };
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
examples/overflow.tsx
TypeScript (TSX)
/* eslint-disable jsx-a11y/label-has-for, jsx-a11y/label-has-associated-control */ import React from 'react'; import Tabs, { TabPane } from '../src'; import '../assets/index.less'; const tabs: React.ReactElement[] = []; for (let i = 0; i < 50; i += 1) { tabs.push( <TabPane key={i} tab={`Tab ${i}`}> Content of {i} </TabPane>, ); } export default () => { const [gutter, setGutter] = React.useState(true); const [destroy, setDestroy] = React.useState(false); if (destroy) { return null; } return ( <div style={{ height: 2000 }}> <React.StrictMode> <div style={{ maxWidth: 550 }}> <Tabs tabBarGutter={gutter ? 32 : null} tabBarExtraContent="extra" defaultActiveKey="8" moreIcon="..." > {tabs} </Tabs> </div> </React.StrictMode> <label> <input type="checkbox" checked={gutter} onChange={() => setGutter(!gutter)} /> Set `tabBarGutter` </label> <button type="button" onClick={() => { setDestroy(true); }} > Destroy </button> </div> ); };
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
examples/position.tsx
TypeScript (TSX)
/* eslint-disable jsx-a11y/label-has-for, jsx-a11y/label-has-associated-control */ import React from 'react'; import Tabs, { TabPane } from '../src'; import '../assets/index.less'; export default () => { const [position, setPosition] = React.useState<any>('left'); const [gutter, setGutter] = React.useState(false); const [fixedHeight, setFixedHeight] = React.useState(false); return ( <React.StrictMode> <select value={position} onChange={e => setPosition(e.target.value)}> <option>left</option> <option>right</option> <option>top</option> <option>bottom</option> </select> <label> <input type="checkbox" checked={fixedHeight} onChange={() => setFixedHeight(!fixedHeight)} /> Fixed Height </label> <label> <input type="checkbox" checked={gutter} onChange={() => setGutter(!gutter)} /> Set Gutter </label> <Tabs tabBarExtraContent={233} tabPosition={position} style={{ height: fixedHeight ? 180 : undefined }} tabBarGutter={gutter ? 16 : null} > <TabPane key="light" tab="light"> Light </TabPane> <TabPane key="bamboo" tab="bamboo"> Bamboo </TabPane> <TabPane key="cat" tab="cat"> Cat </TabPane> <TabPane key="miu" tab="miu"> Miu </TabPane> <TabPane key="333" tab="333"> 3333 </TabPane> <TabPane key="4444" tab="4444"> 4444 </TabPane> </Tabs> </React.StrictMode> ); };
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
examples/renderTabBar-dragable.tsx
TypeScript (TSX)
/* eslint-disable import/no-named-as-default-member */ import React from 'react'; import { DndProvider, DragSource, DropTarget } from 'react-dnd'; import HTML5Backend from 'react-dnd-html5-backend'; import Tabs from '../src'; import '../assets/index.less'; const { TabPane } = Tabs; // Drag & Drop node class TabNode extends React.Component<any, any> { render() { const { connectDragSource, connectDropTarget, children } = this.props; return connectDragSource(connectDropTarget(children)); } } const cardTarget = { drop(props, monitor) { const dragKey = monitor.getItem().index; const hoverKey = props.index; if (dragKey === hoverKey) { return; } props.moveTabNode(dragKey, hoverKey); monitor.getItem().index = hoverKey; }, }; const cardSource = { beginDrag(props) { return { id: props.id, index: props.index, }; }, }; const WrapTabNode = DropTarget('DND_NODE', cardTarget, connect => ({ connectDropTarget: connect.dropTarget(), }))( DragSource('DND_NODE', cardSource, (connect, monitor) => ({ connectDragSource: connect.dragSource(), isDragging: monitor.isDragging(), }))(TabNode), ); class DraggableTabs extends React.Component { state = { order: [], }; moveTabNode = (dragKey, hoverKey) => { const newOrder = this.state.order.slice(); const { children } = this.props; React.Children.forEach(children, (c: React.ReactElement) => { if (newOrder.indexOf(c.key) === -1) { newOrder.push(c.key); } }); const dragIndex = newOrder.indexOf(dragKey); const hoverIndex = newOrder.indexOf(hoverKey); newOrder.splice(dragIndex, 1); newOrder.splice(hoverIndex, 0, dragKey); this.setState({ order: newOrder, }); }; renderTabBar = (props, DefaultTabBar) => ( <DefaultTabBar {...props}> {node => { return ( <WrapTabNode key={node.key} index={node.key} moveTabNode={this.moveTabNode}> {node} </WrapTabNode> ); }} </DefaultTabBar> ); render() { const { order } = this.state; const { children } = this.props; const tabs = []; React.Children.forEach(children, c => { tabs.push(c); }); const orderTabs = tabs.slice().sort((a, b) => { const orderA = order.indexOf(a.key); const orderB = order.indexOf(b.key); if (orderA !== -1 && orderB !== -1) { return orderA - orderB; } if (orderA !== -1) { return -1; } if (orderB !== -1) { return 1; } const ia = tabs.indexOf(a); const ib = tabs.indexOf(b); return ia - ib; }); return ( <DndProvider backend={HTML5Backend}> <Tabs renderTabBar={this.renderTabBar} {...this.props}> {orderTabs} </Tabs> </DndProvider> ); } } export default () => ( <DraggableTabs> <TabPane tab="tab 1" key="1"> Content of Tab Pane 1 </TabPane> <TabPane tab="tab 2" key="2"> Content of Tab Pane 2 </TabPane> <TabPane tab="tab 3" key="3"> Content of Tab Pane 3 </TabPane> </DraggableTabs> );
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
examples/renderTabBar-sticky.tsx
TypeScript (TSX)
import React from 'react'; import { StickyContainer, Sticky } from 'react-sticky'; import Tabs, { TabPane } from '../src'; import '../assets/index.less'; const renderTabBar = (props, DefaultTabBar) => ( <Sticky bottomOffset={80}> {({ style }) => ( <DefaultTabBar {...props} className="site-custom-tab-bar" style={{ ...style, zIndex: 1, background: '#fff' }} /> )} </Sticky> ); export default () => { return ( <div style={{ height: 2000 }}> <StickyContainer> <Tabs defaultActiveKey="1" renderTabBar={renderTabBar}> <TabPane tab="Tab 1" key="1" style={{ height: 200 }}> Content of Tab Pane 1 </TabPane> <TabPane tab="Tab 2" key="2"> Content of Tab Pane 2 </TabPane> <TabPane tab="Tab 3" key="3"> Content of Tab Pane 3 </TabPane> </Tabs> </StickyContainer> </div> ); };
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
examples/renderTabBar-use-panes.tsx
TypeScript (TSX)
import React from 'react'; import Tabs, { TabPane } from '../src'; import '../assets/index.less'; const renderTabBar = props => { return ( <div> {props.panes.map(pane => { const key = pane.key; return <span key={key}>{key}</span>; })} </div> ); }; export default () => { return ( <div style={{ height: 2000 }}> <Tabs defaultActiveKey="1" renderTabBar={renderTabBar}> <TabPane tab="Tab 1" key="1" style={{ height: 200 }}> Content of Tab Pane 1 </TabPane> <TabPane tab="Tab 2" key="2"> Content of Tab Pane 2 </TabPane> <TabPane tab="Tab 3" key="3"> Content of Tab Pane 3 </TabPane> </Tabs> </div> ); };
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
jest.config.js
JavaScript
module.exports = { setupFiles: ['./tests/setup.js'], snapshotSerializers: [require.resolve('enzyme-to-json/serializer')], };
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/TabContext.ts
TypeScript
import { createContext } from 'react'; import { Tab } from './interface'; export interface TabContextProps { tabs: Tab[]; prefixCls: string; } export default createContext<TabContextProps>(null);
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/TabNavList/AddButton.tsx
TypeScript (TSX)
import * as React from 'react'; import { EditableConfig, TabsLocale } from '../interface'; export interface AddButtonProps { prefixCls: string; editable?: EditableConfig; locale?: TabsLocale; style?: React.CSSProperties; } function AddButton( { prefixCls, editable, locale, style }: AddButtonProps, ref: React.Ref<HTMLButtonElement>, ) { if (!editable || editable.showAdd === false) { return null; } return ( <button ref={ref} type="button" className={`${prefixCls}-nav-add`} style={style} aria-label={locale?.addAriaLabel || 'Add tab'} onClick={event => { editable.onEdit('add', { event, }); }} > {editable.addIcon || '+'} </button> ); } export default React.forwardRef(AddButton);
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/TabNavList/OperationNode.tsx
TypeScript (TSX)
import * as React from 'react'; import classNames from 'classnames'; import { useState, useEffect } from 'react'; import KeyCode from 'rc-util/lib/KeyCode'; import Menu, { MenuItem } from 'rc-menu'; import Dropdown from 'rc-dropdown'; import { Tab, TabsLocale, EditableConfig } from '../interface'; import AddButton from './AddButton'; export interface OperationNodeProps { prefixCls: string; className?: string; style?: React.CSSProperties; id: string; tabs: Tab[]; rtl: boolean; tabBarGutter?: number; activeKey: string; mobile: boolean; moreIcon?: React.ReactNode; moreTransitionName?: string; editable?: EditableConfig; locale?: TabsLocale; onTabClick: (key: React.Key, e: React.MouseEvent | React.KeyboardEvent) => void; } function OperationNode( { prefixCls, id, tabs, locale, mobile, moreIcon = 'More', moreTransitionName, style, className, editable, tabBarGutter, rtl, onTabClick, }: OperationNodeProps, ref: React.Ref<HTMLDivElement>, ) { // ======================== Dropdown ======================== const [open, setOpen] = useState(false); const [selectedKey, setSelectedKey] = useState<string>(null); const popupId = `${id}-more-popup`; const dropdownPrefix = `${prefixCls}-dropdown`; const selectedItemId = selectedKey !== null ? `${popupId}-${selectedKey}` : null; const dropdownAriaLabel = locale?.dropdownAriaLabel; const menu = ( <Menu onClick={({ key, domEvent }) => { onTabClick(key, domEvent); setOpen(false); }} id={popupId} tabIndex={-1} role="listbox" aria-activedescendant={selectedItemId} selectedKeys={[selectedKey]} aria-label={dropdownAriaLabel !== undefined ? dropdownAriaLabel : 'expanded dropdown'} > {tabs.map(tab => ( <MenuItem key={tab.key} id={`${popupId}-${tab.key}`} role="option" aria-controls={id && `${id}-panel-${tab.key}`} disabled={tab.disabled} > {tab.tab} </MenuItem> ))} </Menu> ); function selectOffset(offset: -1 | 1) { const enabledTabs = tabs.filter(tab => !tab.disabled); let selectedIndex = enabledTabs.findIndex(tab => tab.key === selectedKey) || 0; const len = enabledTabs.length; for (let i = 0; i < len; i += 1) { selectedIndex = (selectedIndex + offset + len) % len; const tab = enabledTabs[selectedIndex]; if (!tab.disabled) { setSelectedKey(tab.key); return; } } } function onKeyDown(e: React.KeyboardEvent) { const { which } = e; if (!open) { if ([KeyCode.DOWN, KeyCode.SPACE, KeyCode.ENTER].includes(which)) { setOpen(true); e.preventDefault(); } return; } switch (which) { case KeyCode.UP: selectOffset(-1); e.preventDefault(); break; case KeyCode.DOWN: selectOffset(1); e.preventDefault(); break; case KeyCode.ESC: setOpen(false); break; case KeyCode.SPACE: case KeyCode.ENTER: if (selectedKey !== null) onTabClick(selectedKey, e); break; } } // ========================= Effect ========================= useEffect(() => { // We use query element here to avoid React strict warning const ele = document.getElementById(selectedItemId); if (ele && ele.scrollIntoView) { ele.scrollIntoView(false); } }, [selectedKey]); useEffect(() => { if (!open) { setSelectedKey(null); } }, [open]); // ========================= Render ========================= const moreStyle: React.CSSProperties = { [rtl ? 'marginLeft' : 'marginRight']: tabBarGutter, }; if (!tabs.length) { moreStyle.visibility = 'hidden'; moreStyle.order = 1; } const overlayClassName = classNames({ [`${dropdownPrefix}-rtl`]: rtl }) const moreNode: React.ReactElement = mobile ? null : ( <Dropdown prefixCls={dropdownPrefix} overlay={menu} trigger={['hover']} visible={open} transitionName={moreTransitionName} onVisibleChange={setOpen} overlayClassName={overlayClassName} mouseEnterDelay={0.1} mouseLeaveDelay={0.1} > <button type="button" className={`${prefixCls}-nav-more`} style={moreStyle} tabIndex={-1} aria-hidden="true" aria-haspopup="listbox" aria-controls={popupId} id={`${id}-more`} aria-expanded={open} onKeyDown={onKeyDown} > {moreIcon} </button> </Dropdown> ); return ( <div className={classNames(`${prefixCls}-nav-operations`, className)} style={style} ref={ref}> {moreNode} <AddButton prefixCls={prefixCls} locale={locale} editable={editable} /> </div> ); } export default React.forwardRef(OperationNode);
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/TabNavList/TabNode.tsx
TypeScript (TSX)
import * as React from 'react'; import classNames from 'classnames'; import KeyCode from 'rc-util/lib/KeyCode'; import { Tab, TabPosition, EditableConfig } from '../interface'; export interface TabNodeProps { id: string; prefixCls: string; tab: Tab; active: boolean; rtl: boolean; closable?: boolean; editable?: EditableConfig; onClick?: (e: React.MouseEvent | React.KeyboardEvent) => void; onResize?: (width: number, height: number, left: number, top: number) => void; tabBarGutter?: number; tabPosition: TabPosition; renderWrapper?: (node: React.ReactElement) => React.ReactElement; removeAriaLabel?: string; removeIcon?: React.ReactNode; onRemove: () => void; onFocus: React.FocusEventHandler; } function TabNode( { prefixCls, id, active, rtl, tab: { key, tab, disabled, closeIcon }, tabBarGutter, tabPosition, closable, renderWrapper, removeAriaLabel, editable, onClick, onRemove, onFocus, }: TabNodeProps, ref: React.Ref<HTMLDivElement>, ) { const tabPrefix = `${prefixCls}-tab`; React.useEffect(() => onRemove, []); const nodeStyle: React.CSSProperties = {}; if (tabPosition === 'top' || tabPosition === 'bottom') { nodeStyle[rtl ? 'marginLeft' : 'marginRight'] = tabBarGutter; } else { nodeStyle.marginBottom = tabBarGutter; } const removable = editable && closable !== false && !disabled; function onInternalClick(e: React.MouseEvent | React.KeyboardEvent) { if (disabled) return; onClick(e); } function onRemoveTab(event: React.MouseEvent | React.KeyboardEvent) { event.preventDefault(); event.stopPropagation(); editable.onEdit('remove', { key, event, }); } let node: React.ReactElement = ( <div key={key} ref={ref} className={classNames(tabPrefix, { [`${tabPrefix}-with-remove`]: removable, [`${tabPrefix}-active`]: active, [`${tabPrefix}-disabled`]: disabled, })} style={nodeStyle} onClick={onInternalClick} > {/* Primary Tab Button */} <div role="tab" aria-selected={active} id={id && `${id}-tab-${key}`} className={`${tabPrefix}-btn`} aria-controls={id && `${id}-panel-${key}`} aria-disabled={disabled} tabIndex={disabled ? null : 0} onClick={e => { e.stopPropagation(); onInternalClick(e); }} onKeyDown={e => { if ([KeyCode.SPACE, KeyCode.ENTER].includes(e.which)) { e.preventDefault(); onInternalClick(e); } }} onFocus={onFocus} > {tab} </div> {/* Remove Button */} {removable && ( <button type="button" aria-label={removeAriaLabel || 'remove'} tabIndex={0} className={`${tabPrefix}-remove`} onClick={e => { e.stopPropagation(); onRemoveTab(e); }} > {closeIcon || editable.removeIcon || '×'} </button> )} </div> ); if (renderWrapper) { node = renderWrapper(node); } return node; } export default React.forwardRef(TabNode);
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/TabNavList/index.tsx
TypeScript (TSX)
import * as React from 'react'; import { useState, useRef, useEffect } from 'react'; import classNames from 'classnames'; import raf from 'raf'; import ResizeObserver from 'rc-resize-observer'; import useRaf, { useRafState } from '../hooks/useRaf'; import TabNode from './TabNode'; import { TabSizeMap, TabPosition, RenderTabBar, TabsLocale, EditableConfig, AnimatedConfig, OnTabScroll, TabBarExtraPosition, TabBarExtraContent, TabBarExtraMap } from '../interface'; import useOffsets from '../hooks/useOffsets'; import useVisibleRange from '../hooks/useVisibleRange'; import OperationNode from './OperationNode'; import TabContext from '../TabContext'; import useTouchMove from '../hooks/useTouchMove'; import useRefs from '../hooks/useRefs'; import AddButton from './AddButton'; import useSyncState from '../hooks/useSyncState'; export interface TabNavListProps { id: string; tabPosition: TabPosition; activeKey: string; rtl: boolean; panes: React.ReactNode; animated?: AnimatedConfig; extra?: TabBarExtraContent; editable?: EditableConfig; moreIcon?: React.ReactNode; moreTransitionName?: string; mobile: boolean; tabBarGutter?: number; renderTabBar?: RenderTabBar; className?: string; style?: React.CSSProperties; locale?: TabsLocale; onTabClick: (activeKey: React.Key, e: React.MouseEvent | React.KeyboardEvent) => void; onTabScroll?: OnTabScroll; children?: (node: React.ReactElement) => React.ReactElement; } interface ExtraContentProps { position: TabBarExtraPosition; prefixCls: string; extra?: TabBarExtraContent; } const ExtraContent = ({ position, prefixCls, extra }: ExtraContentProps) => { if (!extra) return null; let content: React.ReactNode; const assertExtra = extra as TabBarExtraMap; if (position === 'right') { content = assertExtra.right || (!assertExtra.left && assertExtra) || null; } if (position === 'left') { content = assertExtra.left || null; } return content ? <div className={`${prefixCls}-extra-content`}>{content}</div> : null; }; function TabNavList(props: TabNavListProps, ref: React.Ref<HTMLDivElement>) { const { prefixCls, tabs } = React.useContext(TabContext); const { className, style, id, animated, activeKey, rtl, extra, editable, locale, tabPosition, tabBarGutter, children, onTabClick, onTabScroll, } = props; const tabsWrapperRef = useRef<HTMLDivElement>(); const tabListRef = useRef<HTMLDivElement>(); const operationsRef = useRef<HTMLDivElement>(); const innerAddButtonRef = useRef<HTMLButtonElement>(); const [getBtnRef, removeBtnRef] = useRefs<HTMLDivElement>(); const tabPositionTopOrBottom = tabPosition === 'top' || tabPosition === 'bottom'; const [transformLeft, setTransformLeft] = useSyncState(0, (next, prev) => { if (tabPositionTopOrBottom && onTabScroll) { onTabScroll({ direction: next > prev ? 'left' : 'right' }); } }); const [transformTop, setTransformTop] = useSyncState(0, (next, prev) => { if (!tabPositionTopOrBottom && onTabScroll) { onTabScroll({ direction: next > prev ? 'top' : 'bottom' }); } }); const [wrapperScrollWidth, setWrapperScrollWidth] = useState<number>(0); const [wrapperScrollHeight, setWrapperScrollHeight] = useState<number>(0); const [wrapperContentWidth, setWrapperContentWidth] = useState<number>(0); const [wrapperContentHeight, setWrapperContentHeight] = useState<number>(0); const [wrapperWidth, setWrapperWidth] = useState<number>(null); const [wrapperHeight, setWrapperHeight] = useState<number>(null); const [addWidth, setAddWidth] = useState<number>(0); const [addHeight, setAddHeight] = useState<number>(0); const [tabSizes, setTabSizes] = useRafState<TabSizeMap>(new Map()); const tabOffsets = useOffsets(tabs, tabSizes, wrapperScrollWidth); // ========================== Util ========================= const operationsHiddenClassName = `${prefixCls}-nav-operations-hidden`; let transformMin = 0; let transformMax = 0; if (!tabPositionTopOrBottom) { transformMin = Math.min(0, wrapperHeight - wrapperScrollHeight); transformMax = 0; } else if (rtl) { transformMin = 0; transformMax = Math.max(0, wrapperScrollWidth - wrapperWidth); } else { transformMin = Math.min(0, wrapperWidth - wrapperScrollWidth); transformMax = 0; } function alignInRange(value: number): [number, boolean] { if (value < transformMin) { return [transformMin, false]; } if (value > transformMax) { return [transformMax, false]; } return [value, true]; } // ========================= Mobile ======================== const touchMovingRef = useRef<number>(); const [lockAnimation, setLockAnimation] = useState<number>(); function doLockAnimation() { setLockAnimation(Date.now()); } function clearTouchMoving() { window.clearTimeout(touchMovingRef.current); } useTouchMove(tabsWrapperRef, (offsetX, offsetY) => { let preventDefault = false; function doMove(setState: React.Dispatch<React.SetStateAction<number>>, offset: number) { setState(value => { const [newValue, needPrevent] = alignInRange(value + offset); preventDefault = needPrevent; return newValue; }); } if (tabPositionTopOrBottom) { // Skip scroll if place is enough if (wrapperWidth >= wrapperScrollWidth) { return preventDefault; } doMove(setTransformLeft, offsetX); } else { if (wrapperHeight >= wrapperScrollHeight) { return preventDefault; } doMove(setTransformTop, offsetY); } clearTouchMoving(); doLockAnimation(); return preventDefault; }); useEffect(() => { clearTouchMoving(); if (lockAnimation) { touchMovingRef.current = window.setTimeout(() => { setLockAnimation(0); }, 100); } return clearTouchMoving; }, [lockAnimation]); // ========================= Scroll ======================== function scrollToTab(key = activeKey) { const tabOffset = tabOffsets.get(key); if (!tabOffset) return; if (tabPositionTopOrBottom) { // ============ Align with top & bottom ============ let newTransform = transformLeft; // RTL if (rtl) { if (tabOffset.right < transformLeft) { newTransform = tabOffset.right; } else if (tabOffset.right + tabOffset.width > transformLeft + wrapperWidth) { newTransform = tabOffset.right + tabOffset.width - wrapperWidth; } } // LTR else if (tabOffset.left < -transformLeft) { newTransform = -tabOffset.left; } else if (tabOffset.left + tabOffset.width > -transformLeft + wrapperWidth) { newTransform = -(tabOffset.left + tabOffset.width - wrapperWidth); } setTransformTop(0); setTransformLeft(alignInRange(newTransform)[0]); } else { // ============ Align with left & right ============ let newTransform = transformTop; if (tabOffset.top < -transformTop) { newTransform = -tabOffset.top; } else if (tabOffset.top + tabOffset.height > -transformTop + wrapperHeight) { newTransform = -(tabOffset.top + tabOffset.height - wrapperHeight); } setTransformLeft(0); setTransformTop(alignInRange(newTransform)[0]); } } // ========================== Tab ========================== // Render tab node & collect tab offset const [visibleStart, visibleEnd] = useVisibleRange( tabOffsets, { width: wrapperWidth, height: wrapperHeight, left: transformLeft, top: transformTop, }, { width: wrapperContentWidth, height: wrapperContentHeight, }, { width: addWidth, height: addHeight, }, { ...props, tabs }, ); const tabNodes: React.ReactElement[] = tabs.map(tab => { const { key } = tab; return ( <TabNode id={id} prefixCls={prefixCls} key={key} rtl={rtl} tab={tab} closable={tab.closable} editable={editable} active={key === activeKey} tabPosition={tabPosition} tabBarGutter={tabBarGutter} renderWrapper={children} removeAriaLabel={locale?.removeAriaLabel} ref={getBtnRef(key)} onClick={e => { onTabClick(key, e); }} onRemove={() => { removeBtnRef(key); }} onFocus={() => { scrollToTab(key); doLockAnimation(); // Focus element will make scrollLeft change which we should reset back if (!rtl) { tabsWrapperRef.current.scrollLeft = 0; } tabsWrapperRef.current.scrollTop = 0; }} /> ); }); const onListHolderResize = useRaf(() => { // Update wrapper records const offsetWidth = tabsWrapperRef.current?.offsetWidth || 0; const offsetHeight = tabsWrapperRef.current?.offsetHeight || 0; const newAddWidth = innerAddButtonRef.current?.offsetWidth || 0; const newAddHeight = innerAddButtonRef.current?.offsetHeight || 0; const newOperationWidth = operationsRef.current?.offsetWidth || 0; const newOperationHeight = operationsRef.current?.offsetHeight || 0; setWrapperWidth(offsetWidth); setWrapperHeight(offsetHeight); setAddWidth(newAddWidth); setAddHeight(newAddHeight); const newWrapperScrollWidth = (tabListRef.current?.offsetWidth || 0) - newAddWidth; const newWrapperScrollHeight = (tabListRef.current?.offsetHeight || 0) - newAddHeight; setWrapperScrollWidth(newWrapperScrollWidth); setWrapperScrollHeight(newWrapperScrollHeight); const isOperationHidden = operationsRef.current?.className.includes(operationsHiddenClassName); setWrapperContentWidth(newWrapperScrollWidth - (isOperationHidden ? 0 : newOperationWidth)); setWrapperContentHeight(newWrapperScrollHeight - (isOperationHidden ? 0 : newOperationHeight)); // Update buttons records setTabSizes(() => { const newSizes: TabSizeMap = new Map(); tabs.forEach(({ key }) => { const btnNode = getBtnRef(key).current; if (btnNode) { newSizes.set(key, { width: btnNode.offsetWidth, height: btnNode.offsetHeight, left: btnNode.offsetLeft, top: btnNode.offsetTop, }); } }); return newSizes; }); }); // ======================== Dropdown ======================= const startHiddenTabs = tabs.slice(0, visibleStart); const endHiddenTabs = tabs.slice(visibleEnd + 1); const hiddenTabs = [...startHiddenTabs, ...endHiddenTabs]; // =================== Link & Operations =================== const [inkStyle, setInkStyle] = useState<React.CSSProperties>(); const activeTabOffset = tabOffsets.get(activeKey); // Delay set ink style to avoid remove tab blink const inkBarRafRef = useRef<number>(); function cleanInkBarRaf() { raf.cancel(inkBarRafRef.current); } useEffect(() => { const newInkStyle: React.CSSProperties = {}; if (activeTabOffset) { if (tabPositionTopOrBottom) { if (rtl) { newInkStyle.right = activeTabOffset.right; } else { newInkStyle.left = activeTabOffset.left; } newInkStyle.width = activeTabOffset.width; } else { newInkStyle.top = activeTabOffset.top; newInkStyle.height = activeTabOffset.height; } } cleanInkBarRaf(); inkBarRafRef.current = raf(() => { setInkStyle(newInkStyle); }); return cleanInkBarRaf; }, [activeTabOffset, tabPositionTopOrBottom, rtl]); // ========================= Effect ======================== useEffect(() => { scrollToTab(); }, [activeKey, activeTabOffset, tabOffsets, tabPositionTopOrBottom]); // Should recalculate when rtl changed useEffect(() => { onListHolderResize(); }, [rtl, tabBarGutter, activeKey, tabs.map(tab => tab.key).join('_')]); // ========================= Render ======================== const hasDropdown = !!hiddenTabs.length; const wrapPrefix = `${prefixCls}-nav-wrap`; let pingLeft: boolean; let pingRight: boolean; let pingTop: boolean; let pingBottom: boolean; if (tabPositionTopOrBottom) { if (rtl) { pingRight = transformLeft > 0; pingLeft = transformLeft + wrapperWidth < wrapperScrollWidth; } else { pingLeft = transformLeft < 0; pingRight = -transformLeft + wrapperWidth < wrapperScrollWidth; } } else { pingTop = transformTop < 0; pingBottom = -transformTop + wrapperHeight < wrapperScrollHeight; } /* eslint-disable jsx-a11y/interactive-supports-focus */ return ( <div ref={ref} role="tablist" className={classNames(`${prefixCls}-nav`, className)} style={style} onKeyDown={() => { // No need animation when use keyboard doLockAnimation(); }} > <ExtraContent position="left" extra={extra} prefixCls={prefixCls} /> <ResizeObserver onResize={onListHolderResize}> <div className={classNames(wrapPrefix, { [`${wrapPrefix}-ping-left`]: pingLeft, [`${wrapPrefix}-ping-right`]: pingRight, [`${wrapPrefix}-ping-top`]: pingTop, [`${wrapPrefix}-ping-bottom`]: pingBottom, })} ref={tabsWrapperRef} > <ResizeObserver onResize={onListHolderResize}> <div ref={tabListRef} className={`${prefixCls}-nav-list`} style={{ transform: `translate(${transformLeft}px, ${transformTop}px)`, transition: lockAnimation ? 'none' : undefined, }} > {tabNodes} <AddButton ref={innerAddButtonRef} prefixCls={prefixCls} locale={locale} editable={editable} style={{ visibility: hasDropdown ? 'hidden' : null }} /> <div className={classNames(`${prefixCls}-ink-bar`, { [`${prefixCls}-ink-bar-animated`]: animated.inkBar, })} style={inkStyle} /> </div> </ResizeObserver> </div> </ResizeObserver> <OperationNode {...props} ref={operationsRef} prefixCls={prefixCls} tabs={hiddenTabs} className={!hasDropdown && operationsHiddenClassName} /> <ExtraContent position="right" extra={extra} prefixCls={prefixCls} /> </div> ); /* eslint-enable */ } export default React.forwardRef(TabNavList);
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/TabPanelList/TabPane.tsx
TypeScript (TSX)
import * as React from 'react'; import classNames from 'classnames'; export interface TabPaneProps { tab?: React.ReactNode; className?: string; style?: React.CSSProperties; disabled?: boolean; children?: React.ReactNode; forceRender?: boolean; closable?: boolean; closeIcon?: React.ReactNode; // Pass by TabPaneList prefixCls?: string; tabKey?: string; id?: string; animated?: boolean; active?: boolean; destroyInactiveTabPane?: boolean; } export default function TabPane({ prefixCls, forceRender, className, style, id, active, animated, destroyInactiveTabPane, tabKey, children, }: TabPaneProps) { const [visited, setVisited] = React.useState(forceRender); React.useEffect(() => { if (active) { setVisited(true); } else if (destroyInactiveTabPane) { setVisited(false); } }, [active, destroyInactiveTabPane]); const mergedStyle: React.CSSProperties = {}; if (!active) { if (animated) { mergedStyle.visibility = 'hidden'; mergedStyle.height = 0; mergedStyle.overflowY = 'hidden'; } else { mergedStyle.display = 'none'; } } return ( <div id={id && `${id}-panel-${tabKey}`} role="tabpanel" tabIndex={active ? 0 : -1} aria-labelledby={id && `${id}-tab-${tabKey}`} aria-hidden={!active} style={{ ...mergedStyle, ...style }} className={classNames( `${prefixCls}-tabpane`, active && `${prefixCls}-tabpane-active`, className, )} > {(active || visited || forceRender) && children} </div> ); }
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/TabPanelList/index.tsx
TypeScript (TSX)
import * as React from 'react'; import classNames from 'classnames'; import TabContext from '../TabContext'; import { TabPosition, AnimatedConfig } from '../interface'; export interface TabPanelListProps { activeKey: React.Key; id: string; rtl: boolean; animated?: AnimatedConfig; tabPosition?: TabPosition; destroyInactiveTabPane?: boolean; } export default function TabPanelList({ id, activeKey, animated, tabPosition, rtl, destroyInactiveTabPane, }: TabPanelListProps) { const { prefixCls, tabs } = React.useContext(TabContext); const tabPaneAnimated = animated.tabPane; const activeIndex = tabs.findIndex(tab => tab.key === activeKey); return ( <div className={classNames(`${prefixCls}-content-holder`)}> <div className={classNames(`${prefixCls}-content`, `${prefixCls}-content-${tabPosition}`, { [`${prefixCls}-content-animated`]: tabPaneAnimated, })} style={ activeIndex && tabPaneAnimated ? { [rtl ? 'marginRight' : 'marginLeft']: `-${activeIndex}00%` } : null } > {tabs.map(tab => { return React.cloneElement(tab.node, { key: tab.key, prefixCls, tabKey: tab.key, id, animated: tabPaneAnimated, active: tab.key === activeKey, destroyInactiveTabPane, }); })} </div> </div> ); }
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/Tabs.tsx
TypeScript (TSX)
// Accessibility https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/Tab_Role import * as React from 'react'; import { useEffect, useState } from 'react'; import classNames from 'classnames'; import toArray from 'rc-util/lib/Children/toArray'; import useMergedState from 'rc-util/lib/hooks/useMergedState'; import TabNavList from './TabNavList'; import TabPanelList from './TabPanelList'; import TabPane, { TabPaneProps } from './TabPanelList/TabPane'; import { TabPosition, RenderTabBar, TabsLocale, EditableConfig, AnimatedConfig, OnTabScroll, Tab, TabBarExtraContent, } from './interface'; import TabContext from './TabContext'; import { isMobile } from './hooks/useTouchMove'; /** * Should added antd: * - type * * Removed: * - onNextClick * - onPrevClick * - keyboard */ // Used for accessibility let uuid = 0; export interface TabsProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'onChange'> { prefixCls?: string; className?: string; style?: React.CSSProperties; children?: React.ReactNode; id?: string; activeKey?: string; defaultActiveKey?: string; direction?: 'ltr' | 'rtl'; animated?: boolean | AnimatedConfig; renderTabBar?: RenderTabBar; tabBarExtraContent?: TabBarExtraContent; tabBarGutter?: number; tabBarStyle?: React.CSSProperties; tabPosition?: TabPosition; destroyInactiveTabPane?: boolean; onChange?: (activeKey: string) => void; onTabClick?: (activeKey: string, e: React.KeyboardEvent | React.MouseEvent) => void; onTabScroll?: OnTabScroll; editable?: EditableConfig; // Accessibility locale?: TabsLocale; // Icons moreIcon?: React.ReactNode; /** @private Internal usage. Not promise will rename in future */ moreTransitionName?: string; } function parseTabList(children: React.ReactNode): Tab[] { return toArray(children) .map((node: React.ReactElement<TabPaneProps>) => { if (React.isValidElement(node)) { const key = node.key !== undefined ? String(node.key) : undefined; return { key, ...node.props, node, }; } return null; }) .filter(tab => tab); } function Tabs( { id, prefixCls = 'rc-tabs', className, children, direction, activeKey, defaultActiveKey, editable, animated, tabPosition = 'top', tabBarGutter, tabBarStyle, tabBarExtraContent, locale, moreIcon, moreTransitionName, destroyInactiveTabPane, renderTabBar, onChange, onTabClick, onTabScroll, ...restProps }: TabsProps, ref: React.Ref<HTMLDivElement>, ) { const tabs = parseTabList(children); const rtl = direction === 'rtl'; let mergedAnimated: AnimatedConfig | false; if (animated === false) { mergedAnimated = { inkBar: false, tabPane: false, }; } else { mergedAnimated = { inkBar: true, tabPane: false, ...(animated !== true ? animated : null), }; } // ======================== Mobile ======================== const [mobile, setMobile] = useState(false); useEffect(() => { // Only update on the client side setMobile(isMobile()); }, []); // ====================== Active Key ====================== const [mergedActiveKey, setMergedActiveKey] = useMergedState<string>(() => tabs[0]?.key, { value: activeKey, defaultValue: defaultActiveKey, }); const [activeIndex, setActiveIndex] = useState(() => tabs.findIndex(tab => tab.key === mergedActiveKey), ); // Reset active key if not exist anymore useEffect(() => { let newActiveIndex = tabs.findIndex(tab => tab.key === mergedActiveKey); if (newActiveIndex === -1) { newActiveIndex = Math.max(0, Math.min(activeIndex, tabs.length - 1)); setMergedActiveKey(tabs[newActiveIndex]?.key); } setActiveIndex(newActiveIndex); }, [tabs.map(tab => tab.key).join('_'), mergedActiveKey, activeIndex]); // ===================== Accessibility ==================== const [mergedId, setMergedId] = useMergedState(null, { value: id, }); let mergedTabPosition = tabPosition; if (mobile && !['left', 'right'].includes(tabPosition)) { mergedTabPosition = 'top'; } // Async generate id to avoid ssr mapping failed useEffect(() => { if (!id) { setMergedId(`rc-tabs-${process.env.NODE_ENV === 'test' ? 'test' : uuid}`); uuid += 1; } }, []); // ======================== Events ======================== function onInternalTabClick(key: string, e: React.MouseEvent | React.KeyboardEvent) { onTabClick?.(key, e); setMergedActiveKey(key); onChange?.(key); } // ======================== Render ======================== const sharedProps = { id: mergedId, activeKey: mergedActiveKey, animated: mergedAnimated, tabPosition: mergedTabPosition, rtl, mobile, }; let tabNavBar: React.ReactElement; const tabNavBarProps = { ...sharedProps, editable, locale, moreIcon, moreTransitionName, tabBarGutter, onTabClick: onInternalTabClick, onTabScroll, extra: tabBarExtraContent, style: tabBarStyle, panes: children, }; if (renderTabBar) { tabNavBar = renderTabBar(tabNavBarProps, TabNavList); } else { tabNavBar = <TabNavList {...tabNavBarProps} />; } return ( <TabContext.Provider value={{ tabs, prefixCls }}> <div ref={ref} id={id} className={classNames( prefixCls, `${prefixCls}-${mergedTabPosition}`, { [`${prefixCls}-mobile`]: mobile, [`${prefixCls}-editable`]: editable, [`${prefixCls}-rtl`]: rtl, }, className, )} {...restProps} > {tabNavBar} <TabPanelList destroyInactiveTabPane={destroyInactiveTabPane} {...sharedProps} animated={mergedAnimated} /> </div> </TabContext.Provider> ); } const ForwardTabs = React.forwardRef(Tabs); export type ForwardTabsType = typeof ForwardTabs & { TabPane: typeof TabPane }; (ForwardTabs as ForwardTabsType).TabPane = TabPane; export default ForwardTabs as ForwardTabsType;
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/hooks/useOffsets.ts
TypeScript
import { useMemo } from 'react'; import { TabSizeMap, TabOffsetMap, Tab, TabOffset } from '../interface'; const DEFAULT_SIZE = { width: 0, height: 0, left: 0, top: 0 }; export default function useOffsets(tabs: Tab[], tabSizes: TabSizeMap, holderScrollWidth: number) { return useMemo(() => { const map: TabOffsetMap = new Map(); const lastOffset = tabSizes.get(tabs[0]?.key) || DEFAULT_SIZE; const rightOffset = lastOffset.left + lastOffset.width; for (let i = 0; i < tabs.length; i += 1) { const { key } = tabs[i]; let data = tabSizes.get(key); // Reuse last one when not exist yet if (!data) { data = tabSizes.get(tabs[i - 1]?.key) || DEFAULT_SIZE; } const entity = (map.get(key) || { ...data }) as TabOffset; // Right entity.right = rightOffset - entity.left - entity.width; // Update entity map.set(key, entity); } return map; }, [tabs.map(tab => tab.key).join('_'), tabSizes, holderScrollWidth]); }
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/hooks/useRaf.ts
TypeScript
import { useRef, useState, useEffect } from 'react'; import raf from 'raf'; export default function useRaf<Callback extends Function>(callback: Callback) { const rafRef = useRef<number>(); const removedRef = useRef(false); function trigger(...args: any[]) { if (!removedRef.current) { raf.cancel(rafRef.current); rafRef.current = raf(() => { callback(...args); }); } } useEffect(() => { return () => { removedRef.current = true; raf.cancel(rafRef.current); }; }, []); return trigger; } type Callback<T> = (ori: T) => T; export function useRafState<T>(defaultState: T | (() => T)): [T, (updater: Callback<T>) => void] { const batchRef = useRef<Callback<T>[]>([]); const [, forceUpdate] = useState({}); const state = useRef<T>( typeof defaultState === 'function' ? (defaultState as any)() : defaultState, ); const flushUpdate = useRaf(() => { let current = state.current; batchRef.current.forEach(callback => { current = callback(current); }); batchRef.current = []; state.current = current; forceUpdate({}); }); function updater(callback: Callback<T>) { batchRef.current.push(callback); flushUpdate(); } return [state.current, updater]; }
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/hooks/useRefs.ts
TypeScript
import * as React from 'react'; import { useRef } from 'react'; export default function useRefs<RefType>(): [ (key: React.Key) => React.RefObject<RefType>, (key: React.Key) => void, ] { const cacheRefs = useRef(new Map<React.Key, React.RefObject<RefType>>()); function getRef(key: React.Key) { if (!cacheRefs.current.has(key)) { cacheRefs.current.set(key, React.createRef<RefType>()); } return cacheRefs.current.get(key); } function removeRef(key: React.Key) { cacheRefs.current.delete(key); } return [getRef, removeRef]; }
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/hooks/useSyncState.ts
TypeScript
import * as React from 'react'; type Updater<T> = (prev: T) => T; export default function useSyncState<T>( defaultState: T, onChange: (newValue: T, prevValue: T) => void, ): [T, (updater: T | Updater<T>) => void] { const stateRef = React.useRef<T>(defaultState); const [, forceUpdate] = React.useState({}); function setState(updater: any) { const newValue = typeof updater === 'function' ? updater(stateRef.current) : updater; if (newValue !== stateRef.current) { onChange(newValue, stateRef.current); } stateRef.current = newValue; forceUpdate({}); } return [stateRef.current, setState]; }
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/hooks/useTouchMove.ts
TypeScript
import * as React from 'react'; import { useState, useRef } from 'react'; type TouchEventHandler = (e: TouchEvent) => void; type WheelEventHandler = (e: WheelEvent) => void; const MIN_SWIPE_DISTANCE = 0.1; const STOP_SWIPE_DISTANCE = 0.01; const REFRESH_INTERVAL = 20; const SPEED_OFF_MULTIPLE = 0.995 ** REFRESH_INTERVAL; // ========================= Check if is a mobile ========================= export function isMobile() { const agent = navigator.userAgent || navigator.vendor || (window as any).opera; if ( /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test( agent, ) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55\/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|-[a-w])|libw|lynx|m1-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk\/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas-|your|zeto|zte-/i.test( agent.substr(0, 4), ) ) { return true; } return false; } // ================================= Hook ================================= export default function useTouchMove( ref: React.RefObject<HTMLDivElement>, onOffset: (offsetX: number, offsetY: number) => boolean, ) { const [touchPosition, setTouchPosition] = useState<{ x: number; y: number }>(); const [lastTimestamp, setLastTimestamp] = useState<number>(0); const [lastTimeDiff, setLastTimeDiff] = useState<number>(0); const [lastOffset, setLastOffset] = useState<{ x: number; y: number }>(); const motionRef = useRef<number>(); // ========================= Events ========================= // >>> Touch events function onTouchStart(e: TouchEvent) { const { screenX, screenY } = e.touches[0]; setTouchPosition({ x: screenX, y: screenY }); window.clearInterval(motionRef.current); } function onTouchMove(e: TouchEvent) { if (!touchPosition) return; e.preventDefault(); const { screenX, screenY } = e.touches[0]; setTouchPosition({ x: screenX, y: screenY }); const offsetX = screenX - touchPosition.x; const offsetY = screenY - touchPosition.y; onOffset(offsetX, offsetY); const now = Date.now(); setLastTimestamp(now); setLastTimeDiff(now - lastTimestamp); setLastOffset({ x: offsetX, y: offsetY }); } function onTouchEnd() { if (!touchPosition) return; setTouchPosition(null); setLastOffset(null); // Swipe if needed if (lastOffset) { const distanceX = lastOffset.x / lastTimeDiff; const distanceY = lastOffset.y / lastTimeDiff; const absX = Math.abs(distanceX); const absY = Math.abs(distanceY); // Skip swipe if low distance if (Math.max(absX, absY) < MIN_SWIPE_DISTANCE) return; let currentX = distanceX; let currentY = distanceY; motionRef.current = window.setInterval(() => { if (Math.abs(currentX) < STOP_SWIPE_DISTANCE && Math.abs(currentY) < STOP_SWIPE_DISTANCE) { window.clearInterval(motionRef.current); return; } currentX *= SPEED_OFF_MULTIPLE; currentY *= SPEED_OFF_MULTIPLE; onOffset(currentX * REFRESH_INTERVAL, currentY * REFRESH_INTERVAL); }, REFRESH_INTERVAL); } } // >>> Wheel event const lastWheelTimestampRef = useRef(0); const lastWheelPreventRef = useRef(false); const lastWheelDirectionRef = useRef<'x' | 'y'>(); function onWheel(e: WheelEvent) { const { deltaX, deltaY } = e; // Convert both to x & y since wheel only happened on PC let mixed: number = 0; const absX = Math.abs(deltaX); const absY = Math.abs(deltaY); if (absX === absY) { mixed = lastWheelDirectionRef.current === 'x' ? deltaX : deltaY; } else if (absX > absY) { mixed = deltaX; lastWheelDirectionRef.current = 'x'; } else { mixed = deltaY; lastWheelDirectionRef.current = 'y'; } // Optimize mac touch scroll const now = Date.now(); if (now - lastWheelTimestampRef.current > 100) { lastWheelPreventRef.current = false; } if (onOffset(-mixed, -mixed) || lastWheelPreventRef.current) { e.preventDefault(); lastWheelPreventRef.current = true; } lastWheelTimestampRef.current = now; } // ========================= Effect ========================= const touchEventsRef = useRef<{ onTouchStart: TouchEventHandler; onTouchMove: TouchEventHandler; onTouchEnd: TouchEventHandler; onWheel: WheelEventHandler; }>(null); touchEventsRef.current = { onTouchStart, onTouchMove, onTouchEnd, onWheel }; React.useEffect(() => { function onProxyTouchStart(e: TouchEvent) { touchEventsRef.current.onTouchStart(e); } function onProxyTouchMove(e: TouchEvent) { touchEventsRef.current.onTouchMove(e); } function onProxyTouchEnd(e: TouchEvent) { touchEventsRef.current.onTouchEnd(e); } function onProxyWheel(e: WheelEvent) { touchEventsRef.current.onWheel(e); } document.addEventListener('touchmove', onProxyTouchMove, { passive: false }); document.addEventListener('touchend', onProxyTouchEnd, { passive: false }); // No need to clean up since element removed ref.current.addEventListener('touchstart', onProxyTouchStart, { passive: false }); ref.current.addEventListener('wheel', onProxyWheel); return () => { document.removeEventListener('touchmove', onProxyTouchMove); document.removeEventListener('touchend', onProxyTouchEnd); }; }, []); }
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/hooks/useVisibleRange.ts
TypeScript
import { useMemo } from 'react'; import { Tab, TabOffsetMap } from '../interface'; import { TabNavListProps } from '../TabNavList'; const DEFAULT_SIZE = { width: 0, height: 0, left: 0, top: 0, right: 0 }; export default function useVisibleRange( tabOffsets: TabOffsetMap, containerSize: { width: number; height: number; left: number; top: number }, tabContentNodeSize: { width: number; height: number }, addNodeSize: { width: number; height: number }, { tabs, tabPosition, rtl }: { tabs: Tab[] } & TabNavListProps, ): [number, number] { let unit: 'width' | 'height'; let position: 'left' | 'top' | 'right'; let transformSize: number; if (['top', 'bottom'].includes(tabPosition)) { unit = 'width'; position = rtl ? 'right' : 'left'; transformSize = Math.abs(containerSize.left); } else { unit = 'height'; position = 'top'; transformSize = -containerSize.top; } const basicSize = containerSize[unit]; const tabContentSize = tabContentNodeSize[unit]; const addSize = addNodeSize[unit]; let mergedBasicSize = basicSize; if (tabContentSize + addSize > basicSize) { mergedBasicSize = basicSize - addSize; } return useMemo(() => { if (!tabs.length) { return [0, 0]; } const len = tabs.length; let endIndex = len; for (let i = 0; i < len; i += 1) { const offset = tabOffsets.get(tabs[i].key) || DEFAULT_SIZE; if (offset[position] + offset[unit] > transformSize + mergedBasicSize) { endIndex = i - 1; break; } } let startIndex = 0; for (let i = len - 1; i >= 0; i -= 1) { const offset = tabOffsets.get(tabs[i].key) || DEFAULT_SIZE; if (offset[position] < transformSize) { startIndex = i + 1; break; } } return [startIndex, endIndex]; }, [ tabOffsets, transformSize, mergedBasicSize, tabPosition, tabs.map(tab => tab.key).join('_'), rtl, ]); }
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/index.ts
TypeScript
import Tabs, { TabsProps } from './Tabs'; import TabPane, { TabPaneProps } from './TabPanelList/TabPane'; export { TabPane, TabsProps, TabPaneProps }; export default Tabs;
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
src/interface.ts
TypeScript
import { TabPaneProps } from './TabPanelList/TabPane'; export type TabSizeMap = Map< React.Key, { width: number; height: number; left: number; top: number } >; export interface TabOffset { width: number; height: number; left: number; right: number; top: number; } export type TabOffsetMap = Map<React.Key, TabOffset>; export type TabPosition = 'left' | 'right' | 'top' | 'bottom'; export interface Tab extends TabPaneProps { key: string; node: React.ReactElement; } export type RenderTabBar = (props: any, DefaultTabBar: React.ComponentType) => React.ReactElement; export interface TabsLocale { dropdownAriaLabel?: string; removeAriaLabel?: string; addAriaLabel?: string; } export interface EditableConfig { onEdit: ( type: 'add' | 'remove', info: { key?: string; event: React.MouseEvent | React.KeyboardEvent }, ) => void; showAdd?: boolean; removeIcon?: React.ReactNode; addIcon?: React.ReactNode; } export interface AnimatedConfig { inkBar?: boolean; tabPane?: boolean; } export type OnTabScroll = (info: { direction: 'left' | 'right' | 'top' | 'bottom' }) => void; export type TabBarExtraPosition = 'left' | 'right'; export type TabBarExtraMap = Partial<Record<TabBarExtraPosition, React.ReactNode>>; export type TabBarExtraContent = React.ReactNode | TabBarExtraMap;
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
tests/common/util.tsx
TypeScript (TSX)
import React from 'react'; import { ReactWrapper } from 'enzyme'; import Tabs, { TabPane } from '../../src'; import { TabsProps } from '../../src/Tabs'; export function getOffsetSizeFunc( info: { list?: number; wrapper?: number; add?: number; operation?: number; more?: number; dropdown?: number; } = {}, ) { return function getOffsetSize() { if (this.className.includes('rc-tabs-tab')) { return 20; } if (this.className.includes('rc-tabs-nav-list')) { return info.list || 5 * 20; } if (this.className.includes('rc-tabs-nav-wrap')) { return info.wrapper || 40; } if (this.className.includes('rc-tabs-nav-add')) { return info.add || 10; } if (this.className.includes('rc-tabs-nav-operations')) { return info.operation || 10; } if (this.className.includes('rc-tabs-nav-more')) { return info.more || 10; } if (this.className.includes('rc-tabs-dropdown')) { return info.dropdown || 10; } throw new Error(`className not match ${this.className}`); }; } export function getTransformX(wrapper: ReactWrapper) { const { transform } = wrapper.find('.rc-tabs-nav-list').props().style; const match = transform.match(/\(([-\d.]+)px/); if (!match) { // eslint-disable-next-line no-console console.log(wrapper.find('.rc-tabs-nav-list').html()); throw new Error(`Not find transformX: ${transform}`); } return Number(match[1]); } export function getTransformY(wrapper: ReactWrapper) { const { transform } = wrapper.find('.rc-tabs-nav-list').props().style; const match = transform.match(/,\s*([-\d.]+)px/); if (!match) { // eslint-disable-next-line no-console console.log(wrapper.find('.rc-tabs-nav-list').html()); throw new Error(`Not find transformY: ${transform}`); } return Number(match[1]); } export function getTabs(props: TabsProps = null) { return ( <Tabs {...props}> <TabPane tab="light" key="light"> Light </TabPane> <TabPane tab="bamboo" key="bamboo"> Bamboo </TabPane> <TabPane tab="cute" key="cute"> Cute </TabPane> <TabPane tab="disabled" key="disabled" disabled> Disabled </TabPane> <TabPane tab="miu" key="miu"> Miu </TabPane> </Tabs> ); } export function triggerResize(wrapper: ReactWrapper) { (wrapper .find('.rc-tabs-nav') .find('ResizeObserver') .first() .props() as any).onResize(); }
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
tests/index.test.tsx
TypeScript (TSX)
import React from 'react'; import { mount, ReactWrapper } from 'enzyme'; import KeyCode from 'rc-util/lib/KeyCode'; import Tabs, { TabPane } from '../src'; import { TabsProps } from '../src/Tabs'; describe('Tabs.Basic', () => { function getTabs(props: TabsProps = null) { const mergedProps = { children: [ <TabPane tab="light" key="light"> Light </TabPane>, <TabPane tab="bamboo" key="bamboo"> Bamboo </TabPane>, <TabPane tab="cute" key="cute"> Cute </TabPane>, ], ...props, }; return <Tabs {...mergedProps} />; } it('Normal', () => { const wrapper = mount(getTabs({ defaultActiveKey: 'bamboo' })); expect(wrapper.render()).toMatchSnapshot(); }); it('Skip invalidate children', () => { const wrapper = mount( getTabs({ children: [ <TabPane tab="light" key="light"> Light </TabPane>, 'not me', ], }), ); wrapper.update(); expect(wrapper.render()).toMatchSnapshot(); }); it('nothing for empty tabs', () => { mount(getTabs({ children: null })); }); describe('onChange and onTabClick should work', () => { const list: { name: string; trigger: (wrapper: ReactWrapper) => void }[] = [ { name: 'outer div', trigger: wrapper => wrapper .find('.rc-tabs-tab') .at(2) .simulate('click'), }, { name: 'inner button', trigger: wrapper => wrapper .find('.rc-tabs-tab .rc-tabs-tab-btn') .at(2) .simulate('click'), }, { name: 'inner button key down', trigger: wrapper => wrapper .find('.rc-tabs-tab .rc-tabs-tab-btn') .at(2) .simulate('keydown', { which: KeyCode.SPACE, }), }, ]; list.forEach(({ name, trigger }) => { it(name, () => { const onChange = jest.fn(); const onTabClick = jest.fn(); const wrapper = mount(getTabs({ onChange, onTabClick })); trigger(wrapper); expect(onTabClick).toHaveBeenCalledWith('cute', expect.anything()); expect(onChange).toHaveBeenCalledWith('cute'); }); }); }); it('active first tab when children is changed', () => { const wrapper = mount(getTabs()); wrapper.setProps({ children: ( <TabPane tab="Yo" key="2333"> New </TabPane> ), }); wrapper.update(); expect(wrapper.find('.rc-tabs-tab-active').text()).toEqual('Yo'); }); it('active first tab when children is not changed at controlled mode', () => { const wrapper = mount(getTabs({ activeKey: 'light' })); expect(wrapper.find('.rc-tabs-tab-active').text()).toEqual('light'); wrapper.setProps({ children: ( <TabPane tab="Yo" key="2333"> New </TabPane> ), }); expect(wrapper.find('.rc-tabs-tab-active')).toHaveLength(0); }); it('tabBarGutter should work', () => { const topTabs = mount(getTabs({ tabBarGutter: 23 })); expect( topTabs .find('.rc-tabs-tab') .first() .props().style.marginRight, ).toEqual(23); const rightTabs = mount(getTabs({ tabBarGutter: 33, tabPosition: 'right' })); expect( rightTabs .find('.rc-tabs-tab') .first() .props().style.marginBottom, ).toEqual(33); }); describe('renderTabBar', () => { it('works', () => { const renderTabBar = jest.fn((props, Component) => { return ( <div className="my-wrapper"> <Component {...props}>{node => <span className="my-node">{node}</span>}</Component> </div> ); }); const wrapper = mount(getTabs({ renderTabBar })); expect(wrapper.find('.my-wrapper').length).toBeTruthy(); expect(wrapper.find('.my-node').length).toBeTruthy(); expect(renderTabBar).toHaveBeenCalled(); }); it('has panes property in props', () => { const renderTabBar = props => { return ( <div> {props.panes.map(pane => ( <span key={pane.key} data-key={pane.key}> tab </span> ))} </div> ); }; const wrapper = mount(getTabs({ renderTabBar })); expect(wrapper.find('[data-key="light"]').length).toBeTruthy(); expect(wrapper.find('[data-key="bamboo"]').length).toBeTruthy(); expect(wrapper.find('[data-key="cute"]').length).toBeTruthy(); }); }); it('destroyInactiveTabPane', () => { const wrapper = mount( getTabs({ activeKey: 'light', destroyInactiveTabPane: true, children: [<TabPane key="light">Light</TabPane>, <TabPane key="bamboo">Bamboo</TabPane>], }), ); function matchText(light: string, bamboo: string) { expect( wrapper .find('.rc-tabs-tabpane') .first() .text(), ).toEqual(light); expect( wrapper .find('.rc-tabs-tabpane') .last() .text(), ).toEqual(bamboo); } matchText('Light', ''); wrapper.setProps({ activeKey: 'bamboo' }); matchText('', 'Bamboo'); }); describe('editable', () => { it('no and', () => { const onEdit = jest.fn(); const wrapper = mount(getTabs({ editable: { onEdit, showAdd: false } })); expect(wrapper.find('.rc-tabs-nav-add')).toHaveLength(0); }); it('add', () => { const onEdit = jest.fn(); const wrapper = mount(getTabs({ editable: { onEdit } })); wrapper .find('.rc-tabs-nav-add') .first() .simulate('click'); expect(onEdit).toHaveBeenCalledWith('add', { key: undefined, event: expect.anything(), }); }); const list: { name: string; trigger: (node: ReactWrapper) => void }[] = [ { name: 'click', trigger: node => { node.simulate('click'); }, }, ]; list.forEach(({ name, trigger }) => { it(`remove by ${name}`, () => { const onEdit = jest.fn(); const wrapper = mount(getTabs({ editable: { onEdit } })); const first = wrapper.find('.rc-tabs-tab-remove').first(); trigger(first); // Should be button to enable press SPACE key to trigger expect(first.instance() instanceof HTMLButtonElement).toBeTruthy(); expect(onEdit).toHaveBeenCalledWith('remove', { key: 'light', event: expect.anything(), }); }); }); it('customize closeIcon', () => { const onEdit = jest.fn(); const wrapper = mount( getTabs({ editable: { onEdit }, children: [ <TabPane tab="light" closeIcon={<span className="close-light" />}> Light </TabPane>, ], }), ); expect(wrapper.find('.rc-tabs-tab-remove').find('.close-light').length).toBeTruthy(); }); }); it('extra', () => { const wrapper = mount(getTabs({ tabBarExtraContent: 'Bamboo' })); expect(wrapper.find('.rc-tabs-extra-content').text()).toEqual('Bamboo'); }); it('extra positon', () => { const wrapper = mount( getTabs({ tabBarExtraContent: { left: 'Left Bamboo', right: 'Right Bamboo' } }), ); expect( wrapper .find('.rc-tabs-extra-content') .first() .text(), ).toEqual('Left Bamboo'); expect( wrapper .find('.rc-tabs-extra-content') .at(1) .text(), ).toEqual('Right Bamboo'); }); describe('animated', () => { it('false', () => { const wrapper = mount(getTabs({ animated: false })); expect(wrapper.find('TabPanelList').prop('animated')).toEqual({ inkBar: false, tabPane: false, }); }); it('true', () => { const wrapper = mount(getTabs({ animated: true })); expect(wrapper.find('TabPanelList').prop('animated')).toEqual({ inkBar: true, tabPane: false, }); }); it('customize', () => { const wrapper = mount(getTabs({ animated: { inkBar: false, tabPane: true } })); expect(wrapper.find('TabPanelList').prop('animated')).toEqual({ inkBar: false, tabPane: true, }); }); }); it('focus to scroll', () => { const wrapper = mount(getTabs()); wrapper .find('.rc-tabs-tab') .first() .simulate('focus'); wrapper.unmount(); }); it('tabBarStyle', () => { const wrapper = mount(getTabs({ tabBarStyle: { background: 'red' } })); expect(wrapper.find('.rc-tabs-nav').prop('style').background).toEqual('red'); }); });
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
tests/mobile.test.tsx
TypeScript (TSX)
import React from 'react'; import { mount, ReactWrapper } from 'enzyme'; import { spyElementPrototypes } from 'rc-util/lib/test/domHook'; import { act } from 'react-dom/test-utils'; import Tabs, { TabPane } from '../src'; import { TabsProps } from '../src/Tabs'; import { getTransformX } from './common/util'; describe('Tabs.Mobile', () => { const originAgent = navigator.userAgent; beforeAll(() => { Object.defineProperty(window.navigator, 'userAgent', { value: 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Mobile Safari/537.36', }); }); afterAll(() => { Object.defineProperty(window.navigator, 'userAgent', { value: originAgent, }); }); const tabCount = 100; function getTabs(props: TabsProps = null) { const children: React.ReactElement[] = []; for (let i = 0; i < tabCount; i += 1) { children.push( <TabPane tab={i} key={i}> {i} </TabPane>, ); } return <Tabs {...props}>{children}</Tabs>; } describe('mobile is scrollable', () => { let domSpy: ReturnType<typeof spyElementPrototypes>; let btnSpy: ReturnType<typeof spyElementPrototypes>; let dateSpy: ReturnType<typeof jest.spyOn>; let timestamp: number = 0; let rtl = false; beforeAll(() => { dateSpy = jest.spyOn(Date, 'now').mockImplementation(() => timestamp); btnSpy = spyElementPrototypes(HTMLButtonElement, { offsetWidth: { get: () => 20, }, offsetLeft: { get() { // Mock button offset const btn = this as HTMLButtonElement; const btnList = [...btn.parentNode.childNodes].filter(ele => (ele as HTMLElement).className.includes('rc-tabs-tab'), ); const index = btnList.indexOf(btn); if (rtl) { return 20 * (btnList.length - index - 1); } return 20 * index; }, }, }); domSpy = spyElementPrototypes(HTMLDivElement, { offsetWidth: { get() { if (this.className.includes('rc-tabs-tab')) { return 20; } if (this.className.includes('rc-tabs-nav-list')) { return tabCount * 20; } if (this.className.includes('rc-tabs-nav-wrap')) { return 40; } if (this.className.includes('rc-tabs-nav-operations')) { return 5; } throw new Error(`className not match ${this.className}`); }, }, }); }); afterAll(() => { btnSpy.mockRestore(); domSpy.mockRestore(); dateSpy.mockRestore(); }); function touchMove(wrapper: ReactWrapper, jest: any, offsetX: number[] | number) { act(() => { jest.runAllTimers(); wrapper.update(); }); // Touch to move const node = (wrapper.find('.rc-tabs-nav-wrap').instance() as unknown) as HTMLElement; act(() => { const touchStart = new TouchEvent('touchstart', { touches: [{ screenX: 0, screenY: 0 } as any], }); node.dispatchEvent(touchStart); }); let screenX: number = 0; let screenY: number = 0; const offsetXs = Array.isArray(offsetX) ? offsetX : [offsetX]; function trigger(x = 0, y = 0) { screenX += x; screenY += y; act(() => { const moveEvent1 = new TouchEvent('touchmove', { touches: [{ screenX, screenY } as any], }); document.dispatchEvent(moveEvent1); }); timestamp += 10; } // Init timestamp = 0; // First move trigger(); offsetXs.forEach(x => { trigger(x); }); // Release act(() => { const endEvent = new TouchEvent('touchend', {}); document.dispatchEvent(endEvent); }); // Execution swipe act(() => { jest.runAllTimers(); wrapper.update(); }); } describe('LTR', () => { beforeAll(() => { rtl = false; }); it('slow move', () => { jest.useFakeTimers(); const wrapper = mount(getTabs({ tabPosition: 'top' })); // Last touch is slow move touchMove(wrapper, jest, [-100, 0.05]); expect(getTransformX(wrapper)).toEqual(-99.95); jest.useRealTimers(); }); it('swipe', () => { jest.useFakeTimers(); const wrapper = mount(getTabs({ tabPosition: 'top' })); act(() => { jest.runAllTimers(); wrapper.update(); }); expect(wrapper.find('.rc-tabs-nav-more')).toHaveLength(0); touchMove(wrapper, jest, -200); wrapper.update(); expect(getTransformX(wrapper) < -200).toBeTruthy(); jest.useRealTimers(); }); it('not out of the edge', () => { jest.useFakeTimers(); const wrapper = mount(getTabs({ tabPosition: 'top' })); touchMove(wrapper, jest, 100); wrapper.update(); expect(getTransformX(wrapper)).toEqual(0); jest.useRealTimers(); }); }); describe('RTL', () => { beforeAll(() => { rtl = true; }); it('not out of the edge', () => { jest.useFakeTimers(); const wrapper = mount(getTabs({ direction: 'rtl' })); touchMove(wrapper, jest, -100); wrapper.update(); expect(getTransformX(wrapper)).toEqual(0); jest.useRealTimers(); }); }); }); });
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
tests/operation-overflow.test.tsx
TypeScript (TSX)
import { mount } from 'enzyme'; import { spyElementPrototypes } from 'rc-util/lib/test/domHook'; import { act } from 'react-dom/test-utils'; import { getOffsetSizeFunc, getTabs, triggerResize } from './common/util'; describe('Tabs.Operation-Overflow', () => { let domSpy: ReturnType<typeof spyElementPrototypes>; let holder: HTMLDivElement; const hackOffsetInfo = { wrapper: 105, list: 110, add: 10, operation: 20 }; beforeAll(() => { holder = document.createElement('div'); document.body.appendChild(holder); function btnOffsetPosition() { const btn = this as HTMLButtonElement; const btnList = [...btn.parentNode.childNodes].filter(ele => (ele as HTMLElement).className.includes('rc-tabs-tab'), ); const index = btnList.indexOf(btn); return 20 * index; } domSpy = spyElementPrototypes(HTMLElement, { scrollIntoView: () => {}, offsetWidth: { get: getOffsetSizeFunc(hackOffsetInfo), }, offsetHeight: { get: getOffsetSizeFunc(hackOffsetInfo), }, offsetLeft: { get: btnOffsetPosition, }, offsetTop: { get: btnOffsetPosition, }, }); }); afterAll(() => { domSpy.mockRestore(); document.body.removeChild(holder); }); it('should collapse', () => { jest.useFakeTimers(); const onEdit = jest.fn(); const wrapper = mount(getTabs({ editable: { onEdit } })); triggerResize(wrapper); act(() => { jest.runAllTimers(); wrapper.update(); }); expect( wrapper.find('.rc-tabs-nav-operations').hasClass('rc-tabs-nav-operations-hidden'), ).toBeFalsy(); wrapper.unmount(); jest.useRealTimers(); }); });
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
tests/overflow.test.tsx
TypeScript (TSX)
import React from 'react'; import { mount } from 'enzyme'; import KeyCode from 'rc-util/lib/KeyCode'; import { spyElementPrototypes } from 'rc-util/lib/test/domHook'; import { act } from 'react-dom/test-utils'; import { getOffsetSizeFunc, getTabs, triggerResize, getTransformX, getTransformY, } from './common/util'; import { TabPane } from '../src'; describe('Tabs.Overflow', () => { let domSpy: ReturnType<typeof spyElementPrototypes>; let holder: HTMLDivElement; const hackOffsetInfo: { list?: number } = {}; beforeAll(() => { holder = document.createElement('div'); document.body.appendChild(holder); function btnOffsetPosition() { const btn = this as HTMLButtonElement; const btnList = [...btn.parentNode.childNodes].filter(ele => (ele as HTMLElement).className.includes('rc-tabs-tab'), ); const index = btnList.indexOf(btn); return 20 * index; } domSpy = spyElementPrototypes(HTMLElement, { scrollIntoView: () => {}, offsetWidth: { get: getOffsetSizeFunc(hackOffsetInfo), }, offsetHeight: { get: getOffsetSizeFunc(hackOffsetInfo), }, offsetLeft: { get: btnOffsetPosition, }, offsetTop: { get: btnOffsetPosition, }, }); }); afterAll(() => { domSpy.mockRestore(); document.body.removeChild(holder); }); it('should collapse', () => { jest.useFakeTimers(); const onChange = jest.fn(); const wrapper = mount(getTabs({ onChange })); triggerResize(wrapper); act(() => { jest.runAllTimers(); wrapper.update(); }); expect(wrapper.find('.rc-tabs-nav-more').render()).toMatchSnapshot(); // Click to open wrapper.find('.rc-tabs-nav-more').simulate('mouseenter'); jest.runAllTimers(); wrapper.update(); expect( wrapper .find('.rc-tabs-dropdown li') .first() .text(), ).toEqual('cute'); // Click to select wrapper .find('.rc-tabs-dropdown-menu-item') .first() .simulate('click'); expect(onChange).toHaveBeenCalledWith('cute'); wrapper.unmount(); jest.useRealTimers(); }); [KeyCode.SPACE, KeyCode.ENTER].forEach(code => { it(`keyboard with select keycode: ${code}`, () => { jest.useFakeTimers(); const onChange = jest.fn(); const wrapper = mount(getTabs({ onChange }), { attachTo: holder }); triggerResize(wrapper); act(() => { jest.runAllTimers(); wrapper.update(); }); // Open wrapper.find('.rc-tabs-nav-more').simulate('keydown', { which: KeyCode.DOWN, }); // key selection function keyMatch(which: number, match: string) { wrapper.find('.rc-tabs-nav-more').simulate('keydown', { which, }); expect(wrapper.find('.rc-tabs-dropdown-menu-item-selected').text()).toEqual(match); } keyMatch(KeyCode.DOWN, 'cute'); keyMatch(KeyCode.DOWN, 'miu'); keyMatch(KeyCode.UP, 'cute'); // Select wrapper.find('.rc-tabs-nav-more').simulate('keydown', { which: code, }); expect(onChange).toHaveBeenCalledWith('cute'); // Open wrapper.find('.rc-tabs-nav-more').simulate('keydown', { which: KeyCode.DOWN, }); wrapper.update(); expect( wrapper .find('.rc-tabs-dropdown') .last() .hasClass('rc-tabs-dropdown-hidden'), ).toBeFalsy(); // ESC wrapper.find('.rc-tabs-nav-more').simulate('keydown', { which: KeyCode.ESC, }); wrapper.update(); expect( wrapper .find('.rc-tabs-dropdown') .last() .hasClass('rc-tabs-dropdown-hidden'), ).toBeTruthy(); wrapper.unmount(); jest.useRealTimers(); }); }); describe('wheel', () => { const list: { name: string; x1: number; y1: number; x2: number; y2: number }[] = [ { name: 'deltaX', x1: 20, y1: 5, x2: 3, y2: -3, }, { name: 'deltaY', y1: 20, x1: 5, y2: 3, x2: -3, }, ]; ['top', 'left'].forEach((tabPosition: any) => { list.forEach(({ name, x1, y1, x2, y2 }) => { it(`should ${tabPosition} work for ${name}`, () => { jest.useFakeTimers(); const wrapper = mount(getTabs({ tabPosition }), { attachTo: holder }); triggerResize(wrapper); act(() => { jest.runAllTimers(); wrapper.update(); }); // Wheel to move const node = (wrapper.find('.rc-tabs-nav-wrap').instance() as unknown) as HTMLElement; act(() => { const touchStart = new WheelEvent('wheel', { deltaX: x1, deltaY: y1, }); node.dispatchEvent(touchStart); jest.runAllTimers(); }); act(() => { const touchStart = new WheelEvent('wheel', { deltaX: x2, deltaY: y2, }); node.dispatchEvent(touchStart); jest.runAllTimers(); }); wrapper.update(); if (tabPosition === 'top') { expect(getTransformX(wrapper)).toEqual(-23); } else { expect(getTransformY(wrapper)).toEqual(-23); } wrapper.unmount(); jest.useRealTimers(); }); }); }); ['top', 'left'].forEach((tabPosition: any) => { it(`no need if place is enough: ${tabPosition}`, () => { hackOffsetInfo.list = 20; jest.useFakeTimers(); const wrapper = mount(getTabs({ children: [<TabPane key="yo">Yo</TabPane>], tabPosition })); triggerResize(wrapper); act(() => { jest.runAllTimers(); wrapper.update(); }); // Wheel to move const node = (wrapper.find('.rc-tabs-nav-wrap').instance() as unknown) as HTMLElement; const touchStart = new WheelEvent('wheel', { deltaX: 20, deltaY: 20, }); touchStart.preventDefault = jest.fn(); act(() => { node.dispatchEvent(touchStart); jest.runAllTimers(); }); expect(touchStart.preventDefault).not.toHaveBeenCalled(); expect(getTransformX(wrapper)).toEqual(0); jest.useRealTimers(); hackOffsetInfo.list = undefined; }); }); }); describe('overflow to scroll', () => { it('top', () => { jest.useFakeTimers(); const onTabScroll = jest.fn(); // light bamboo [cute disabled] miu const wrapper = mount(getTabs({ activeKey: 'disabled', onTabScroll })); triggerResize(wrapper); act(() => { jest.runAllTimers(); wrapper.update(); }); expect(getTransformX(wrapper)).toEqual(-40); // light [bamboo cute] disabled miu onTabScroll.mockReset(); wrapper.setProps({ activeKey: 'bamboo' }); act(() => { jest.runAllTimers(); wrapper.update(); }); expect(getTransformX(wrapper)).toEqual(-20); expect(onTabScroll).toHaveBeenCalledWith({ direction: 'left' }); jest.useRealTimers(); }); it('left', () => { jest.useFakeTimers(); const onTabScroll = jest.fn(); /** * light light * bamboo -------- * -------- bamboo * cute cute * disabled -------- * -------- disabled * miu miu */ const wrapper = mount(getTabs({ activeKey: 'disabled', tabPosition: 'left', onTabScroll })); triggerResize(wrapper); act(() => { jest.runAllTimers(); wrapper.update(); }); expect(getTransformY(wrapper)).toEqual(-40); // light [bamboo cute] disabled miu onTabScroll.mockReset(); wrapper.setProps({ activeKey: 'bamboo' }); act(() => { jest.runAllTimers(); wrapper.update(); }); expect(getTransformY(wrapper)).toEqual(-20); expect(onTabScroll).toHaveBeenCalledWith({ direction: 'top' }); jest.useRealTimers(); }); }); });
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
tests/rtl.test.tsx
TypeScript (TSX)
import { mount } from 'enzyme'; import { spyElementPrototypes } from 'rc-util/lib/test/domHook'; import { act } from 'react-dom/test-utils'; import { getOffsetSizeFunc, getTabs, triggerResize, getTransformX } from './common/util'; // Same as `overflow.test.tsx` but use in RTL describe('Tabs.RTL', () => { let domSpy: ReturnType<typeof spyElementPrototypes>; let holder: HTMLDivElement; beforeAll(() => { holder = document.createElement('div'); document.body.appendChild(holder); domSpy = spyElementPrototypes(HTMLElement, { scrollIntoView: () => {}, offsetWidth: { get: getOffsetSizeFunc(), }, offsetHeight: { get: getOffsetSizeFunc(), }, scrollWidth: { get: () => 5 * 20, }, offsetLeft: { get() { // Mock button offset const btn = this as HTMLButtonElement; const btnList = [...btn.parentNode.childNodes].filter(ele => (ele as HTMLElement).className.includes('rc-tabs-tab'), ); const index = btnList.indexOf(btn); return 20 * (btnList.length - index - 1); }, }, }); }); afterAll(() => { domSpy.mockRestore(); document.body.removeChild(holder); }); it('overflow to scroll', () => { // Miu [Disabled Cute] Bamboo Light jest.useFakeTimers(); const wrapper = mount(getTabs({ direction: 'rtl', defaultActiveKey: 'disabled' })); triggerResize(wrapper); act(() => { jest.runAllTimers(); wrapper.update(); }); expect(getTransformX(wrapper)).toEqual(40); // Miu Disabled [Cute Bamboo] Light wrapper.setProps({ activeKey: 'bamboo' }); act(() => { jest.runAllTimers(); wrapper.update(); }); expect(getTransformX(wrapper)).toEqual(20); jest.useRealTimers(); }); });
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
tests/setup.js
JavaScript
global.requestAnimationFrame = function requestAnimationFrame(cb) { return setTimeout(cb, 0); }; const Enzyme = require('enzyme'); const Adapter = require('enzyme-adapter-react-16'); Enzyme.configure({ adapter: new Adapter() });
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
tests/swipe.js
JavaScript
/* eslint-disable no-undef */ import React, { Component } from 'react'; import { mount, render } from 'enzyme'; import { renderToJson } from 'enzyme-to-json'; import Tabs, { TabPane } from '../src'; import SwipeableTabContent from '../src/SwipeableTabContent'; import SwipeableInkTabBar from '../src/SwipeableInkTabBar'; const contentStyle = { display: 'flex', alignItems: 'center', justifyContent: 'center', height: '5rem', backgroundColor: '#fff', }; const makeTabPane = key => ( <TabPane tab={`选项${key}`} key={key}> <div style={contentStyle}>{`选项${key}内容`}</div> </TabPane> ); const makeMultiTabPane = count => { const result = []; for (let i = 0; i < count; i++) { result.push(makeTabPane(i)); } return result; }; class NormalTabs extends Component { render() { return ( <div style={{ width: '750px', height: '1334px' }}> <Tabs ref={root => { this.root = root; }} defaultActiveKey="8" renderTabBar={() => ( <SwipeableInkTabBar ref={tabBar => { this.tabBar = tabBar; }} /> )} renderTabContent={() => <SwipeableTabContent />} > {makeMultiTabPane(11)} </Tabs> </div> ); } } describe('rc-swipeable-tabs', () => { it('should render Slider with correct DOM structure', () => { const wrapper = render(<NormalTabs />); expect(renderToJson(wrapper)).toMatchSnapshot(); }); it('create and nav should works', () => { const wrapper = render(<NormalTabs />); expect(wrapper.find('.rc-tabs').length).toBe(1); expect(wrapper.find('.rc-tabs-tab').length).toBe(11); }); it('default active should works', () => { const wrapper = mount(<NormalTabs />); expect(wrapper.find('.rc-tabs-tab').length).toBe(11); expect(wrapper.instance().root.state.activeKey).toBe('8'); expect( wrapper .find('.rc-tabs-tab') .at(8) .hasClass('rc-tabs-tab-active'), ).toBe(true); }); it('onChange and onTabClick should works', () => { const handleChange = jest.fn(); const handleTabClick = jest.fn(); const wrapper = mount( <Tabs defaultActiveKey="8" renderTabBar={() => <SwipeableInkTabBar onTabClick={handleTabClick} />} renderTabContent={() => <SwipeableTabContent />} onChange={handleChange} > {makeMultiTabPane(11)} </Tabs>, ); const targetTab = wrapper.find('.rc-tabs-tab').at(6); targetTab.simulate('click'); expect(handleTabClick).toHaveBeenCalledWith('6', expect.anything()); expect(handleChange).toHaveBeenCalledWith('6'); }); });
zombieJ/test-style
0
Test for `css in js` solution.
TypeScript
zombieJ
二货爱吃白萝卜
alipay
android/build.gradle
Gradle
buildscript { ext.safeExtGet = {prop, fallback -> rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback } repositories { google() gradlePluginPortal() } dependencies { classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${safeExtGet("kotlinVersion", "2.1.20")}") classpath("com.android.tools.build:gradle:8.13.0") } } def isNewArchitectureEnabled() { return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true" } apply plugin: "com.android.library" apply plugin: "kotlin-android" if (isNewArchitectureEnabled()) { apply plugin: "com.facebook.react" } android { namespace "com.zoontek.rnnavigationbar" buildToolsVersion safeExtGet("buildToolsVersion", "35.0.0") compileSdkVersion safeExtGet("compileSdkVersion", 35) buildFeatures { buildConfig true } defaultConfig { buildConfigField("boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()) minSdkVersion safeExtGet("minSdkVersion", 24) targetSdkVersion safeExtGet("targetSdkVersion", 35) } lintOptions { abortOnError false } sourceSets { main { if (isNewArchitectureEnabled()) { java.srcDirs += ["src/newarch"] } else { java.srcDirs += ["src/oldarch"] } } } } repositories { maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url("$rootDir/../node_modules/react-native/android") } mavenCentral() google() } dependencies { //noinspection GradleDynamicVersion implementation "com.facebook.react:react-native:+" // From node_modules }
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
android/src/main/java/com/zoontek/rnnavigationbar/NavigationBarModuleImpl.kt
Kotlin
package com.zoontek.rnnavigationbar import android.app.Activity import android.graphics.Color import android.os.Build.VERSION import android.os.Build.VERSION_CODES import android.util.TypedValue import androidx.core.view.WindowInsetsCompat import androidx.core.view.WindowInsetsControllerCompat import com.facebook.common.logging.FLog import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.common.ReactConstants // The light scrim color used in the platform API 29+ // https://cs.android.com/android/platform/superproject/+/master:frameworks/base/core/java/com/android/internal/policy/DecorView.java;drc=6ef0f022c333385dba2c294e35b8de544455bf19;l=142 internal val LightNavigationBarColor = Color.argb(0xe6, 0xFF, 0xFF, 0xFF) // The dark scrim color used in the platform. // https://cs.android.com/android/platform/superproject/+/master:frameworks/base/core/res/res/color/system_bar_background_semi_transparent.xml // https://cs.android.com/android/platform/superproject/+/master:frameworks/base/core/res/remote_color_resources_res/values/colors.xml;l=67 internal val DarkNavigationBarColor = Color.argb(0x80, 0x1b, 0x1b, 0x1b) object NavigationBarModuleImpl { const val NAME = "RNNavigationBar" private const val NO_ACTIVITY_ERROR = "$NAME: Ignored navigation bar change, current activity is null." private val boolAttributes = mutableMapOf<Int, Boolean>() private fun resolveBoolAttribute(activity: Activity, resId: Int): Boolean = boolAttributes.getOrPut(resId) { val value = TypedValue() activity.theme.resolveAttribute(resId, value, true) && value.data != 0 } private fun isNavigationBarTransparent(activity: Activity): Boolean = !resolveBoolAttribute(activity, R.attr.enforceNavigationBarContrast) @Suppress("DEPRECATION") fun setStyle(reactContext: ReactApplicationContext?, style: String) { val activity = reactContext?.currentActivity ?: return FLog.w(ReactConstants.TAG, NO_ACTIVITY_ERROR) if (VERSION.SDK_INT >= VERSION_CODES.O) { activity.runOnUiThread { val light = style == "dark-content" // dark-content = light background val transparent = isNavigationBarTransparent(activity) val window = activity.window if (VERSION.SDK_INT >= VERSION_CODES.Q) { window.isNavigationBarContrastEnforced = !transparent } window.navigationBarColor = when { transparent -> Color.TRANSPARENT light -> LightNavigationBarColor else -> DarkNavigationBarColor } WindowInsetsControllerCompat(window, window.decorView).run { isAppearanceLightNavigationBars = light } } } } // copy StatusBar behavior (default is light-content) // https://github.com/facebook/react-native/blob/v0.81.1/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/statusbar/StatusBarModule.kt#L131 fun initialize(reactContext: ReactApplicationContext?) { setStyle(reactContext, "light-content") } fun setHidden(reactContext: ReactApplicationContext?, hidden: Boolean) { val activity = reactContext?.currentActivity ?: return FLog.w(ReactConstants.TAG, NO_ACTIVITY_ERROR) activity.runOnUiThread { val window = activity.window WindowInsetsControllerCompat(window, window.decorView).run { systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE when (hidden) { true -> hide(WindowInsetsCompat.Type.navigationBars()) else -> show(WindowInsetsCompat.Type.navigationBars()) } } } } }
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
android/src/main/java/com/zoontek/rnnavigationbar/NavigationBarPackage.kt
Kotlin
package com.zoontek.rnnavigationbar import com.facebook.react.BaseReactPackage import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.module.model.ReactModuleInfo import com.facebook.react.module.model.ReactModuleInfoProvider class NavigationBarPackage : BaseReactPackage() { override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? { return when (name) { NavigationBarModuleImpl.NAME -> NavigationBarModule(reactContext) else -> null } } override fun getReactModuleInfoProvider(): ReactModuleInfoProvider { return ReactModuleInfoProvider { val isTurboModule = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED val moduleInfo = ReactModuleInfo( NavigationBarModuleImpl.NAME, NavigationBarModuleImpl.NAME, false, true, false, isTurboModule ) mapOf( NavigationBarModuleImpl.NAME to moduleInfo ) } } }
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
android/src/newarch/com/zoontek/rnnavigationbar/NavigationBarModule.kt
Kotlin
package com.zoontek.rnnavigationbar import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.module.annotations.ReactModule @ReactModule(name = NavigationBarModuleImpl.NAME) class NavigationBarModule(reactContext: ReactApplicationContext) : NativeNavigationBarModuleSpec(reactContext) { init { NavigationBarModuleImpl.initialize(reactApplicationContext) } override fun getName(): String { return NavigationBarModuleImpl.NAME } override fun setStyle(style: String) { NavigationBarModuleImpl.setStyle(reactApplicationContext, style) } override fun setHidden(hidden: Boolean) { NavigationBarModuleImpl.setHidden(reactApplicationContext, hidden) } }
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
android/src/oldarch/com/zoontek/rnnavigationbar/NavigationBarModule.kt
Kotlin
package com.zoontek.rnnavigationbar import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule import com.facebook.react.bridge.ReactMethod import com.facebook.react.module.annotations.ReactModule @ReactModule(name = NavigationBarModuleImpl.NAME) class NavigationBarModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) { init { NavigationBarModuleImpl.initialize(reactApplicationContext) } override fun getName(): String { return NavigationBarModuleImpl.NAME } @ReactMethod fun setStyle(style: String) { NavigationBarModuleImpl.setStyle(reactApplicationContext, style) } @ReactMethod fun setHidden(hidden: Boolean) { NavigationBarModuleImpl.setHidden(reactApplicationContext, hidden) } }
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
app.plugin.js
JavaScript
module.exports = require("./dist/commonjs/expo");
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
example/android/app/build.gradle
Gradle
apply plugin: "com.android.application" apply plugin: "org.jetbrains.kotlin.android" apply plugin: "com.facebook.react" /** * This is the configuration block to customize your React Native Android app. * By default you don't need to apply any configuration, just uncomment the lines you need. */ react { /* Folders */ // The root of your project, i.e. where "package.json" lives. Default is '../..' // root = file("../../") // The folder where the react-native NPM package is. Default is ../../node_modules/react-native // reactNativeDir = file("../../node_modules/react-native") // The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen // codegenDir = file("../../node_modules/@react-native/codegen") // The cli.js file which is the React Native CLI entrypoint. Default is ../../node_modules/react-native/cli.js // cliFile = file("../../node_modules/react-native/cli.js") /* Variants */ // The list of variants to that are debuggable. For those we're going to // skip the bundling of the JS bundle and the assets. By default is just 'debug'. // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants. // debuggableVariants = ["liteDebug", "prodDebug"] /* Bundling */ // A list containing the node command and its flags. Default is just 'node'. // nodeExecutableAndArgs = ["node"] // // The command to run when bundling. By default is 'bundle' // bundleCommand = "ram-bundle" // // The path to the CLI configuration file. Default is empty. // bundleConfig = file(../rn-cli.config.js) // // The name of the generated asset file containing your JS bundle // bundleAssetName = "MyApplication.android.bundle" // // The entry file for bundle generation. Default is 'index.android.js' or 'index.js' // entryFile = file("../js/MyApplication.android.js") // // A list of extra flags to pass to the 'bundle' commands. // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle // extraPackagerArgs = [] /* Hermes Commands */ // The hermes compiler command to run. By default it is 'hermesc' // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc" // // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map" // hermesFlags = ["-O", "-output-source-map"] /* Autolinking */ autolinkLibrariesWithApp() } /** * Set this to true to Run Proguard on Release builds to minify the Java bytecode. */ def enableProguardInReleaseBuilds = false /** * The preferred build flavor of JavaScriptCore (JSC) * * For example, to use the international variant, you can use: * `def jscFlavor = io.github.react-native-community:jsc-android-intl:2026004.+` * * The international variant includes ICU i18n library and necessary data * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that * give correct results when using with locales other than en-US. Note that * this variant is about 6MiB larger per architecture than default. */ def jscFlavor = 'io.github.react-native-community:jsc-android:2026004.+' android { ndkVersion rootProject.ext.ndkVersion buildToolsVersion rootProject.ext.buildToolsVersion compileSdk rootProject.ext.compileSdkVersion namespace "com.rnnavigationbarexample" defaultConfig { applicationId "com.rnnavigationbarexample" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" } signingConfigs { debug { storeFile file('debug.keystore') storePassword 'android' keyAlias 'androiddebugkey' keyPassword 'android' } } buildTypes { debug { signingConfig signingConfigs.debug } release { // Caution! In production, you need to generate your own keystore file. // see https://reactnative.dev/docs/signed-apk-android. signingConfig signingConfigs.debug minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" } } } dependencies { // The version of react-native is set by the React Native Gradle Plugin implementation("com.facebook.react:react-android") if (hermesEnabled.toBoolean()) { implementation("com.facebook.react:hermes-android") } else { implementation jscFlavor } }
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
example/android/app/src/main/java/com/rnnavigationbarexample/MainActivity.kt
Kotlin
package com.rnnavigationbarexample import com.facebook.react.ReactActivity import com.facebook.react.ReactActivityDelegate import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled import com.facebook.react.defaults.DefaultReactActivityDelegate class MainActivity : ReactActivity() { /** * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ override fun getMainComponentName(): String = "RNNavigationBarExample" /** * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate] * which allows you to enable New Architecture with a single boolean flags [fabricEnabled] */ override fun createReactActivityDelegate(): ReactActivityDelegate = DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled) }
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
example/android/app/src/main/java/com/rnnavigationbarexample/MainApplication.kt
Kotlin
package com.rnnavigationbarexample import android.app.Application import com.facebook.react.PackageList import com.facebook.react.ReactApplication import com.facebook.react.ReactHost import com.facebook.react.ReactNativeApplicationEntryPoint.loadReactNative import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost class MainApplication : Application(), ReactApplication { override val reactHost: ReactHost by lazy { getDefaultReactHost( context = applicationContext, packageList = PackageList(this).packages.apply { // Packages that cannot be autolinked yet can be added manually here, for example: // add(MyReactNativePackage()) }, ) } override fun onCreate() { super.onCreate() loadReactNative(this) } }
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
example/android/build.gradle
Gradle
buildscript { ext { buildToolsVersion = "36.0.0" minSdkVersion = 24 compileSdkVersion = 36 targetSdkVersion = 36 ndkVersion = "27.1.12297006" kotlinVersion = "2.1.20" } repositories { google() mavenCentral() } dependencies { classpath("com.android.tools.build:gradle") classpath("com.facebook.react:react-native-gradle-plugin") classpath("org.jetbrains.kotlin:kotlin-gradle-plugin") } } apply plugin: "com.facebook.react.rootproject"
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
example/android/settings.gradle
Gradle
pluginManagement { includeBuild("../node_modules/@react-native/gradle-plugin") } plugins { id("com.facebook.react.settings") } extensions.configure(com.facebook.react.ReactSettingsExtension){ ex -> ex.autolinkLibrariesFromCommand() } rootProject.name = 'RNNavigationBarExample' include ':app' includeBuild('../node_modules/@react-native/gradle-plugin')
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
example/babel.config.js
JavaScript
const path = require("path"); const pkg = require("../package.json"); const resolverConfig = { extensions: [".ts", ".tsx", ".js", ".jsx", ".json"], alias: { [pkg.name]: path.resolve(__dirname, "../src") }, }; module.exports = { presets: ["module:@react-native/babel-preset"], plugins: [["module-resolver", resolverConfig]], };
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
example/index.js
JavaScript
import { AppRegistry } from "react-native"; import { name as appName } from "./app.json"; import { App } from "./src/App"; AppRegistry.registerComponent(appName, () => App);
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
example/ios/RNNavigationBarExample/AppDelegate.swift
Swift
import UIKit import React import React_RCTAppDelegate import ReactAppDependencyProvider @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var reactNativeDelegate: ReactNativeDelegate? var reactNativeFactory: RCTReactNativeFactory? func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil ) -> Bool { let delegate = ReactNativeDelegate() let factory = RCTReactNativeFactory(delegate: delegate) delegate.dependencyProvider = RCTAppDependencyProvider() reactNativeDelegate = delegate reactNativeFactory = factory window = UIWindow(frame: UIScreen.main.bounds) factory.startReactNative( withModuleName: "RNNavigationBarExample", in: window, launchOptions: launchOptions ) return true } } class ReactNativeDelegate: RCTDefaultReactNativeFactoryDelegate { override func sourceURL(for bridge: RCTBridge) -> URL? { self.bundleURL() } override func bundleURL() -> URL? { #if DEBUG RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index") #else Bundle.main.url(forResource: "main", withExtension: "jsbundle") #endif } }
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
example/metro.config.js
JavaScript
const path = require("path"); const pkg = require("../package.json"); const { getDefaultConfig, mergeConfig } = require("@react-native/metro-config"); const escape = require("escape-string-regexp"); const peerDependencies = Object.keys(pkg.peerDependencies); const root = path.resolve(__dirname, ".."); const projectNodeModules = path.join(__dirname, "node_modules"); const rootNodeModules = path.join(root, "node_modules"); // We need to make sure that only one version is loaded for peerDependencies // So we block them at the root, and alias them to the versions in example's node_modules const blockList = peerDependencies.map( (name) => new RegExp(`^${escape(path.join(rootNodeModules, name))}\\/.*$`), ); const extraNodeModules = peerDependencies.reduce((acc, name) => { return { ...acc, [name]: path.join(projectNodeModules, name) }; }, {}); /** * Metro configuration * https://reactnative.dev/docs/metro * * @type {import('@react-native/metro-config').MetroConfig} */ const config = { projectRoot: __dirname, watchFolders: [root], resolver: { blockList, extraNodeModules }, }; module.exports = mergeConfig(getDefaultConfig(__dirname), config);
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
example/src/App.tsx
TypeScript (TSX)
import SegmentedControl from "@react-native-segmented-control/segmented-control"; import { NavigationBar, type NavigationBarStyle, } from "@zoontek/react-native-navigation-bar"; import { useEffect, useState, type ReactNode } from "react"; import { Appearance, Text as BaseText, StatusBar, StyleSheet, Switch, useColorScheme, View, type StatusBarStyle, type TextProps, } from "react-native"; const DARK_BACKGROUND = "#1F2937"; const DARK_TEXT = "#374151"; const LIGHT_BACKGROUND = "#F9FAFB"; const LIGHT_TEXT = "#E5E7EB"; const styles = StyleSheet.create({ container: { backgroundColor: LIGHT_BACKGROUND, flex: 1, justifyContent: "center", paddingHorizontal: 16, }, darkContainer: { backgroundColor: DARK_BACKGROUND, }, row: { flexDirection: "row", alignItems: "center", }, }); const Space = ({ size }: { size: number }) => ( <View accessibilityRole="none" collapsable={true} style={{ height: size, width: size }} /> ); const Title = ({ children }: { children: ReactNode }) => ( <> <Text style={{ fontSize: 20, fontWeight: "700" }}>{children}</Text> <Space size={16} /> </> ); const Text = ({ style, ...props }: TextProps) => { const dark = useColorScheme() === "dark"; return ( <BaseText style={[{ color: dark ? LIGHT_TEXT : DARK_TEXT }, style]} {...props} /> ); }; const SCHEMES = ["system", "light", "dark"]; const STYLES: NavigationBarStyle[] = [ "default", "light-content", "dark-content", ]; export const App = () => { const dark = useColorScheme() === "dark"; const thumbColor = dark ? LIGHT_TEXT : "#fff"; const trackColor = dark ? { false: "#1c1c1f", true: "#2b3e55" } : { false: "#eeeef0", true: "#ccd8e5" }; const [schemeIndex, setSchemeIndex] = useState(0); const [statusBarStyleIndex, setStatusBarStyleIndex] = useState(0); const [navigationBarStyleIndex, setNavigationBarStyleIndex] = useState(0); const [statusBarHidden, setStatusBarHidden] = useState(false); const [navigationBarHidden, setNavigationBarHidden] = useState(false); useEffect(() => { const value = SCHEMES[schemeIndex]; const scheme = value === "light" || value === "dark" ? value : "unspecified"; Appearance.setColorScheme(scheme); }, [schemeIndex]); return ( <View style={[styles.container, dark && styles.darkContainer]}> <StatusBar animated={true} barStyle={STYLES[statusBarStyleIndex]} hidden={statusBarHidden} /> <NavigationBar barStyle={STYLES[navigationBarStyleIndex]} hidden={navigationBarHidden} /> <Title>Theme</Title> <SegmentedControl appearance={dark ? "dark" : "light"} values={SCHEMES} selectedIndex={schemeIndex} onValueChange={(value) => { setSchemeIndex(SCHEMES.indexOf(value)); }} /> <Space size={32} /> <View style={[styles.row, { justifyContent: "space-between" }]}> <Title>{"<StatusBar />"}</Title> <View style={styles.row}> <Text>Hide</Text> <Space size={4} /> <Switch thumbColor={thumbColor} trackColor={trackColor} value={statusBarHidden} onValueChange={setStatusBarHidden} /> </View> </View> <Space size={16} /> <SegmentedControl appearance={dark ? "dark" : "light"} values={STYLES} selectedIndex={statusBarStyleIndex} onValueChange={(value) => { setStatusBarStyleIndex(STYLES.indexOf(value as StatusBarStyle)); }} /> <Space size={32} /> <View style={[styles.row, { justifyContent: "space-between" }]}> <Title>{"<NavigationBar />"}</Title> <View style={styles.row}> <Text>Hide</Text> <Space size={4} /> <Switch thumbColor={thumbColor} trackColor={trackColor} value={navigationBarHidden} onValueChange={setNavigationBarHidden} /> </View> </View> <Space size={16} /> <SegmentedControl appearance={dark ? "dark" : "light"} values={STYLES} selectedIndex={navigationBarStyleIndex} onValueChange={(value) => { setNavigationBarStyleIndex( STYLES.indexOf(value as NavigationBarStyle), ); }} /> </View> ); };
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
src/NavigationBar.ts
TypeScript
import { useEffect, useMemo, useRef } from "react"; import NativeModule from "./specs/NativeNavigationBarModule"; import type { NavigationBarProps, NavigationBarStyle } from "./types"; // Merges the entries stack function mergeEntriesStack(entriesStack: NavigationBarProps[]) { return entriesStack.reduce<{ barStyle: NavigationBarStyle | undefined; hidden: boolean | undefined; }>( (prev, cur) => { for (const prop in cur) { if (cur[prop as keyof NavigationBarProps] != null) { // @ts-expect-error prev[prop] = cur[prop]; } } return prev; }, { barStyle: undefined, hidden: undefined, }, ); } // Returns an object to insert in the props stack from the props function createStackEntry({ barStyle, hidden, }: NavigationBarProps): NavigationBarProps { return { barStyle, hidden }; // Create a copy } const entriesStack: NavigationBarProps[] = []; // Timer for updating the native module values at the end of the frame let updateImmediate: NodeJS.Immediate | null = null; // The current merged values from the entries stack const currentValues: { barStyle: NavigationBarStyle | undefined; hidden: boolean | undefined; } = { barStyle: undefined, hidden: undefined, }; function setStyle(style: NavigationBarStyle | undefined) { if (style !== currentValues.barStyle) { currentValues.barStyle = style; if (NativeModule != null) { NativeModule.setStyle(style ?? "default"); } } } /** * Set the navigation bar style. * * @param style Navigation bar style to set. */ function setBarStyle(style: NavigationBarStyle) { setStyle(style); } /** * Show or hide the navigation bar. * * @param hidden Hide the navigation bar. */ function setHidden(hidden: boolean) { if (hidden !== currentValues.hidden) { currentValues.hidden = hidden; if (NativeModule != null) { NativeModule.setHidden(hidden); } } } // Updates the native navigation bar with the entries from the stack function updateEntriesStack() { if (NativeModule != null) { if (updateImmediate != null) { clearImmediate(updateImmediate); } updateImmediate = setImmediate(() => { const { barStyle, hidden } = mergeEntriesStack(entriesStack); setStyle(barStyle); if (hidden != null) { setHidden(hidden); } }); } } /** * Push a `NavigationBar` entry onto the stack. * The return value should be passed to `popStackEntry` when complete. * * @param props Object containing the `NavigationBar` props to use in the stack entry. */ function pushStackEntry(props: NavigationBarProps): NavigationBarProps { const entry = createStackEntry(props); entriesStack.push(entry); updateEntriesStack(); return entry; } /** * Remove an existing `NavigationBar` stack entry from the stack. * * @param entry Entry returned from `pushStackEntry`. */ function popStackEntry(entry: NavigationBarProps): void { const index = entriesStack.indexOf(entry); if (index !== -1) { entriesStack.splice(index, 1); } updateEntriesStack(); } /** * Replace an existing `NavigationBar` stack entry with new props. * * @param entry Entry returned from `pushStackEntry` to replace. * @param props Object containing the `NavigationBar` props to use in the replacement stack entry. */ function replaceStackEntry( entry: NavigationBarProps, props: NavigationBarProps, ): NavigationBarProps { const newEntry = createStackEntry(props); const index = entriesStack.indexOf(entry); if (index !== -1) { entriesStack[index] = newEntry; } updateEntriesStack(); return newEntry; } export function NavigationBar(props: NavigationBarProps) { const { barStyle, hidden } = props; const stableProps = useMemo<NavigationBarProps>( () => ({ barStyle, hidden }), [barStyle, hidden], ); const stackEntryRef = useRef<NavigationBarProps | null>(null); useEffect(() => { // Every time a NavigationBar component is mounted, we push it's prop to a stack // and always update the native navigation bar with the props from the top of then // stack. This allows having multiple NavigationBar components and the one that is // added last or is deeper in the view hierarchy will have priority. stackEntryRef.current = pushStackEntry(stableProps); return () => { // When a NavigationBar is unmounted, remove itself from the stack and update // the native bar with the next props. if (stackEntryRef.current) { popStackEntry(stackEntryRef.current); } }; }, []); useEffect(() => { if (stackEntryRef.current) { stackEntryRef.current = replaceStackEntry( stackEntryRef.current, stableProps, ); } }, [stableProps]); return null; } NavigationBar.pushStackEntry = pushStackEntry; NavigationBar.popStackEntry = popStackEntry; NavigationBar.replaceStackEntry = replaceStackEntry; NavigationBar.setBarStyle = setBarStyle; NavigationBar.setHidden = setHidden;
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
src/expo.ts
TypeScript
import { type ConfigPlugin, createRunOncePlugin, withAndroidStyles, } from "@expo/config-plugins"; type AndroidProps = { enforceNavigationBarContrast?: boolean; }; type Props = { android?: AndroidProps } | undefined; const withAndroidNavigationBarStyles: ConfigPlugin<Props> = ( config, props = {}, ) => { const name = "enforceNavigationBarContrast"; return withAndroidStyles(config, (config) => { const { android = {} } = props; const { enforceNavigationBarContrast } = android; config.modResults.resources.style = config.modResults.resources.style?.map( (style): typeof style => { if (style.$.name === "AppTheme") { style.item = style.item.filter((item) => item.$.name !== name); if (enforceNavigationBarContrast != null) { style.item = style.item.filter( (item) => item.$.name !== `android:${name}`, ); style.item.push({ $: { name }, _: String(enforceNavigationBarContrast), }); } } return style; }, ); return config; }); }; export default createRunOncePlugin( withAndroidNavigationBarStyles, "zoontek/react-native-navigation-bar", );
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
src/index.ts
TypeScript
export { NavigationBar } from "./NavigationBar"; export type { NavigationBarProps, NavigationBarStyle } from "./types";
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
src/specs/NativeNavigationBarModule.ts
TypeScript
import type { TurboModule } from "react-native"; import { Platform, TurboModuleRegistry } from "react-native"; interface Spec extends TurboModule { setStyle(style: string): void; setHidden(hidden: boolean): void; } export default Platform.OS === "android" ? TurboModuleRegistry.getEnforcing<Spec>("RNNavigationBar") : null;
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
src/specs/NativeNavigationBarModule.web.ts
TypeScript
export default null;
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
src/types.ts
TypeScript
export type NavigationBarStyle = "default" | "light-content" | "dark-content"; export type NavigationBarProps = { barStyle?: NavigationBarStyle; hidden?: boolean; };
zoontek/react-native-navigation-bar
81
React Native StatusBar long-lost twin: A component to control your Android app's navigation bar.
TypeScript
zoontek
Mathieu Acthernoene
Swan
ascii.go
Go
package codec var printableASCII [256]bool func init() { for b := 0; b < len(printableASCII); b++ { if '\x08' < b && b < '\x7f' { printableASCII[b] = true } } } // isPrintableASCII returns true if all bytes are printable ASCII func isPrintableASCII(b []byte) bool { for _, c := range b { if !printableASCII[c] { return false } } return true } // hasByte can be used to check if a string has at least one of the provided // bytes. Note: make sure byteset is long enough to handle the largest byte in // the string. func hasByte(data string, byteset []bool) bool { for i := 0; i < len(data); i++ { if byteset[data[i]] { return true } } return false }
zricethezav/codec
0
optimized codec
Go
zricethezav
Zachary Rice
gitleaks trufflesecurity
base64.go
Go
package codec import ( "encoding/base64" ) // likelyBase64Chars is a set of characters that you would expect to find at // least one of in base64 encoded data. This risks missing about 1% of // base64 encoded data that doesn't contain these characters, but gives you // the performance gain of not trying to decode a lot of long symbols in code. var likelyBase64Chars = make([]bool, 256) func init() { for _, c := range `0123456789+/-_` { likelyBase64Chars[c] = true } } // decodeBase64 decodes base64 encoded printable ASCII characters func decodeBase64(encodedValue string) string { // Exit early if it doesn't seem like base64 if !hasByte(encodedValue, likelyBase64Chars) { return "" } // Try standard base64 decoding decodedValue, err := base64.StdEncoding.DecodeString(encodedValue) if err == nil && isPrintableASCII(decodedValue) { return string(decodedValue) } // Try base64url decoding decodedValue, err = base64.RawURLEncoding.DecodeString(encodedValue) if err == nil && isPrintableASCII(decodedValue) { return string(decodedValue) } return "" }
zricethezav/codec
0
optimized codec
Go
zricethezav
Zachary Rice
gitleaks trufflesecurity
decoder.go
Go
package codec import ( "bytes" "github.com/betterleaks/betterleaks/logging" ) // Decoder decodes various types of data in place type Decoder struct { decodedMap map[string]string } // NewDecoder creates a default decoder struct func NewDecoder() *Decoder { return &Decoder{ decodedMap: make(map[string]string), } } // Decode returns the data with the values decoded in place along with the // encoded segment meta data for the next pass of decoding func (d *Decoder) Decode(data string, predecessors []*EncodedSegment) (string, []*EncodedSegment) { segments := d.findEncodedSegments(data, predecessors) if len(segments) > 0 { result := bytes.NewBuffer(make([]byte, 0, len(data))) encodedStart := 0 for _, segment := range segments { result.WriteString(data[encodedStart:segment.encoded.start]) result.WriteString(segment.decodedValue) encodedStart = segment.encoded.end } result.WriteString(data[encodedStart:]) return result.String(), segments } return data, segments } // findEncodedSegments finds the encoded segments in the data func (d *Decoder) findEncodedSegments(data string, predecessors []*EncodedSegment) []*EncodedSegment { if len(data) == 0 { return []*EncodedSegment{} } decodedShift := 0 encodingMatches := findEncodingMatches(data) segments := make([]*EncodedSegment, 0, len(encodingMatches)) for _, m := range encodingMatches { encodedValue := data[m.start:m.end] decodedValue, alreadyDecoded := d.decodedMap[encodedValue] if !alreadyDecoded { decodedValue = m.encoding.decode(encodedValue) d.decodedMap[encodedValue] = decodedValue } if len(decodedValue) == 0 { continue } segment := &EncodedSegment{ predecessors: predecessors, original: toOriginal(predecessors, m.startEnd), encoded: m.startEnd, decoded: startEnd{ m.start + decodedShift, m.start + decodedShift + len(decodedValue), }, decodedValue: decodedValue, encodings: m.encoding.kind, depth: 1, } // Shift decoded start and ends based on size changes decodedShift += len(decodedValue) - len(encodedValue) // Adjust depth and encoding if applicable if len(segment.predecessors) != 0 { // Set the depth based on the predecessors' depth in the previous pass segment.depth = 1 + segment.predecessors[0].depth // Adjust encodings for _, p := range segment.predecessors { if segment.encoded.overlaps(p.decoded) { segment.encodings |= p.encodings } } } segments = append(segments, segment) logging.Debug(). Str("decoder", m.encoding.kind.String()). Msgf( "segment found: original=%s pos=%s: %q -> %q", segment.original, segment.encoded, encodedValue, segment.decodedValue, ) } return segments }
zricethezav/codec
0
optimized codec
Go
zricethezav
Zachary Rice
gitleaks trufflesecurity
decoder_test.go
Go
package codec import ( "encoding/hex" "net/url" "strings" "testing" "github.com/stretchr/testify/assert" ) func TestDecode(t *testing.T) { tests := []struct { chunk string expected string name string }{ { name: "only b64 chunk", chunk: `bG9uZ2VyLWVuY29kZWQtc2VjcmV0LXRlc3Q=`, expected: `longer-encoded-secret-test`, }, { name: "mixed content", chunk: `token: bG9uZ2VyLWVuY29kZWQtc2VjcmV0LXRlc3Q=`, expected: `token: longer-encoded-secret-test`, }, { name: "no chunk", chunk: ``, expected: ``, }, { name: "env var (looks like all b64 decodable but has `=` in the middle)", chunk: `some-encoded-secret=dGVzdC1zZWNyZXQtdmFsdWU=`, expected: `some-encoded-secret=test-secret-value`, }, { name: "has longer b64 inside", chunk: `some-encoded-secret="bG9uZ2VyLWVuY29kZWQtc2VjcmV0LXRlc3Q="`, expected: `some-encoded-secret="longer-encoded-secret-test"`, }, { name: "many possible i := 0substrings", chunk: `Many substrings in this slack message could be base64 decoded but only dGhpcyBlbmNhcHN1bGF0ZWQgc2VjcmV0 should be decoded.`, expected: `Many substrings in this slack message could be base64 decoded but only this encapsulated secret should be decoded.`, }, { name: "b64-url-safe: only b64 chunk", chunk: `bG9uZ2VyLWVuY29kZWQtc2VjcmV0LXRlc3Q`, expected: `longer-encoded-secret-test`, }, { name: "b64-url-safe: mixed content", chunk: `token: bG9uZ2VyLWVuY29kZWQtc2VjcmV0LXRlc3Q`, expected: `token: longer-encoded-secret-test`, }, { name: "b64-url-safe: env var (looks like all b64 decodable but has `=` in the middle)", chunk: `some-encoded-secret=dGVzdC1zZWNyZXQtdmFsdWU=`, expected: `some-encoded-secret=test-secret-value`, }, { name: "b64-url-safe: has longer b64 inside", chunk: `some-encoded-secret="bG9uZ2VyLWVuY29kZWQtc2VjcmV0LXRlc3Q"`, expected: `some-encoded-secret="longer-encoded-secret-test"`, }, { name: "b64-url-safe: hyphen url b64", chunk: `Z2l0bGVha3M-PmZpbmRzLXNlY3JldHM`, expected: `gitleaks>>finds-secrets`, }, { name: "b64-url-safe: underscore url b64", chunk: `YjY0dXJsc2FmZS10ZXN0LXNlY3JldC11bmRlcnNjb3Jlcz8_`, expected: `b64urlsafe-test-secret-underscores??`, }, { name: "invalid base64 string", chunk: `a3d3fa7c2bb99e469ba55e5834ce79ee4853a8a3`, expected: `a3d3fa7c2bb99e469ba55e5834ce79ee4853a8a3`, }, { name: "url encoded value", chunk: `secret%3D%22q%24%21%40%23%24%25%5E%26%2A%28%20asdf%22`, expected: `secret="q$!@#$%^&*( asdf"`, }, { name: "hex encoded value", chunk: `secret="466973684D617048756E6B79212121363334"`, expected: `secret="FishMapHunky!!!634"`, }, { name: "unicode encoded value", chunk: `secret=U+0061 U+0062 U+0063 U+0064 U+0065 U+0066`, expected: "secret=abcdef", }, { name: "unicode encoded value backslashed", chunk: `secret=\\u0068\\u0065\\u006c\\u006c\\u006f\\u0020\\u0077\\u006f\\u0072\\u006c\\u0064\\u0020\\u0064\\u0075\\u0064\\u0065`, expected: "secret=hello world dude", }, { name: "unicode encoded value backslashed mixed w/ hex", chunk: `secret=\u0068\u0065\u006c\u006c\u006f\u0020\u0077\u006f\u0072\u006c\u0064 6C6F76656C792070656F706C65206F66206561727468`, expected: "secret=hello world lovely people of earth", }, } decoder := NewDecoder() fullDecode := func(data string) string { segments := []*EncodedSegment{} for { data, segments = decoder.Decode(data, segments) if len(segments) == 0 { return data } } } // Test value decoding for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert.Equal(t, tt.expected, fullDecode(tt.chunk)) }) } // Percent encode the values to test percent decoding for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { encodedChunk := url.PathEscape(tt.chunk) assert.Equal(t, tt.expected, fullDecode(encodedChunk)) }) } // Hex encode the values to test hex decoding for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { encodedChunk := hex.EncodeToString([]byte(tt.chunk)) assert.Equal(t, tt.expected, fullDecode(encodedChunk)) }) } } func TestFindEncodingMatches(t *testing.T) { t.Run("no matches", func(t *testing.T) { tests := []struct { name string input string }{ {"empty string", ""}, {"plain text", "hello world"}, {"short b64 run (15 chars)", "aBcDeFgHiJkLmNo"}, {"percent with non-hex digits", "%GGhello"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert.Nil(t, findEncodingMatches(tt.input)) }) } }) t.Run("base64 matches", func(t *testing.T) { tests := []struct { name string input string wantStr string // expected matched substring wantKind encodingKind }{ { name: "16+ char b64 run", input: "aBcDeFgHiJkLmNoPq", wantStr: "aBcDeFgHiJkLmNoPq", wantKind: base64Kind, }, { name: "b64 with 1 trailing equals", input: "aBcDeFgHiJkLmNoP=", wantStr: "aBcDeFgHiJkLmNoP=", wantKind: base64Kind, }, { name: "b64 with 2 trailing equals", input: "aBcDeFgHiJkLmNoP==", wantStr: "aBcDeFgHiJkLmNoP==", wantKind: base64Kind, }, { name: "b64 stops at 2 trailing equals", input: "aBcDeFgHiJkLmNoP===", wantStr: "aBcDeFgHiJkLmNoP==", wantKind: base64Kind, }, { name: "31 hex chars falls to b64", input: "aabbccdd00112233aabbccdd0011223", wantStr: "aabbccdd00112233aabbccdd0011223", wantKind: base64Kind, }, { name: "mixed hex and non-hex is b64", input: "aabbccddG0112233aabbccdd0011223", wantStr: "aabbccddG0112233aabbccdd0011223", wantKind: base64Kind, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { matches := findEncodingMatches(tt.input) assert.Len(t, matches, 1) assert.Equal(t, tt.wantKind, matches[0].encoding.kind) assert.Equal(t, tt.wantStr, tt.input[matches[0].start:matches[0].end]) }) } }) t.Run("hex matches", func(t *testing.T) { tests := []struct { name string input string }{ {"exactly 32 hex chars", "aabbccdd00112233aabbccdd00112233"}, {"64 hex chars", "aabbccdd00112233aabbccdd00112233aabbccdd00112233aabbccdd00112233"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { matches := findEncodingMatches(tt.input) assert.Len(t, matches, 1) assert.Equal(t, hexKind, matches[0].encoding.kind) }) } }) t.Run("percent matches", func(t *testing.T) { tests := []struct { name string input string wantStr string }{ { name: "single %XX", input: "hello%20world", wantStr: "%20", }, { name: "greedy span to last %XX on line", input: "%20stuff%3D", wantStr: "%20stuff%3D", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { matches := findEncodingMatches(tt.input) assert.Len(t, matches, 1) assert.Equal(t, percentKind, matches[0].encoding.kind) assert.Equal(t, tt.wantStr, tt.input[matches[0].start:matches[0].end]) }) } }) t.Run("percent does not cross newlines", func(t *testing.T) { input := "%20hello\n%3D" matches := findEncodingMatches(input) assert.Len(t, matches, 2) assert.Equal(t, "%20", input[matches[0].start:matches[0].end]) assert.Equal(t, "%3D", input[matches[1].start:matches[1].end]) }) t.Run("unicode matches", func(t *testing.T) { tests := []struct { name string input string wantStr string }{ { name: "U+XXXX at end of string", input: "U+0041", wantStr: "U+0041", }, { name: "U+XXXX with trailing whitespace", input: "U+0041 ", wantStr: "U+0041", }, { name: "multiple U+XXXX sequences", input: "U+0048 U+0069", wantStr: "U+0048 U+0069", }, { name: "single backslash escape sequence", input: `\u0048\u0069\u0021\u0021\u0021\u0021`, wantStr: `\u0048\u0069\u0021\u0021\u0021\u0021`, }, { name: "double backslash escape sequence", input: `\\u0048\\u0069`, wantStr: `\\u0048\\u0069`, }, { name: "case insensitive uppercase U", input: `\U0048\U0069\U0021\U0021\U0021\U0021`, wantStr: `\U0048\U0069\U0021\U0021\U0021\U0021`, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { matches := findEncodingMatches(tt.input) assert.Len(t, matches, 1) assert.Equal(t, unicodeKind, matches[0].encoding.kind) assert.Equal(t, tt.wantStr, tt.input[matches[0].start:matches[0].end]) }) } }) t.Run("not unicode", func(t *testing.T) { tests := []struct { name string input string }{ {"U+XXXX without trailing whitespace or end", "U+0041X"}, {"backslash not followed by u", `\n\t\r`}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { for _, m := range findEncodingMatches(tt.input) { assert.NotEqual(t, unicodeKind, m.encoding.kind) } }) } }) t.Run("precedence and multi-type", func(t *testing.T) { tests := []struct { name string input string wantKinds []encodingKind }{ { name: "percent wins over overlapping b64", input: "secret%3D%22longvalue1234567%22", wantKinds: []encodingKind{percentKind}, }, { name: "percent and b64 in same string", input: `%20%20 bG9uZ2VyLWVuY29kZWQtc2VjcmV0LXRlc3Q=`, wantKinds: []encodingKind{percentKind, base64Kind}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { matches := findEncodingMatches(tt.input) assert.Len(t, matches, len(tt.wantKinds)) for i, wk := range tt.wantKinds { assert.Equal(t, wk, matches[i].encoding.kind) } }) } }) } func TestDecodeUnicode(t *testing.T) { tests := []struct { name string input string expected string }{ {"single U+XXXX", "U+0041", "A"}, {"U+XXXX with surrounding text", "key=U+0041", "key=A"}, {"mixed single and double backslash", `\u0041\\u0042`, "AB"}, {"uppercase U in escape", `\U0041\U0042`, "AB"}, {"no unicode returns unchanged", "just plain text", "just plain text"}, {"invalid hex in U+XXXX returns unchanged", "U+ZZZZ", "U+ZZZZ"}, {"invalid hex in backslash escape returns unchanged", `\uZZZZ`, `\uZZZZ`}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert.Equal(t, tt.expected, decodeUnicode(tt.input)) }) } } func TestDecodeEdgeCases(t *testing.T) { tests := []struct { name string chunk string expected string }{ { name: "long identifier not falsely decoded", chunk: "SomeVeryLongVariable", expected: "SomeVeryLongVariable", }, { name: "hex exactly 32 chars decodes", chunk: hex.EncodeToString([]byte("abcdefghijklmnop")), expected: "abcdefghijklmnop", }, { name: "double encoded percent", chunk: url.PathEscape(url.PathEscape("hello=world")), expected: "hello=world", }, { name: "percent then b64 in same string", chunk: `%48%65%6C%6C%6F token=bG9uZ2VyLWVuY29kZWQtc2VjcmV0LXRlc3Q=`, expected: `Hello token=longer-encoded-secret-test`, }, { name: "many short words no false positives", chunk: "func main() { fmt.Println(x, y, z) }", expected: "func main() { fmt.Println(x, y, z) }", }, { name: "newline separates independent hex matches", chunk: hex.EncodeToString([]byte("line-one-secret!")) + "\n" + hex.EncodeToString([]byte("line-two-secret!")), expected: "line-one-secret!\nline-two-secret!", }, { name: "U+XXXX sequence fully decodes", chunk: "U+0073 U+0065 U+0063 U+0072 U+0065 U+0074", expected: "secret", }, { name: "long hex-only string non-printable ascii unchanged", chunk: strings.Repeat("ff", 16), expected: strings.Repeat("ff", 16), }, } decoder := NewDecoder() fullDecode := func(data string) string { segments := []*EncodedSegment{} for { data, segments = decoder.Decode(data, segments) if len(segments) == 0 { return data } } } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert.Equal(t, tt.expected, fullDecode(tt.chunk)) }) } }
zricethezav/codec
0
optimized codec
Go
zricethezav
Zachary Rice
gitleaks trufflesecurity
encodings.go
Go
package codec import ( "math" ) // Lookup tables for byte classification. var ( isHexChar [256]bool // 0-9, A-F, a-f isB64Char [256]bool // 0-9, A-Z, a-z, _, /, +, - (matches [\w\/+-]) isB64NotHex [256]bool // b64 chars that are NOT hex (G-Z, g-z, _, /, +, -) isWhitespace [256]bool // space, tab, \n, \r, etc. ) func init() { for c := '0'; c <= '9'; c++ { isHexChar[c] = true isB64Char[c] = true } for c := 'A'; c <= 'F'; c++ { isHexChar[c] = true isB64Char[c] = true } for c := 'a'; c <= 'f'; c++ { isHexChar[c] = true isB64Char[c] = true } for c := 'G'; c <= 'Z'; c++ { isB64Char[c] = true isB64NotHex[c] = true } for c := 'g'; c <= 'z'; c++ { isB64Char[c] = true isB64NotHex[c] = true } isB64Char['_'] = true isB64NotHex['_'] = true isB64Char['/'] = true isB64NotHex['/'] = true isB64Char['+'] = true isB64NotHex['+'] = true isB64Char['-'] = true isB64NotHex['-'] = true isWhitespace[' '] = true isWhitespace['\t'] = true isWhitespace['\n'] = true isWhitespace['\r'] = true isWhitespace['\f'] = true isWhitespace['\v'] = true } var ( encodings = []*encoding{ { kind: percentKind, decode: decodePercent, precedence: 4, }, { kind: unicodeKind, decode: decodeUnicode, precedence: 3, }, { kind: hexKind, decode: decodeHex, precedence: 2, }, { kind: base64Kind, decode: decodeBase64, precedence: 1, }, } ) // encodingNames is used to map the encodingKinds to their name var encodingNames = []string{ "percent", "unicode", "hex", "base64", } // encodingKind can be or'd together to capture all of the unique encodings // that were present in a segment type encodingKind int var ( // make sure these go up by powers of 2 percentKind = encodingKind(1) unicodeKind = encodingKind(2) hexKind = encodingKind(4) base64Kind = encodingKind(8) ) func (e encodingKind) String() string { i := int(math.Log2(float64(e))) if i >= len(encodingNames) { return "" } return encodingNames[i] } // kinds returns a list of encodingKinds combined in this one func (e encodingKind) kinds() []encodingKind { kinds := []encodingKind{} for i := 0; i < len(encodingNames); i++ { if kind := int(e) & int(math.Pow(2, float64(i))); kind != 0 { kinds = append(kinds, encodingKind(kind)) } } return kinds } // encodingMatch represents a match of an encoding in the text type encodingMatch struct { encoding *encoding startEnd } // encoding represent a type of coding supported by the decoder. type encoding struct { // the kind of decoding (e.g. base64, etc) kind encodingKind // take the match and return the decoded value decode func(string) string // determine which encoding should win out when two overlap precedence int } // findEncodingMatches finds as many encodings as it can for this pass // using a single-pass byte-level scanner instead of regex. func findEncodingMatches(data string) []encodingMatch { n := len(data) if n == 0 { return nil } var all []encodingMatch i := 0 for i < n { c := data[i] // --- Percent encoding: %XX --- if c == '%' && i+2 < n && isHexChar[data[i+1]] && isHexChar[data[i+2]] { start := i // Scan forward to find the last %XX on this line. // The regex `%XX(?:.*%XX)?` is greedy and matches from the first // %XX through any chars (except \n) to the last %XX on the line. lastPercentEnd := i + 3 j := i + 3 for j < n && data[j] != '\n' { if data[j] == '%' && j+2 < n && isHexChar[data[j+1]] && isHexChar[data[j+2]] { lastPercentEnd = j + 3 } j++ } all = append(all, encodingMatch{ encoding: encodings[0], // percent startEnd: startEnd{start, lastPercentEnd}, }) i = lastPercentEnd continue } // --- Unicode code points: U+XXXX --- if c == 'U' && i+5 < n && data[i+1] == '+' && isHexChar[data[i+2]] && isHexChar[data[i+3]] && isHexChar[data[i+4]] && isHexChar[data[i+5]] { // Check that the next char after the 4 hex digits is whitespace or end. // The regex requires (?:\s|$) after each U+XXXX. afterHex := i + 6 if afterHex >= n || isWhitespace[data[afterHex]] { start := i end := afterHex // Consume additional U+XXXX sequences separated by whitespace j := afterHex for j < n { // Skip whitespace between code points if !isWhitespace[data[j]] { break } ws := j for ws < n && isWhitespace[data[ws]] { ws++ } // Check for another U+XXXX if ws+5 < n && data[ws] == 'U' && data[ws+1] == '+' && isHexChar[data[ws+2]] && isHexChar[data[ws+3]] && isHexChar[data[ws+4]] && isHexChar[data[ws+5]] { nextAfter := ws + 6 if nextAfter >= n || isWhitespace[data[nextAfter]] { end = nextAfter j = nextAfter continue } } break } all = append(all, encodingMatch{ encoding: encodings[1], // unicode startEnd: startEnd{start, end}, }) i = end continue } } // --- Unicode escapes: \uXXXX or \\uXXXX --- if c == '\\' { matched := false // Check for \\uXXXX (double backslash) if i+7 < n && data[i+1] == '\\' { uc := data[i+2] if (uc == 'u' || uc == 'U') && isHexChar[data[i+3]] && isHexChar[data[i+4]] && isHexChar[data[i+5]] && isHexChar[data[i+6]] { start := i end := i + 7 // Consume additional \\uXXXX or \uXXXX sequences j := end for j < n { if j+6 < n && data[j] == '\\' && data[j+1] == '\\' { uc2 := data[j+2] if (uc2 == 'u' || uc2 == 'U') && isHexChar[data[j+3]] && isHexChar[data[j+4]] && isHexChar[data[j+5]] && isHexChar[data[j+6]] { end = j + 7 j = end continue } } if j+5 < n && data[j] == '\\' { uc2 := data[j+1] if (uc2 == 'u' || uc2 == 'U') && isHexChar[data[j+2]] && isHexChar[data[j+3]] && isHexChar[data[j+4]] && isHexChar[data[j+5]] { end = j + 6 j = end continue } } break } all = append(all, encodingMatch{ encoding: encodings[1], // unicode startEnd: startEnd{start, end}, }) i = end matched = true } } // Check for \uXXXX (single backslash) if !matched && i+5 < n { uc := data[i+1] if (uc == 'u' || uc == 'U') && isHexChar[data[i+2]] && isHexChar[data[i+3]] && isHexChar[data[i+4]] && isHexChar[data[i+5]] { start := i end := i + 6 // Consume additional \uXXXX or \\uXXXX sequences j := end for j < n { if j+6 < n && data[j] == '\\' && data[j+1] == '\\' { uc2 := data[j+2] if (uc2 == 'u' || uc2 == 'U') && isHexChar[data[j+3]] && isHexChar[data[j+4]] && isHexChar[data[j+5]] && isHexChar[data[j+6]] { end = j + 7 j = end continue } } if j+5 < n && data[j] == '\\' { uc2 := data[j+1] if (uc2 == 'u' || uc2 == 'U') && isHexChar[data[j+2]] && isHexChar[data[j+3]] && isHexChar[data[j+4]] && isHexChar[data[j+5]] { end = j + 6 j = end continue } } break } all = append(all, encodingMatch{ encoding: encodings[1], // unicode startEnd: startEnd{start, end}, }) i = end matched = true } } if matched { continue } } // --- Hex / Base64 runs --- if isB64Char[c] { start := i allHex := !isB64NotHex[c] i++ for i < n && isB64Char[data[i]] { if isB64NotHex[data[i]] { allHex = false } i++ } runLen := i - start end := i // Count trailing '=' (up to 2) for base64 padding eqCount := 0 for eqCount < 2 && end < n && data[end] == '=' { eqCount++ end++ } if allHex && runLen >= 32 { // Emit as hex match (without trailing =) all = append(all, encodingMatch{ encoding: encodings[2], // hex startEnd: startEnd{start, start + runLen}, }) } else if runLen >= 16 { // Emit as base64 match (include trailing =) all = append(all, encodingMatch{ encoding: encodings[3], // base64 startEnd: startEnd{start, end}, }) } continue } i++ } totalMatches := len(all) if totalMatches <= 1 { return all } // filter out lower precedence ones that overlap their neighbors filtered := make([]encodingMatch, 0, len(all)) for i, m := range all { if i > 0 { prev := all[i-1] if m.overlaps(prev.startEnd) && prev.encoding.precedence > m.encoding.precedence { continue // skip this one } } if i+1 < totalMatches { next := all[i+1] if m.overlaps(next.startEnd) && next.encoding.precedence > m.encoding.precedence { continue // skip this one } } filtered = append(filtered, m) } return filtered }
zricethezav/codec
0
optimized codec
Go
zricethezav
Zachary Rice
gitleaks trufflesecurity
hex.go
Go
package codec // hexMap is a precalculated map of hex nibbles const hexMap = "" + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\xff\xff\xff\xff\xff\xff" + "\xff\x0a\x0b\x0c\x0d\x0e\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff" + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + "\xff\x0a\x0b\x0c\x0d\x0e\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff" + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" // likelyHexChars is a set of characters that you would expect to find at // least one of in hex encoded data. This risks missing some hex data that // doesn't contain these characters, but gives you the performance gain of not // trying to decode a lot of long symbols in code. var likelyHexChars = make([]bool, 256) func init() { for _, c := range `0123456789` { likelyHexChars[c] = true } } // decodeHex decodes hex data func decodeHex(encodedValue string) string { size := len(encodedValue) // hex should have two characters per byte if size%2 != 0 { return "" } if !hasByte(encodedValue, likelyHexChars) { return "" } decodedValue := make([]byte, size/2) for i := 0; i < size; i += 2 { n1 := hexMap[encodedValue[i]] n2 := hexMap[encodedValue[i+1]] if n1|n2 == '\xff' { return "" } b := n1<<4 | n2 if !printableASCII[b] { return "" } decodedValue[i/2] = b } return string(decodedValue) }
zricethezav/codec
0
optimized codec
Go
zricethezav
Zachary Rice
gitleaks trufflesecurity
percent.go
Go
package codec // decodePercent decodes percent encoded strings func decodePercent(encodedValue string) string { encLen := len(encodedValue) decodedValue := make([]byte, encLen) decIndex := 0 encIndex := 0 for encIndex < encLen { if encodedValue[encIndex] == '%' && encIndex+2 < encLen { n1 := hexMap[encodedValue[encIndex+1]] n2 := hexMap[encodedValue[encIndex+2]] // Make sure they're hex characters if n1|n2 != '\xff' { b := n1<<4 | n2 if !printableASCII[b] { return "" } decodedValue[decIndex] = b encIndex += 3 decIndex += 1 continue } } decodedValue[decIndex] = encodedValue[encIndex] encIndex += 1 decIndex += 1 } return string(decodedValue[:decIndex]) }
zricethezav/codec
0
optimized codec
Go
zricethezav
Zachary Rice
gitleaks trufflesecurity
segment.go
Go
package codec import ( "fmt" ) // EncodedSegment represents a portion of text that is encoded in some way. type EncodedSegment struct { // predecessors are all of the segments from the previous decoding pass predecessors []*EncodedSegment // original start/end indices before decoding original startEnd // encoded start/end indices relative to the previous decoding pass. // If it's a top level segment, original and encoded will be the // same. encoded startEnd // decoded start/end indices in this pass after decoding decoded startEnd // decodedValue contains the decoded string for this segment decodedValue string // encodings is the encodings that make up this segment. encodingKind // can be or'd together to hold multiple encodings encodings encodingKind // depth is how many decoding passes it took to decode this segment depth int } // Tags returns additional meta data tags related to the types of segments func Tags(segments []*EncodedSegment) []string { // Return an empty list if we don't have any segments if len(segments) == 0 { return []string{} } // Since decoding is done in passes, the depth of all the segments // should be the same depth := segments[0].depth // Collect the encodings from the segments encodings := segments[0].encodings for i := 1; i < len(segments); i++ { encodings |= segments[i].encodings } kinds := encodings.kinds() tags := make([]string, len(kinds)+1) tags[len(tags)-1] = fmt.Sprintf("decode-depth:%d", depth) for i, kind := range kinds { tags[i] = fmt.Sprintf("decoded:%s", kind) } return tags } // CurrentLine returns from the start of the line containing the segments // to the end of the line where the segment ends. func CurrentLine(segments []*EncodedSegment, currentRaw string) string { // Return the whole thing if no segments are provided if len(segments) == 0 { return currentRaw } start := 0 end := len(currentRaw) // Merge the ranges together into a single decoded value decoded := segments[0].decoded for i := 1; i < len(segments); i++ { decoded = decoded.merge(segments[i].decoded) } // Find the start of the range for i := decoded.start; i > -1; i-- { c := currentRaw[i] if c == '\n' { start = i break } } // Find the end of the range for i := decoded.end; i < end; i++ { c := currentRaw[i] if c == '\n' { end = i break } } return currentRaw[start:end] } // AdjustMatchIndex maps a match index from the current decode pass back to // its location in the original text func AdjustMatchIndex(segments []*EncodedSegment, matchIndex []int) []int { // Don't adjust if we're not provided any segments if len(segments) == 0 { return matchIndex } // Map the match to the location in the original text match := startEnd{matchIndex[0], matchIndex[1]} // Map the match to its orignal location adjusted := toOriginal(segments, match) // Return the adjusted match index return []int{ adjusted.start, adjusted.end, } } // SegmentsWithDecodedOverlap the segments where the start and end overlap its // decoded range func SegmentsWithDecodedOverlap(segments []*EncodedSegment, start, end int) []*EncodedSegment { se := startEnd{start, end} overlaps := []*EncodedSegment{} for _, segment := range segments { if segment.decoded.overlaps(se) { overlaps = append(overlaps, segment) } } return overlaps } // toOriginal maps a start/end to its start/end in the original text // the provided start/end should be relative to the segment's decoded value func toOriginal(predecessors []*EncodedSegment, decoded startEnd) startEnd { if len(predecessors) == 0 { return decoded } // Map the decoded value one level up where it was encoded encoded := startEnd{} for _, p := range predecessors { if !p.decoded.overlaps(decoded) { continue // Not in scope } // If fully contained, return the segments original start/end if p.decoded.contains(decoded) { return p.original } // Map the value to be relative to the predecessors's decoded values if encoded.end == 0 { encoded = p.encoded.add(p.decoded.overflow(decoded)) } else { encoded = encoded.merge(p.encoded.add(p.decoded.overflow(decoded))) } } // Should only get here if the thing passed in wasn't in a decoded // value. This shouldn't be the case if encoded.end == 0 { return decoded } // Climb up another level // (NOTE: each segment references all the predecessors) return toOriginal(predecessors[0].predecessors, encoded) }
zricethezav/codec
0
optimized codec
Go
zricethezav
Zachary Rice
gitleaks trufflesecurity
start_end.go
Go
package codec import ( "fmt" ) // startEnd represents the start and end of some data. It mainly exists as a // helper when referencing the values type startEnd struct { start int end int } // sub subtracts the values of two startEnds func (s startEnd) sub(o startEnd) startEnd { return startEnd{ s.start - o.start, s.end - o.end, } } // add adds the values of two startEnds func (s startEnd) add(o startEnd) startEnd { return startEnd{ s.start + o.start, s.end + o.end, } } // overlaps returns true if two startEnds overlap func (s startEnd) overlaps(o startEnd) bool { return o.start <= s.end && o.end >= s.start } // contains returns true if the other is fully contained within this one func (s startEnd) contains(o startEnd) bool { return s.start <= o.start && o.end <= s.end } // overflow returns a startEnd that tells how much the other goes outside the // bounds of this one func (s startEnd) overflow(o startEnd) startEnd { return s.merge(o).sub(s) } // merge takes two start/ends and returns a single one that encompasses both func (s startEnd) merge(o startEnd) startEnd { return startEnd{ min(s.start, o.start), max(s.end, o.end), } } // String returns a string representation for clearer debugging func (s startEnd) String() string { return fmt.Sprintf("[%d,%d]", s.start, s.end) }
zricethezav/codec
0
optimized codec
Go
zricethezav
Zachary Rice
gitleaks trufflesecurity
unicode.go
Go
package codec import ( "strings" "unicode/utf8" ) // Unicode characters are encoded as 1 to 4 bytes per rune. const maxBytesPerRune = 4 // parseHex4 parses exactly 4 hex characters into a rune value. // Returns the rune and true on success, 0 and false on failure. func parseHex4(s string, offset int) (rune, bool) { if offset+4 > len(s) { return 0, false } var val rune for i := 0; i < 4; i++ { n := hexMap[s[offset+i]] if n == '\xff' { return 0, false } val = val<<4 | rune(n) } return val, true } // decodeUnicode decodes Unicode escape sequences in the given string. // Handles both U+XXXX code point notation and \uXXXX / \\uXXXX escape sequences. func decodeUnicode(encodedValue string) string { // Determine which format we're dealing with if strings.Contains(encodedValue, "U+") { return decodeUnicodeCodePoints(encodedValue) } if strings.Contains(encodedValue, `\u`) || strings.Contains(encodedValue, `\U`) { return decodeUnicodeEscapes(encodedValue) } return encodedValue } // decodeUnicodeCodePoints decodes U+XXXX sequences with byte scanning. func decodeUnicodeCodePoints(s string) string { n := len(s) var buf strings.Builder buf.Grow(n) utf8Bytes := make([]byte, maxBytesPerRune) i := 0 changed := false for i < n { // Look for U+XXXX if i+5 < n && s[i] == 'U' && s[i+1] == '+' { r, ok := parseHex4(s, i+2) if ok { changed = true utf8Len := utf8.EncodeRune(utf8Bytes, r) buf.Write(utf8Bytes[:utf8Len]) i += 6 // Skip trailing whitespace/separator between code points // The regex matched `U+XXXX.?` where .? consumed a trailing char, // and the multi pattern split on whitespace. if i < n && (s[i] == ' ' || s[i] == '\t') { // Only skip the space if the next thing is another U+XXXX // (to avoid eating meaningful trailing spaces) if i+6 < n && s[i+1] == 'U' && s[i+2] == '+' { i++ // skip separator } } continue } } buf.WriteByte(s[i]) i++ } if !changed { return s } return buf.String() } // decodeUnicodeEscapes decodes \uXXXX and \\uXXXX sequences with byte scanning. func decodeUnicodeEscapes(s string) string { n := len(s) var buf strings.Builder buf.Grow(n) utf8Bytes := make([]byte, maxBytesPerRune) i := 0 changed := false for i < n { if s[i] == '\\' { // Check for \\uXXXX (double backslash + u + 4 hex) if i+6 < n && s[i+1] == '\\' { uc := s[i+2] if uc == 'u' || uc == 'U' { r, ok := parseHex4(s, i+3) if ok { changed = true utf8Len := utf8.EncodeRune(utf8Bytes, r) buf.Write(utf8Bytes[:utf8Len]) i += 7 continue } } } // Check for \uXXXX (single backslash + u + 4 hex) if i+5 < n { uc := s[i+1] if uc == 'u' || uc == 'U' { r, ok := parseHex4(s, i+2) if ok { changed = true utf8Len := utf8.EncodeRune(utf8Bytes, r) buf.Write(utf8Bytes[:utf8Len]) i += 6 continue } } } } buf.WriteByte(s[i]) i++ } if !changed { return s } return buf.String() }
zricethezav/codec
0
optimized codec
Go
zricethezav
Zachary Rice
gitleaks trufflesecurity
searcher.go
Go
package icanhazwordz import ( "sort" "strings" ahocorasick "github.com/BobuSumisu/aho-corasick" ) // Default filter ignores single character words. // If you want to include them, set MinLength to 1. var DefaultFilter = Filter{MinLength: 2, MaxLength: 0, PreferLongestNonOverlapping: false} // Match represents a found word match type Match struct { Word string `json:"word"` StartPos int `json:"start_pos"` EndPos int `json:"end_pos"` } // Result represents the result of English word detection type Result struct { WordCount int `json:"word_count"` UniqueWords []string `json:"unique_words"` Matches []Match `json:"matches"` } // Filter defines criteria for filtering words type Filter struct { MinLength int // Minimum word length (inclusive) MaxLength int // Maximum word length (inclusive, 0 means no limit) ExactLength int // Exact word length (0 means no exact match required) PreferLongestNonOverlapping bool // Prefer longest non-overlapping matches. e.g. "hello" vs "hell" } // Searcher provides nltk English word detection with configurable filters type Searcher struct { trie *ahocorasick.Trie words []string filter Filter } // NewSearcher creates a new searcher with the specified word filters func NewSearcher(filter Filter) *Searcher { words := getFilteredWords(filter) return &Searcher{ trie: ahocorasick.NewTrieBuilder().AddStrings(words).Build(), words: words, filter: filter, } } // GetWordCount returns the number of words in this searcher's dictionary func (s *Searcher) GetWordCount() int { return len(s.words) } // GetWords returns all words in this searcher's dictionary func (s *Searcher) GetWords() []string { return append([]string(nil), s.words...) } // Find analyzes text using this searcher's word list func (s *Searcher) Find(text string) Result { if text == "" { return Result{ WordCount: 0, UniqueWords: []string{}, Matches: []Match{}, } } textLower := strings.ToLower(text) matches := s.trie.MatchString(textLower) var allMatches []Match for _, match := range matches { word := match.MatchString() startPos := int(match.Pos()) endPos := startPos + len(word) allMatches = append(allMatches, Match{ Word: word, StartPos: startPos, EndPos: endPos, }) } // Conditionally filter out overlapping matches finalMatches := allMatches if s.filter.PreferLongestNonOverlapping { finalMatches = filterOverlappingMatches(allMatches) } // Build unique words map from final matches uniqueWordsMap := make(map[string]bool) for _, match := range finalMatches { uniqueWordsMap[match.Word] = true } var uniqueWords []string for word := range uniqueWordsMap { uniqueWords = append(uniqueWords, word) } return Result{ WordCount: len(finalMatches), UniqueWords: uniqueWords, Matches: finalMatches, } } // filterOverlappingMatches removes overlapping matches, keeping only the longest non-overlapping ones func filterOverlappingMatches(matches []Match) []Match { if len(matches) == 0 { return matches } // Sort matches by start position, then by length (longest first for same start position) sort.Slice(matches, func(i, j int) bool { if matches[i].StartPos == matches[j].StartPos { return len(matches[i].Word) > len(matches[j].Word) // Longer words first } return matches[i].StartPos < matches[j].StartPos }) var result []Match lastEndPos := -1 for _, match := range matches { // If this match doesn't overlap with the last accepted match if match.StartPos >= lastEndPos { result = append(result, match) lastEndPos = match.EndPos } // If it overlaps, we skip it (since we sorted by length, the previous one was longer) } return result } // getFilteredWords returns words filtered by the given criteria func getFilteredWords(filter Filter) []string { var filtered []string for _, word := range nltkWords { wordLen := len(word) // Check exact length filter first if filter.ExactLength > 0 { if wordLen == filter.ExactLength { filtered = append(filtered, word) } continue } // Check min length if filter.MinLength > 0 && wordLen < filter.MinLength { continue } // Check max length (0 means no limit) if filter.MaxLength > 0 && wordLen > filter.MaxLength { continue } filtered = append(filtered, word) } return filtered }
zricethezav/icanhazwordz
0
does this string contain words?
Go
zricethezav
Zachary Rice
gitleaks trufflesecurity
searcher_test.go
Go
package icanhazwordz import ( "testing" ) func TestSearcherFindExact(t *testing.T) { // Use a simple filter for testing searcher := NewSearcher(Filter{ExactLength: 5}) tests := []struct { name string text string numMatches int }{ { name: "exact filter", text: "hello world", numMatches: 2, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := searcher.Find(tt.text) if result.WordCount != tt.numMatches { t.Errorf("expected %d matches, got %d. Words: %v", tt.numMatches, result.WordCount, result.Matches) } }) } } func TestSearcherFindDefault(t *testing.T) { // Use a simple filter for testing searcher := NewSearcher(DefaultFilter) tests := []struct { name string text string numMatches int }{ { name: "default filter", text: "hello world", numMatches: 9, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := searcher.Find(tt.text) if result.WordCount != tt.numMatches { t.Errorf("expected %d matches, got %d. Words: %v", tt.numMatches, result.WordCount, result.Matches) } }) } } func TestSearcherFindWithFilter(t *testing.T) { // should only match "hell" in "hello world" filter := Filter{MinLength: 3, MaxLength: 4, PreferLongestNonOverlapping: true} searcher := NewSearcher(filter) tests := []struct { name string text string numMatches int }{ { name: "test min and max", text: "The quick brown fox jumps over the lazy dog", numMatches: 8, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := searcher.Find(tt.text) if result.WordCount != tt.numMatches { t.Errorf("expected %d matches, got %d. Words: %v", tt.numMatches, result.WordCount, result.Matches) } }) } }
zricethezav/icanhazwordz
0
does this string contain words?
Go
zricethezav
Zachary Rice
gitleaks trufflesecurity
gitleaks.js
JavaScript
/** * Gitleaks WASM Integration and UI Management * * This file ties together our secret scanning logic (powered by Gitleaks via WASM) * with the browser's UI. It handles scanning operations, displays findings, * and integrates with the Rule Wizard. */ // ============================================= // Global Variables // ============================================= let gitleaksModule; let currentFindings = []; let currentSort = { column: null, direction: 'asc' }; let highlightMarkers = []; // ============================================= // WASM & Gitleaks Module Loading // ============================================= /** * Loads the default configuration from the WASM function, if available. */ function loadDefaultConfig() { if (typeof window.getDefaultConfig !== 'function') { console.warn("getDefaultConfig() not found. Possibly WASM not loaded yet."); return; } // Check if we have a pending shared state from a URL if (window.pendingSharedState) { console.log("Found pending shared state, loading instead of default config"); // If we're using the default config flag, just load default config with custom settings if (window.pendingSharedState.useDefaultConfig) { console.log("Using default config with custom settings"); const defaultConfig = window.getDefaultConfig(); configEditor.setValue(defaultConfig); // Apply custom settings if (window.pendingSharedState.logLevel) { document.getElementById("logLevelSelect").value = window.pendingSharedState.logLevel; } if (window.pendingSharedState.activeTab) { document.querySelector(`.tab-btn[data-tab="${window.pendingSharedState.activeTab}"]`).click(); } } // Otherwise load custom config from the shared state else if (window.pendingSharedState.config) { configEditor.setValue(window.pendingSharedState.config); // Set log level if present if (window.pendingSharedState.logLevel) { document.getElementById("logLevelSelect").value = window.pendingSharedState.logLevel; } // Switch to the correct tab if specified if (window.pendingSharedState.activeTab) { document.querySelector(`.tab-btn[data-tab="${window.pendingSharedState.activeTab}"]`).click(); } } // Load input text if present in a separate window variable if (window.pendingInputText) { editor.setValue(window.pendingInputText); window.pendingInputText = null; } // Clear the pending state so we don't load it again window.pendingSharedState = null; // Show notification showNotification("Shared configuration loaded successfully!"); // Hide the loading overlay now that content is loaded if (typeof hideLoadingOverlay === 'function') { hideLoadingOverlay(); } return; } try { const defaultConfig = window.getDefaultConfig(); configEditor.setValue(defaultConfig); console.log("Default config loaded into editor"); // Hide the loading overlay if it exists (for cases where hash existed but was invalid) if (typeof hideLoadingOverlay === 'function') { hideLoadingOverlay(); } } catch (err) { console.error("Error fetching default config:", err); // Hide the loading overlay on error if (typeof hideLoadingOverlay === 'function') { hideLoadingOverlay(); } } } /** * Loads and initializes the Gitleaks WASM module. */ async function loadGitleaks() { console.log("Starting Gitleaks loading process..."); if (!window.Go) { console.error("Go is not defined! Make sure wasm_exec.js is loaded properly"); throw new Error("Go is not defined"); } const go = new Go(); console.log("Go instance created"); try { console.log("Fetching gitleaks.wasm..."); const response = await fetch("gitleaks.wasm"); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const buffer = await response.arrayBuffer(); console.log("WASM buffer received, instantiating..."); const result = await WebAssembly.instantiate(buffer, go.importObject); gitleaksModule = result.instance; console.log("WASM module instantiated"); console.log("Starting Go runtime..."); // Run the Go runtime (don't await so that the UI can continue initializing) go.run(gitleaksModule); console.log("Gitleaks successfully loaded and functions registered"); loadDefaultConfig(); } catch (err) { console.error("Error during Gitleaks initialization:", err); document.getElementById("results").innerHTML = `<p class="error">Failed to load Gitleaks WASM: ${err}</p>`; } } // ============================================= // Scanning and Results Handling // ============================================= /** * Initiates a secret scan on the content from the editor. */ async function scan() { // Clear any existing highlights in the editor clearHighlights(); // Update and validate config each time the scan is initiated if (typeof window.setUserConfig !== 'function') { console.error("setUserConfig() not available. Is WASM loaded?"); document.getElementById("results").innerHTML = "<p class='error'>Error: setUserConfig function not loaded.</p>"; return; } const configStr = configEditor.getValue(); const configResult = window.setUserConfig(configStr); if (typeof configResult === 'string' && configResult.startsWith("Error:")) { document.getElementById("results").innerHTML = `<p class='error'>${configResult}</p>`; return; } const inputText = editor.getValue(); const scannedBytes = new Blob([inputText]).size; const resultsDiv = document.getElementById("results"); resultsDiv.innerHTML = ""; // Show spinner during scanning const spinner = document.createElement('div'); spinner.className = 'spinner'; resultsDiv.appendChild(spinner); // Allow the spinner to render before starting the scan await new Promise(resolve => setTimeout(resolve, 50)); // Get the selected log level from the dropdown const logLevel = document.getElementById("logLevelSelect").value; const startTime = performance.now(); let scanResult; try { // Pass both the input text and the log level to the WASM function scanResult = window.scanTextWithGitleaks(inputText, logLevel); } catch (error) { console.error("Error during scan:", error); resultsDiv.innerHTML = `<p class="error">Error during scan: ${error.message}</p>`; return; } const elapsed = performance.now() - startTime; let logs, findingsArray; if (scanResult && typeof scanResult === 'object' && scanResult.logs !== undefined) { logs = scanResult.logs; findingsArray = scanResult.findings; } else { findingsArray = scanResult; logs = `Scan completed in ${elapsed.toFixed(2)} ms.<br>Scanned ${scannedBytes} bytes.<br>Found ${Array.isArray(findingsArray) ? findingsArray.length : 0} secrets.`; } // Replace newline characters with <br> for proper formatting. const statsMsg = document.createElement('p'); statsMsg.className = 'scan-stats'; statsMsg.innerHTML = logs.replace(/\n/g, '<br>'); resultsDiv.innerHTML = ""; resultsDiv.appendChild(statsMsg); if (typeof findingsArray === 'string' && findingsArray.startsWith("Error:")) { resultsDiv.innerHTML += `<p class="error">${findingsArray}</p>`; return; } currentFindings = Array.isArray(findingsArray) ? findingsArray : [findingsArray]; displayFindings(currentFindings); } /** * Renders the scan findings in a table. * @param {Array} findings - List of secret findings. */ function displayFindings(findings) { const resultsDiv = document.getElementById('results'); // Preserve scan stats message while updating the results display let statsMsg = resultsDiv.querySelector('.scan-stats'); resultsDiv.innerHTML = ""; if (statsMsg) resultsDiv.appendChild(statsMsg); if (!findings || findings.length === 0) { resultsDiv.innerHTML += "<p>No secrets found.</p>"; return; } // Add toolbar with action buttons const toolbar = document.createElement('div'); toolbar.className = 'results-toolbar'; const highlightBtn = document.createElement('button'); highlightBtn.textContent = 'Highlight All'; highlightBtn.className = 'btn btn-sm'; highlightBtn.onclick = highlightAll; const clearBtn = document.createElement('button'); clearBtn.textContent = 'Clear Highlights'; clearBtn.className = 'btn btn-sm'; clearBtn.onclick = clearHighlights; const downloadBtn = document.createElement('button'); downloadBtn.textContent = 'Download Report'; downloadBtn.className = 'btn btn-sm'; downloadBtn.onclick = downloadReport; toolbar.appendChild(highlightBtn); toolbar.appendChild(clearBtn); toolbar.appendChild(downloadBtn); resultsDiv.appendChild(toolbar); // Table wrapper for scrollability const tableWrapper = document.createElement('div'); tableWrapper.className = 'table-wrapper'; // Create findings table const table = createTable(findings); tableWrapper.appendChild(table); resultsDiv.appendChild(tableWrapper); } /** * Constructs the HTML table for displaying secret findings. * @param {Array} findings - The list of findings. * @returns {HTMLElement} The constructed table element. */ function createTable(findings) { const columns = [ { key: 'ruleID', label: 'Rule' }, { key: 'entropy', label: 'Entropy' }, { key: 'secret', label: 'Secret' }, { key: 'startLine', label: 'Line' } ]; const table = document.createElement('table'); table.className = 'findings-table'; // Table header const thead = document.createElement('thead'); const headerRow = document.createElement('tr'); columns.forEach(column => { const th = document.createElement('th'); th.textContent = column.label; th.onclick = () => handleSort(column.key); if (currentSort.column === column.key) { th.className = currentSort.direction; } headerRow.appendChild(th); }); thead.appendChild(headerRow); table.appendChild(thead); // Table body const tbody = document.createElement('tbody'); const sortedFindings = currentSort.column ? sortFindings(findings, currentSort.column, currentSort.direction) : findings; sortedFindings.forEach(finding => { const row = document.createElement('tr'); columns.forEach(column => { const td = document.createElement('td'); if (column.key === 'secret') { const pre = document.createElement('pre'); pre.textContent = finding[column.key] || ''; td.appendChild(pre); } else { td.textContent = column.key === 'entropy' ? parseFloat(finding[column.key]).toFixed(2) : (finding[column.key] || ''); } row.appendChild(td); }); // Allow clicking on a row to scroll to and highlight the secret in the editor row.style.cursor = 'pointer'; row.onclick = () => { if (finding.startLine !== undefined && finding.match && finding.secret) { scrollAndHighlight(finding); } }; tbody.appendChild(row); }); table.appendChild(tbody); return table; } // ============================================= // Highlighting Functions // ============================================= /** * Scrolls the editor to the specified finding and highlights the matching secret text. * @param {Object} finding - The finding object containing match details. */ function scrollAndHighlight(finding) { const lineIndex = finding.startLine - 1; // Adjust for CodeMirror's 0-indexed lines const lineText = editor.getLine(lineIndex); let matchStart = lineText.indexOf(finding.match); if (matchStart === -1) { // Fallback: search for the secret directly matchStart = lineText.indexOf(finding.secret); if (matchStart === -1) { console.warn("Cannot find match or secret in the target line."); return; } clearHighlights(); const secretMarker = editor.markText( { line: lineIndex, ch: matchStart }, { line: lineIndex, ch: matchStart + finding.secret.length }, { className: 'highlight-red' } ); highlightMarkers.push(secretMarker); editor.scrollIntoView({ line: lineIndex, ch: matchStart }, 100); return; } const secretOffset = finding.match.indexOf(finding.secret); if (secretOffset < 0) { console.warn("Secret not found within match text."); return; } const secretStart = matchStart + secretOffset; const secretEnd = secretStart + finding.secret.length; const matchEnd = matchStart + finding.match.length; editor.scrollIntoView({ line: lineIndex, ch: matchStart }, 100); clearHighlights(); if (secretOffset > 0) { const preMarker = editor.markText( { line: lineIndex, ch: matchStart }, { line: lineIndex, ch: secretStart }, { className: 'highlight-yellow' } ); highlightMarkers.push(preMarker); } const secretMarker = editor.markText( { line: lineIndex, ch: secretStart }, { line: lineIndex, ch: secretEnd }, { className: 'highlight-red' } ); highlightMarkers.push(secretMarker); if (secretEnd < matchEnd) { const postMarker = editor.markText( { line: lineIndex, ch: secretEnd }, { line: lineIndex, ch: matchEnd }, { className: 'highlight-yellow' } ); highlightMarkers.push(postMarker); } } /** * Highlights a finding in the editor without scrolling. * @param {Object} finding - The finding object to highlight. */ function highlightFinding(finding) { const lineIndex = finding.startLine - 1; const lineText = editor.getLine(lineIndex); let matchStart = lineText.indexOf(finding.match); if (matchStart === -1) { matchStart = lineText.indexOf(finding.secret); if (matchStart === -1) { console.warn("Cannot find match or secret in the target line."); return; } // Fallback: highlight secret in red const marker = editor.markText( { line: lineIndex, ch: matchStart }, { line: lineIndex, ch: matchStart + finding.secret.length }, { className: 'highlight-red' } ); highlightMarkers.push(marker); return; } const secretOffset = finding.match.indexOf(finding.secret); if (secretOffset < 0) { console.warn("Secret not found within match text."); return; } const secretStart = matchStart + secretOffset; const secretEnd = secretStart + finding.secret.length; const matchEnd = matchStart + finding.match.length; if (secretOffset > 0) { const preMarker = editor.markText( { line: lineIndex, ch: matchStart }, { line: lineIndex, ch: secretStart }, { className: 'highlight-yellow' } ); highlightMarkers.push(preMarker); } const secretMarker = editor.markText( { line: lineIndex, ch: secretStart }, { line: lineIndex, ch: secretEnd }, { className: 'highlight-red' } ); highlightMarkers.push(secretMarker); if (secretEnd < matchEnd) { const postMarker = editor.markText( { line: lineIndex, ch: secretEnd }, { line: lineIndex, ch: matchEnd }, { className: 'highlight-yellow' } ); highlightMarkers.push(postMarker); } } /** * Clears all highlight markers from the editor. */ function clearHighlights() { highlightMarkers.forEach(marker => marker.clear()); highlightMarkers = []; } /** * Highlights all findings in the editor. */ function highlightAll() { clearHighlights(); currentFindings.forEach(finding => { if (finding.startLine !== undefined && finding.match && finding.secret) { highlightFinding(finding); } }); } /** * Sorts the findings array based on a given column and direction. * @param {Array} findings - The findings to sort. * @param {string} column - The key to sort by. * @param {string} direction - 'asc' or 'desc'. * @returns {Array} The sorted findings. */ function sortFindings(findings, column, direction) { return [...findings].sort((a, b) => { let aVal = a[column] || ''; let bVal = b[column] || ''; if (!isNaN(aVal) && !isNaN(bVal)) { aVal = Number(aVal); bVal = Number(bVal); } if (direction === 'asc') { return aVal > bVal ? 1 : -1; } else { return aVal < bVal ? 1 : -1; } }); } /** * Handles column header clicks to sort findings. * @param {string} column - The column key to sort by. */ function handleSort(column) { const direction = currentSort.column === column && currentSort.direction === 'asc' ? 'desc' : 'asc'; currentSort = { column, direction }; displayFindings(currentFindings); } /** * Generates and downloads a JSON report of the scan findings. */ function downloadReport() { if (!currentFindings || currentFindings.length === 0) { return; } const report = { timestamp: new Date().toISOString(), findings: currentFindings }; const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `gitleaks-report-${new Date().toISOString().split('T')[0]}.json`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); } // ============================================= // Rule Wizard Functions // ============================================= /** * Updates the visible fields in the Rule Wizard based on the selected rule type. * Already defined in ui.js */ /* function updateWizardFields() { ... } */ /** * Updates the display for capture type fields. */ function updateCaptureTypeDisplay() { const captureType = document.getElementById('captureType').value; if (captureType === "manual") { document.getElementById('captureManualDiv').style.display = 'block'; document.getElementById('capturePresetDiv').style.display = 'none'; } else { document.getElementById('captureManualDiv').style.display = 'none'; document.getElementById('capturePresetDiv').style.display = 'block'; const preset = document.getElementById('capturePreset').value; if (preset === "Hex8_4_4_4_12") { document.getElementById('presetRangeDiv').style.display = 'none'; } else { document.getElementById('presetRangeDiv').style.display = 'block'; } } } /** * Updates the generated rule in the Rule Wizard based on current input values. */ function updateGeneratedRule() { const ruleType = document.getElementById('ruleType').value; const id = document.getElementById('ruleId').value; const description = document.getElementById('ruleDescription').value; let regex = ""; let entropy = ""; let keyword = ""; let secretRegex = ""; if (ruleType === "semi") { const identifiers = document.getElementById('identifiers').value; entropy = document.getElementById('entropySemi').value; const keywordSemi = document.getElementById('keywordSemi').value; const captureType = document.getElementById('captureType').value; if (captureType === "manual") { secretRegex = document.getElementById('captureManual').value; } else { const preset = document.getElementById('capturePreset').value; if (preset === "Hex8_4_4_4_12") { secretRegex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"; } else { const captureMin = document.getElementById('captureMin').value; const captureMax = document.getElementById('captureMax').value; const presetMapping = { "Numeric": "0-9", "Hex": "a-f0-9", "AlphaNumeric": "a-z0-9", "AlphaNumericExtendedShort": "a-z0-9_-", "AlphaNumericExtended": "a-z0-9=_\\-", "AlphaNumericExtendedLong": "a-z0-9\\/_=_\\+\\-" }; secretRegex = "[" + presetMapping[preset] + "]{" + captureMin + "," + captureMax + "}"; } } regex = generateSemiGenericRegex(identifiers, secretRegex); keyword = keywordSemi; } else if (ruleType === "unique") { const regexInput = document.getElementById('regexUnique').value; entropy = document.getElementById('entropyUnique').value; keyword = document.getElementById('keyword').value; regex = generateUniqueRegex(regexInput); } let ruleToml = "\n[[rules]]\n"; if (id) ruleToml += `id = "${id}"\n`; if (description) ruleToml += `description = "${description}"\n`; if (regex) ruleToml += `regex = '''${regex}'''\n`; if (entropy) ruleToml += `entropy = ${entropy}\n`; if (keyword) { let keywords = keyword.split(",").map(k => k.trim()).filter(k => k); ruleToml += `keywords = [${keywords.map(k => `"${k}"`).join(", ")}]\n`; } document.getElementById('generatedRule').value = ruleToml; } /** * Generates a semi-generic regex based on identifiers and a secret regex. * @param {string} identifiersStr - Comma-separated identifiers. * @param {string} secretRegex - The regex for capturing the secret. * @returns {string} The generated regex pattern. */ function generateSemiGenericRegex(identifiersStr, secretRegex) { const caseInsensitive = "(?i)"; const identifierPrefix = "[\\w.-]{0,50}?(?:"; const identifierSuffix = ")(?:[ \\t\\w.-]{0,20})[\\s'\"]{0,3}"; const operator = "(?:=|>|:{1,3}=|\\|\\||:|=>|\\?=|,)"; const secretPrefix = "[\\x60'\"\\s=]{0,5}("; const secretSuffix = ")(?:[\\x60'\"\\s;]|\\\\[nr]|$)"; let identifiers = identifiersStr.split(",").map(s => s.trim()).filter(s => s.length > 0); if (identifiers.length === 0) { return ""; } const idPart = identifierPrefix + identifiers.join("|") + identifierSuffix; return caseInsensitive + idPart + operator + secretPrefix + secretRegex + secretSuffix; } /** * Generates a unique regex pattern based on user input. * @param {string} secretRegex - The user-provided regex. * @param {boolean} [isCaseInsensitive=true] - Whether the regex should be case-insensitive. * @returns {string} The generated regex pattern. */ function generateUniqueRegex(secretRegex, isCaseInsensitive = true) { const caseInsensitive = "(?i)"; const secretPrefixUnique = "\\b("; const secretSuffix = ")(?:[\\x60'\"\\s;]|\\\\[nr]|$)"; let regex = ""; if (isCaseInsensitive) { regex += caseInsensitive; } regex += secretPrefixUnique + secretRegex + secretSuffix; return regex; } /** * Copies the generated rule from the Rule Wizard to the clipboard. */ function copyGeneratedRule() { const ruleText = document.getElementById('generatedRule').value; if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(ruleText) .then(() => { // Show a temporary copy success indicator const copyBtn = document.getElementById('copyRuleBtn'); const originalText = copyBtn.textContent; copyBtn.textContent = 'Copied!'; setTimeout(() => { copyBtn.textContent = originalText; }, 2000); }) .catch(err => { console.error('Failed to copy: ', err); }); } else { // Fallback for browsers without clipboard API const textarea = document.getElementById('generatedRule'); const currentSelectionStart = textarea.selectionStart; const currentSelectionEnd = textarea.selectionEnd; textarea.select(); document.execCommand("copy"); textarea.setSelectionRange(currentSelectionStart, currentSelectionEnd); // Show copy feedback const copyBtn = document.getElementById('copyRuleBtn'); const originalText = copyBtn.textContent; copyBtn.textContent = 'Copied!'; setTimeout(() => { copyBtn.textContent = originalText; }, 2000); } } // Initialize Gitleaks on page load console.log("Starting initialization..."); loadGitleaks().then(() => { // Check if we need to handle a pending shared state that hasn't been processed yet if (window.pendingSharedState) { console.log("Processing pending shared state after WASM load"); setTimeout(() => { window.loadSharedState(window.pendingSharedState); window.pendingSharedState = null; // Hide loading overlay after state is fully loaded if (typeof hideLoadingOverlay === 'function') { hideLoadingOverlay(); } }, 100); // Small delay to ensure everything is ready } else { // No pending state, hide loading overlay if it exists if (typeof hideLoadingOverlay === 'function') { hideLoadingOverlay(); } } }).catch(err => { console.error("Failed to load Gitleaks WASM:", err); document.getElementById("results").innerHTML = `<p class="error">Failed to load Gitleaks WASM: ${err}</p>`; // Hide loading overlay on error if (typeof hideLoadingOverlay === 'function') { hideLoadingOverlay(); } });
zricethezav/wasmleaks
3
gitleaks wasm browser
JavaScript
zricethezav
Zachary Rice
gitleaks trufflesecurity
index.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>WASMLeaks | WASM Gitleaks Playground</title> <meta name="description" content="WASMLeaks is a free, browser-based tool powered by Gitleaks. 100% client-side with no server uploads." /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> <!-- CodeMirror CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/codemirror.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/theme/idea.min.css" /> <!-- Custom Styles --> <link rel="stylesheet" href="styles.css" /> <script> // Immediately check for dark mode preference before page renders (function() { const savedTheme = localStorage.getItem('theme'); if (savedTheme === 'dark') { document.documentElement.classList.add('dark-mode-preload'); } })(); </script> </head> <body> <div class="app-container"> <!-- Header --> <header class="app-header"> <div class="logo"> <a href="index.html" class="logo-link"> <h1>WASMLeaks</h1> </a> </div> <div class="header-actions"> <!-- Add the new share button here, right before the sponsor button --> <button id="share-btn" class="btn btn-primary"> <span class="icon"></span> <span>Share</span> </button> <a class="btn btn-primary" href="https://github.com/sponsors/zricethezav" target="_blank"> <span class="icon">❤️</span> <span>Sponsor</span> </a> <button id="toggle-theme-btn" class="btn btn-icon" title="Toggle Theme">💡</button> </div> </header> <!-- Main Content --> <main class="app-main"> <!-- Tabs for main content --> <div class="tabs-container"> <div class="tabs"> <button class="tab-btn active" data-tab="scan">Scan</button> <button class="tab-btn" data-tab="config">Configuration</button> <button class="tab-btn" data-tab="wizard">Rule Wizard</button> </div> <!-- Metadata bar (always visible) --> <div class="metadata-bar"> <div class="entropy-calc"> <input type="text" id="entropyInput" placeholder="Calculate entropy..." /> <span id="entropyOutput">Entropy: 0.00</span> <small class="entropy-warning">Do not paste real secrets!</small> </div> </div> </div> <!-- Tab Content --> <div class="tab-content-container"> <!-- Scan Tab --> <div class="tab-content active" id="scan-tab"> <div class="resizable-container"> <!-- Editor Section (Resizable) --> <div class="editor-section"> <div class="editor-container"> <textarea id="inputText" placeholder="Paste your code here to scan for secrets..."></textarea> </div> <div class="action-bar"> <select id="logLevelSelect" title="Log Level"> <option value="Trace">Trace</option> <option value="Debug">Debug</option> <option value="Info" selected>Info</option> <option value="Warn">Warn</option> <option value="Error">Error</option> </select> <button id="scanBtn" class="btn btn-primary">Scan Content for Secrets</button> </div> </div> <!-- Resize Handle --> <div class="resize-handle" id="resizeHandle"></div> <!-- Results Section --> <div class="results-section"> <div id="results" class="results-container"></div> </div> </div> </div> <!-- Config Tab --> <div class="tab-content" id="config-tab"> <div class="editor-toolbar"> <span>Gitleaks Configuration (TOML)</span> <button id="loadDefaultConfigBtn" class="btn btn-sm">Load Default Config</button> </div> <div class="editor-container"> <textarea id="configText"></textarea> </div> </div> <!-- Rule Wizard Tab --> <div class="tab-content" id="wizard-tab"> <div class="wizard-form"> <div class="form-group"> <label for="ruleType">Rule Type</label> <select id="ruleType" name="ruleType" onchange="updateWizardFields()"> <option value="semi">Semi Generic</option> <option value="unique">Unique</option> </select> </div> <div class="form-group"> <label for="ruleId">ID</label> <input type="text" id="ruleId" name="ruleId" oninput="updateGeneratedRule()" placeholder="Enter rule ID" /> </div> <div class="form-group"> <label for="ruleDescription">Description</label> <input type="text" id="ruleDescription" name="ruleDescription" oninput="updateGeneratedRule()" placeholder="Enter rule description" /> </div> <!-- Fields for Semi Generic --> <div id="semiFields"> <div class="form-group"> <label for="identifiers">Identifiers (comma separated)</label> <input type="text" id="identifiers" name="identifiers" oninput="updateGeneratedRule()" placeholder="e.g. API_KEY, SECRET" /> </div> <div class="form-group"> <label for="entropySemi">Entropy</label> <input type="number" id="entropySemi" name="entropySemi" oninput="updateGeneratedRule()" placeholder="Enter entropy threshold" /> </div> <div class="form-group"> <label for="keywordSemi">Keywords (comma separated)</label> <input type="text" id="keywordSemi" name="keywordSemi" oninput="updateGeneratedRule()" placeholder="Enter keywords" /> </div> <div class="form-group"> <label for="captureType">Secret Capture Group Content</label> <select id="captureType" name="captureType" onchange="updateCaptureTypeDisplay(); updateGeneratedRule();"> <option value="manual">Manual</option> <option value="preset">Preset</option> </select> </div> <div id="captureManualDiv" class="form-group"> <label for="captureManual">Manual Regex</label> <input type="text" id="captureManual" name="captureManual" oninput="updateGeneratedRule()" placeholder="e.g. .+" /> </div> <div id="capturePresetDiv" class="form-group" style="display:none;"> <label for="capturePreset">Preset</label> <select id="capturePreset" name="capturePreset" onchange="updateCaptureTypeDisplay(); updateGeneratedRule()"> <option value="Numeric">Numeric</option> <option value="Hex">Hex</option> <option value="AlphaNumeric">AlphaNumeric</option> <option value="AlphaNumericExtendedShort">AlphaNumericExtendedShort</option> <option value="AlphaNumericExtended">AlphaNumericExtended</option> <option value="AlphaNumericExtendedLong">AlphaNumericExtendedLong</option> <option value="Hex8_4_4_4_12">Hex8_4_4_4_12</option> </select> <div id="presetRangeDiv" class="form-group"> <label for="captureMin">Min</label> <input type="number" id="captureMin" name="captureMin" oninput="updateGeneratedRule()" placeholder="min" /> <label for="captureMax">Max</label> <input type="number" id="captureMax" name="captureMax" oninput="updateGeneratedRule()" placeholder="max" /> </div> </div> </div> <!-- Fields for Unique --> <div id="uniqueFields" style="display:none;"> <div class="form-group"> <label for="regexUnique">Regex</label> <input type="text" id="regexUnique" name="regexUnique" oninput="updateGeneratedRule()" placeholder="Enter regex pattern" /> </div> <div class="form-group"> <label for="entropyUnique">Entropy</label> <input type="number" id="entropyUnique" name="entropyUnique" oninput="updateGeneratedRule()" placeholder="Enter entropy threshold" /> </div> <div class="form-group"> <label for="keyword">Keywords (comma separated)</label> <input type="text" id="keyword" name="keyword" oninput="updateGeneratedRule()" placeholder="Enter keywords" /> </div> </div> <div class="generated-rule-container form-group"> <label for="generatedRule">Generated Rule</label> <div class="rule-output-container"> <textarea id="generatedRule" readonly></textarea> <button id="copyRuleBtn" class="btn btn-sm copy-btn" onclick="copyGeneratedRule()">Copy</button> </div> </div> </div> </div> </div> </main> <!-- Footer --> <footer class="app-footer"> <p>Powered by <a href="https://github.com/zricethezav/gitleaks/releases" target="_blank">Gitleaks v8.24.0</a></p> </footer> </div> <!-- CodeMirror JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/codemirror.min.js"></script> <!-- CodeMirror TOML Mode --> <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/toml/toml.min.js"></script> <!-- CodeMirror JavaScript Mode (for syntax highlighting) --> <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/javascript/javascript.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/pako/2.1.0/pako.min.js"></script> <!-- Go WASM Runtime --> <script src="wasm_exec.js"></script> <!-- Main JS --> <script src="gitleaks.js"></script> <!-- UI JS --> <script src="ui.js"></script> </body> </html>
zricethezav/wasmleaks
3
gitleaks wasm browser
JavaScript
zricethezav
Zachary Rice
gitleaks trufflesecurity
main.go
Go
package main import ( "bytes" "fmt" "syscall/js" "time" "github.com/rs/zerolog" "github.com/spf13/viper" "github.com/zricethezav/gitleaks/v8/config" "github.com/zricethezav/gitleaks/v8/detect" "github.com/zricethezav/gitleaks/v8/logging" "github.com/zricethezav/gitleaks/v8/report" ) /* Gitleaks WASM Entry Point This Go code exposes several functions to JavaScript via the WebAssembly interface: - getDefaultConfig: returns the default TOML configuration. - getGitleaksVersion: returns the current version string. - setUserConfig: accepts user-supplied config, validates it, and updates the detector. - scanText: performs the secret scan on input text. */ // Global variables to hold our detector and configuration. var ( globalDetector *detect.Detector globalConfig = config.DefaultConfig // current TOML config as a string ) // findingToJSObject converts a Finding into a JavaScript-friendly object. func findingToJSObject(finding report.Finding) map[string]interface{} { tags := make([]interface{}, len(finding.Tags)) for i, tag := range finding.Tags { tags[i] = tag } return map[string]interface{}{ "ruleID": finding.RuleID, "match": finding.Match, "startLine": finding.StartLine + 1, // Convert to 1-indexed for UI "endLine": finding.EndLine, "startColumn": finding.StartColumn, "endColumn": finding.EndColumn, "secret": finding.Secret, "file": finding.File, "commit": finding.Commit, "author": finding.Author, "description": finding.Description, "tags": tags, "entropy": finding.Entropy, } } // createJSObject helps transform a Go map into a JavaScript object. func createJSObject(data map[string]interface{}) js.Value { obj := js.Global().Get("Object").New() for key, value := range data { switch v := value.(type) { case []interface{}: arr := js.Global().Get("Array").New(len(v)) for i, item := range v { arr.SetIndex(i, js.ValueOf(item)) } obj.Set(key, arr) default: obj.Set(key, js.ValueOf(v)) } } return obj } // getDefaultConfig returns the default configuration for display in the UI. func getDefaultConfig(this js.Value, args []js.Value) interface{} { return config.DefaultConfig } // getGitleaksVersion exposes the Gitleaks version to the JS environment. func getGitleaksVersion(this js.Value, args []js.Value) interface{} { // Replace with dynamic version if available. return "Gitleaks v8.24.0" } // setUserConfig validates the provided TOML config and updates the global detector. func setUserConfig(this js.Value, args []js.Value) (result interface{}) { defer func() { if r := recover(); r != nil { result = fmt.Sprintf("Error: %v", r) } }() if len(args) < 1 { return "Error: No config provided" } userConfig := args[0].String() err := updateGlobalDetector(userConfig) if err != nil { return fmt.Sprintf("Error: %v", err) } globalConfig = userConfig return "OK" } // scanText scans the input text for secrets using the global detector. // It now accepts an optional second argument indicating the desired log level. func scanText(this js.Value, args []js.Value) interface{} { if len(args) < 1 { return "Error: No input text provided" } inputText := args[0].String() // Default log level is Trace logLevelStr := "Trace" if len(args) >= 2 { logLevelStr = args[1].String() } var level zerolog.Level switch logLevelStr { case "Trace": level = zerolog.TraceLevel case "Debug": level = zerolog.DebugLevel case "Info": level = zerolog.InfoLevel case "Warn": level = zerolog.WarnLevel case "Error": level = zerolog.ErrorLevel default: level = zerolog.TraceLevel } if globalDetector == nil { // If the detector hasn't been initialized, try to update it using the current config. err := updateGlobalDetector(globalConfig) if err != nil { return fmt.Sprintf("Error: Detector not initialized - %v", err) } } // Create a buffer to capture logs from the Gitleaks detector. var detectorLogBuffer bytes.Buffer // Override the logging package's logger to write to our buffer. // Disable ANSI colors and set the log level based on the user selection. logging.Logger = zerolog.New(zerolog.ConsoleWriter{ Out: &detectorLogBuffer, NoColor: true, }).Level(level) // }).Level(level).With().Timestamp().Logger() start := time.Now() findings := globalDetector.DetectString(inputText) duration := time.Since(start) logging.Logger.Info().Msgf("Scan completed in %v", duration) if len(findings) == 0 { logging.Logger.Info().Msg("No secrets found") } else { logging.Logger.Info().Msgf("Found %d secrets ⬇", len(findings)) } // Capture the logs from the detector. logs := detectorLogBuffer.String() jsFindings := js.Global().Get("Array").New(len(findings)) for i, finding := range findings { jsObject := createJSObject(findingToJSObject(finding)) jsFindings.SetIndex(i, jsObject) } // Return an object containing both the logs and the findings. result := js.Global().Get("Object").New() result.Set("logs", logs) result.Set("findings", jsFindings) return result } // updateGlobalDetector parses the config string, creates a new detector, and sets it globally. func updateGlobalDetector(cfgString string) error { viper.SetConfigType("toml") if err := viper.ReadConfig(bytes.NewBufferString(cfgString)); err != nil { return fmt.Errorf("failed to parse config: %w", err) } var vc config.ViperConfig if err := viper.Unmarshal(&vc); err != nil { return fmt.Errorf("failed to unmarshal config: %w", err) } translatedCfg, err := vc.Translate() if err != nil { return fmt.Errorf("failed to translate config: %w", err) } // Create a new detector using the supplied configuration. detector := detect.NewDetector(translatedCfg) globalDetector = detector return nil } func main() { fmt.Println("Go WASM starting") // Expose functions to the JS environment. js.Global().Set("getDefaultConfig", js.FuncOf(getDefaultConfig)) js.Global().Set("getGitleaksVersion", js.FuncOf(getGitleaksVersion)) js.Global().Set("setUserConfig", js.FuncOf(setUserConfig)) js.Global().Set("scanTextWithGitleaks", js.FuncOf(scanText)) fmt.Println("Functions registered, entering main loop") <-make(chan struct{}) }
zricethezav/wasmleaks
3
gitleaks wasm browser
JavaScript
zricethezav
Zachary Rice
gitleaks trufflesecurity
styles.css
CSS
/* Base styles and reset */ :root { --primary-color: #2563eb; --primary-dark: #1d4ed8; --primary-light: #3b82f6; --secondary-color: #f3f4f6; --surface-color: #ffffff; --border-color: #e5e7eb; --text-color: #374151; --text-light: #6b7280; --text-inverse: #ffffff; --error-color: #ef4444; --warning-color: #f59e0b; --success-color: #10b981; --highlight-color: rgba(255, 255, 0, 0.2); --highlight-secret: rgba(239, 68, 68, 0.2); --shadow: 0 1px 3px rgba(0, 0, 0, 0.1); --radius: 0; /* Changed from 6px to 0 for angular look */ --header-height: 60px; --metadata-height: 50px; --footer-height: 40px; --resize-handle-height: 8px; --min-editor-height: 100px; --default-editor-height: 300px; --font-mono: 'Fira Code', 'IBM Plex Mono', 'Source Code Pro', monospace; --font-main: 'IBM Plex Sans', 'Roboto Mono', monospace; } /* Dark mode variables */ body.dark-mode { --primary-color: #1e40af; --primary-dark: #1e3a8a; --primary-light: #3b82f6; --secondary-color: #1f2937; --surface-color: #111827; --border-color: #374151; --text-color: #f3f4f6; --text-light: #9ca3af; --text-inverse: #111827; --highlight-color: rgba(255, 255, 0, 0.3); /* Increased brightness for dark mode */ --highlight-secret: rgba(255, 99, 99, 0.3); /* Brighter and more red for dark mode */ } * { margin: 0; padding: 0; box-sizing: border-box; } html, body { height: 100%; font-family: var(--font-main); /* Updated from default system fonts */ font-size: 16px; line-height: 1.5; color: var(--text-color); background-color: var(--surface-color); } /* App Container */ .app-container { display: flex; flex-direction: column; height: 100%; max-width: 100%; overflow: hidden; } /* Header */ .app-header { height: var(--header-height); background-color: var(--primary-color); color: var(--text-inverse); display: flex; align-items: center; justify-content: space-between; padding: 0 1.5rem; flex-shrink: 0; box-shadow: var(--shadow); z-index: 10; } /* Dark mode header */ body.dark-mode .app-header { background-color: #0f172a; /* Very dark blue */ color: #fff; } /* Logo link styling */ .logo-link { text-decoration: none; color: var(--text-inverse); } .logo-link:hover { opacity: 0.9; } .logo h1 { font-size: 1.5rem; font-weight: 600; } .exponent { font-size: 0.6em; } .header-actions { display: flex; align-items: center; gap: 0.5rem; } /* Main area */ .app-main { flex: 1; display: flex; flex-direction: column; overflow: hidden; position: relative; } /* Tabs */ .tabs-container { border-bottom: 1px solid var(--border-color); background-color: var(--surface-color); flex-shrink: 0; } .tabs { display: flex; padding: 0 1rem; } .tab-btn { padding: 0.75rem 1.25rem; background: none; border: none; color: var(--text-light); font-weight: 500; cursor: pointer; border-bottom: 2px solid transparent; transition: all 0.2s ease; } .tab-btn:hover { color: var(--primary-color); } .tab-btn.active { color: var(--primary-color); border-bottom-color: var(--primary-color); } /* Dark mode tabs */ body.dark-mode .tab-btn.active { color: #60a5fa; /* Light blue for better visibility */ border-bottom-color: #60a5fa; } body.dark-mode .tab-btn:hover { color: #60a5fa; } /* Metadata bar */ .metadata-bar { display: flex; align-items: center; padding: 0.5rem 1rem; gap: 1rem; height: var(--metadata-height); border-bottom: 1px solid var(--border-color); } /* Mobile metadata optimizations */ @media (max-width: 768px) { .metadata-bar { padding: 0.3rem 0.5rem; height: auto; min-height: 30px; max-height: 40px; gap: 0.25rem; } .app-main { height: calc(100vh - var(--header-height) - 40px - var(--footer-height)); } } .version-label { display: inline-block; background-color: var(--primary-color); color: var(--text-inverse); font-size: 0.75rem; padding: 0.2rem 0.4rem; border-radius: 0; /* Changed from 4px */ text-decoration: none; font-weight: 500; } .entropy-calc { display: flex; align-items: center; gap: 0.5rem; flex: 1; } .entropy-calc input { flex: 1; max-width: 350px; padding: 0.375rem 0.75rem; background-color: var(--surface-color); border: 1px solid var(--border-color); border-radius: var(--radius); color: var(--text-color); font-size: 0.875rem; font-family: var(--font-mono); /* Added for input fields */ } #entropyOutput { font-size: 0.875rem; font-weight: 500; white-space: nowrap; font-family: var(--font-mono); /* Added for monospaced output */ } .entropy-warning { color: var(--error-color); font-size: 0.75rem; } /* Tab content */ .tab-content-container { flex: 1; overflow: hidden; position: relative; } .tab-content { display: none; height: 100%; overflow: auto; padding: 1rem; } .tab-content.active { display: flex; flex-direction: column; } /* Editor container */ .editor-container { border: 1px solid var(--border-color); border-radius: var(--radius); overflow: hidden; flex: 1; display: flex; flex-direction: column; } /* Editor toolbar */ .editor-toolbar { display: flex; align-items: center; justify-content: space-between; padding: 0.5rem 0.75rem; background-color: var(--secondary-color); border-bottom: 1px solid var(--border-color); font-size: 0.875rem; } /* Action bar */ .action-bar { display: flex; align-items: center; padding: 0.75rem 0; gap: 0.5rem; } /* Log level select dropdown */ #logLevelSelect { padding: 0.5rem 0.75rem; border: 1px solid var(--border-color); border-radius: var(--radius); font-size: 0.875rem; background-color: var(--surface-color); color: var(--text-color); min-width: 100px; font-family: var(--font-main); /* Added for consistent font */ } body.dark-mode #logLevelSelect { background-color: var(--secondary-color); color: var(--text-color); border-color: var(--border-color); } /* Mobile specific log level dropdown */ @media (max-width: 768px) { #logLevelSelect { padding: 0.3rem 0.5rem; font-size: 0.75rem; min-width: 80px; } } /* Results container */ .results-container { margin-top: 1rem; overflow: auto; flex: 1; min-height: 100px; } /* Resizable sections */ .resizable-container { display: flex; flex-direction: column; flex: 1; overflow: hidden; } .editor-section { display: flex; flex-direction: column; height: var(--default-editor-height); min-height: var(--min-editor-height); overflow: hidden; } .resize-handle { height: var(--resize-handle-height); background-color: var(--secondary-color); cursor: ns-resize; position: relative; border-top: 1px solid var(--border-color); border-bottom: 1px solid var(--border-color); display: flex; justify-content: center; align-items: center; } .resize-handle::before { content: ""; width: 30px; height: 2px; background-color: var(--border-color); border-radius: 0; /* Changed from 1px */ } .resize-handle:hover { background-color: var(--primary-light); } .resize-handle:hover::before { background-color: var(--text-inverse); } .results-section { flex: 1; overflow: hidden; display: flex; flex-direction: column; } /* Rule wizard */ .wizard-form { overflow: auto; max-height: 100%; padding: 1rem; } /* Form styling */ .form-group { margin-bottom: 1rem; } .form-group label { display: block; font-size: 0.875rem; font-weight: 500; margin-bottom: 0.25rem; } .form-group input, .form-group select, .form-group textarea { width: 100%; padding: 0.5rem 0.75rem; border: 1px solid var(--border-color); border-radius: var(--radius); font-size: 0.875rem; background-color: var(--surface-color); color: var(--text-color); font-family: var(--font-main); /* Added for consistent font */ } .form-group textarea { font-family: var(--font-mono); /* Use monospace for textareas */ } .form-group input:focus, .form-group select:focus, .form-group textarea:focus { outline: none; border-color: var(--primary-color); } /* Dark mode form overrides */ body.dark-mode .form-group input, body.dark-mode .form-group select, body.dark-mode .form-group textarea { background-color: var(--secondary-color); color: var(--text-color); border-color: var(--border-color); } /* Generated rule output */ .rule-output-container { position: relative; } .rule-output-container textarea { width: 100%; height: 150px; resize: vertical; padding: 0.5rem; font-family: var(--font-mono); /* Changed to specified mono font */ font-size: 0.875rem; } .copy-btn { position: absolute; top: 0.5rem; right: 0.5rem; background-color: var(--secondary-color); border: none; padding: 0.25rem 0.5rem; border-radius: var(--radius); cursor: pointer; font-size: 0.75rem; } /* Footer */ .app-footer { height: var(--footer-height); padding: 0 1.5rem; display: flex; align-items: center; justify-content: center; /* border-top: 1px solid var(--border-color); */ font-size: 0.75rem; color: var(--text-light); flex-shrink: 0; } .app-footer a { color: var(--primary-color); text-decoration: none; } .app-footer a:hover { text-decoration: underline; } /* Buttons */ .btn { display: inline-flex; align-items: center; justify-content: center; padding: 0.5rem 1rem; border-radius: var(--radius); font-size: 0.875rem; font-weight: 500; cursor: pointer; transition: background-color 0.2s, color 0.2s; border: none; font-family: var(--font-main); /* Added for consistent font */ } .btn-primary { text-decoration: none; background-color: var(--primary-color); color: var(--text-inverse); } .btn-primary:hover { background-color: var(--primary-dark); } .btn-sm { padding: 0.25rem 0.5rem; font-size: 0.75rem; } .btn-icon { padding: 0.375rem; background: none; color: var(--text-inverse); } /* Dark mode button overrides */ body.dark-mode .btn { border: 1px solid var(--border-color); } body.dark-mode .btn-primary { background-color: #0f172a; /* Very dark blue to match header */ color: #fff; border-color: #1e293b; /* Slightly lighter border */ } body.dark-mode .btn-primary:hover { background-color: #1e293b; /* Slightly lighter on hover */ } body.dark-mode .btn-sm { background-color: var(--secondary-color); color: var(--text-color); } body.dark-mode .btn-sm:hover { background-color: var(--primary-color); color: var(--text-inverse); } .icon { margin-right: 0.25rem; } /* Dropdown */ .dropdown { position: relative; } .dropdown-toggle::after { content: '▼'; font-size: 0.5rem; margin-left: 0.25rem; display: inline-block; vertical-align: middle; } .dropdown-menu { display: none; position: absolute; top: 100%; right: 0; min-width: 10rem; padding: 0.5rem 0; margin-top: 0.25rem; background-color: var(--surface-color); border: 1px solid var(--border-color); border-radius: var(--radius); box-shadow: var(--shadow); z-index: 100; } .dropdown:hover .dropdown-menu { display: block; } .dropdown-menu a { display: block; padding: 0.5rem 1rem; color: var(--text-color); text-decoration: none; font-size: 0.875rem; } .dropdown-menu a:hover { background-color: var(--secondary-color); } /* Dark mode header buttons and elements */ body.dark-mode .header-button, body.dark-mode .header-actions .btn { background-color: #1e293b; /* Slightly lighter than the header */ } body.dark-mode .header-button:hover, body.dark-mode .header-actions .btn:hover { background-color: #334155; /* Even lighter on hover */ } /* CodeMirror customization */ .CodeMirror { height: 100% !important; font-family: var(--font-mono) !important; /* Changed to specified mono font */ font-size: 14px; line-height: 1.6; } /* Dark mode CodeMirror adjustments */ body.dark-mode .CodeMirror { background-color: var(--surface-color); color: #d4d4d4; } body.dark-mode .CodeMirror-gutters { background-color: var(--secondary-color); border-right: 1px solid var(--border-color); } body.dark-mode .CodeMirror-linenumber { color: #858585; } /* CodeMirror Syntax Highlighting for Dark Mode */ body.dark-mode .cm-s-idea span.cm-comment { color: #6A9955; } body.dark-mode .cm-s-idea span.cm-string, body.dark-mode .cm-s-idea span.cm-string-2 { color: #ce9178; } body.dark-mode .cm-s-idea span.cm-number { color: #b5cea8; } body.dark-mode .cm-s-idea span.cm-property { color: #9cdcfe; } body.dark-mode .cm-s-idea span.cm-atom { color: #569cd6; } body.dark-mode .cm-s-idea span.cm-keyword { color: #569cd6; } body.dark-mode .cm-s-idea span.cm-operator { color: #d4d4d4; } body.dark-mode .cm-s-idea span.cm-variable { color: #9cdcfe; } body.dark-mode .cm-s-idea span.cm-variable-2 { color: #9cdcfe; } body.dark-mode .cm-s-idea span.cm-def { color: #dcdcaa; } body.dark-mode .cm-s-idea span.cm-tag { color: #569cd6; } body.dark-mode .cm-s-idea span.cm-bracket { color: #d4d4d4; } body.dark-mode .cm-s-idea span.cm-link { color: #569cd6; } /* Findings table */ .findings-table { width: 100%; border-collapse: collapse; font-size: 0.875rem; font-family: var(--font-main); /* Added for consistent font */ } .findings-table th { background-color: var(--secondary-color); padding: 0.75rem; text-align: left; font-weight: 500; position: sticky; top: 0; z-index: 1; } .findings-table th.asc::after { content: ' ↑'; } .findings-table th.desc::after { content: ' ↓'; } .findings-table td { padding: 0.75rem; border-top: 1px solid var(--border-color); vertical-align: top; } .findings-table tr:hover td { background-color: var(--secondary-color); } .findings-table pre { font-family: var(--font-mono); /* Changed to specified mono font */ font-size: 0.875rem; background-color: var(--secondary-color); padding: 0.5rem; border-radius: var(--radius); overflow-x: auto; white-space: pre-wrap; word-break: break-all; } /* Results toolbar */ .results-toolbar { display: flex; align-items: center; gap: 0.5rem; padding: 0.5rem 0; margin-bottom: 0.5rem; } /* Highlight colors for CodeMirror */ .CodeMirror .highlight-yellow { background-color: var(--highlight-color) !important; } .CodeMirror .highlight-red { background-color: var(--highlight-secret) !important; } /* Enhanced dark mode highlights for CodeMirror */ body.dark-mode .CodeMirror .highlight-yellow { background-color: rgba(255, 255, 0, 0.3) !important; color: #ffffff !important; text-shadow: 0 0 2px rgba(0, 0, 0, 0.7); } body.dark-mode .CodeMirror .highlight-red { background-color: rgba(255, 99, 99, 0.3) !important; color: #ffffff !important; text-shadow: 0 0 2px rgba(0, 0, 0, 0.7); } /* Error and status messages */ .error { color: var(--error-color); padding: 1rem; background-color: rgba(239, 68, 68, 0.1); border-radius: var(--radius); margin: 1rem 0; } .scan-stats { font-size: 0.875rem; margin: 1rem 0; line-height: 1.5; } /* Loading spinner */ .spinner { display: inline-block; width: 1.5rem; height: 1.5rem; border: 3px solid rgba(0, 0, 0, 0.1); border-radius: 50%; /* Keeping this circular as it's a spinner */ border-top-color: var(--primary-color); animation: spin 1s linear infinite; } @keyframes spin { to { transform: rotate(360deg); } } /* Table wrapper */ .table-wrapper { overflow-x: auto; border: 1px solid var(--border-color); border-radius: var(--radius); } /* Mobile responsive styles */ @media (max-width: 768px) { .app-header { justify-content: center; flex-direction: column; height: auto; padding: 0.5rem; gap: 0.5rem; } .header-actions { width: 100%; justify-content: center; } .logo h1 { font-size: 1.0rem; font-weight: 600; } .tabs { overflow-x: auto; padding: 0; } .tab-btn { padding: 0.5rem 0.75rem; white-space: nowrap; } .metadata-bar { flex-direction: column; height: auto; align-items: flex-start; } .entropy-calc { width: 100%; } .action-bar { flex-direction: column; align-items: stretch; } #logLevelSelect { width: 100%; } /* Ensure the scan tab content shows the editor by default */ .app-main { display: flex; flex-direction: column; height: calc(100vh - var(--header-height) - var(--footer-height)); overflow: hidden; } .tab-content-container { display: flex; flex-direction: column; flex: 1; overflow: hidden; } .tab-content { display: flex; flex-direction: column; height: 100%; } .editor-container { min-height: 40px; /* Ensure minimum height for editor on mobile */ max-height: 300px; /* Prevent editor from taking too much space */ overflow: auto; } .results-container { overflow: auto; flex: 1; } /* Fix table overflow on mobile */ .table-wrapper { overflow-x: auto; width: 100%; } /* Adjust button sizes on mobile for better touch targets */ .btn { padding: 0.75rem 1rem; font-size: 1rem; } .btn-primary { font-size: 0.75rem; padding: 0.5rem 0.5rem; } .btn-icon { font-size: 0.75rem; padding: 0.5rem 0.5rem; } .entropy-warning { display: none; } .entropy-calc { display: flex; align-items: center; gap: 0.5rem; font-size: 0.75rem; flex: 1; } .entropy-calc input { flex: 1; /* max-width: 350px; */ padding: 0.375rem 0.75rem; background-color: var(--surface-color); border: 1px solid var(--border-color); border-radius: var(--radius); color: var(--text-color); font-size: 0.75rem; } #entropyOutput { font-size: 0.75rem; font-weight: 500; white-space: nowrap; } .btn-sm { padding: 0.5rem 0.75rem; font-size: 0.75rem; } /* Adjust resize handle for mobile */ .resize-handle { height: 16px; /* Larger touch target for mobile */ } } /* Small screen adjustments */ @media (max-width: 480px) { .header-actions { flex-wrap: wrap; gap: 0.5rem; } .logo h1 { font-size: 0.75rem; font-weight: 600; } .tabs { justify-content: space-between; } .tab-btn { flex: 1; text-align: center; font-size: 0.8rem; padding: 0.4rem 0.5rem; } /* Ensure CodeMirror editors display properly on mobile */ .CodeMirror { height: 200px; font-size: 11px; /* Even smaller font on mobile */ } .CodeMirror-linenumber { font-size: 9px; /* Smaller line numbers */ padding: 0 3px 0 3px; /* Tighter padding */ } /* Adjust findings table for mobile */ .findings-table th, .findings-table td { padding: 0.5rem; font-size: 0.75rem; } .findings-table pre { font-size: 0.75rem; max-width: 150px; overflow-x: auto; } /* Make sure we can see the code AND the results */ .tab-content#scan-tab { display: flex; flex-direction: column; height: auto; min-height: 100%; } /* Make action buttons more accessible */ .results-toolbar .btn { padding: 0.4rem; font-size: 0.75rem; margin-bottom: 0.5rem; } /* Scan button smaller on mobile */ #scanBtn { font-size: 0.85rem; padding: 0.4rem 0.75rem; } /* Compact metadata bar */ .metadata-bar { padding: 0.3rem 0.5rem; } } /* About page specific styles - add these to your styles.css file */ .about-content { flex: 1; overflow-y: auto; padding: 2rem 1rem; background-color: var(--surface-color); } .about-container { max-width: 800px; margin: 0 auto; background-color: var(--surface-color); border-radius: var(--radius); box-shadow: var(--shadow); padding: 2rem; } .about-container h1 { color: var(--primary-color); margin-bottom: 1.5rem; font-size: 1.8rem; text-align: center; } .about-section { margin-bottom: 2rem; } .about-section h2 { color: var(--text-color); font-size: 1.4rem; margin-bottom: 1rem; padding-bottom: 0.5rem; border-bottom: 1px solid var(--border-color); } .about-section p { margin-bottom: 1rem; line-height: 1.6; } .about-section ul, .about-section ol { margin-bottom: 1rem; padding-left: 1.5rem; } .about-section li { margin-bottom: 0.5rem; line-height: 1.6; } .about-section a { color: var(--primary-color); text-decoration: none; } .about-section a:hover { text-decoration: underline; } /* Dark mode specific styles */ body.dark-mode .logo-link { color: white; } body.dark-mode .about-container { background-color: var(--surface-color); } body.dark-mode .about-section h2 { border-bottom-color: var(--border-color); } /* Mobile responsive styles */ @media (max-width: 768px) { .about-content { padding: 1rem 0.5rem; } .about-container { padding: 1.5rem 1rem; } .about-container h1 { font-size: 1.5rem; } .about-section h2 { font-size: 1.2rem; } } /* Share button styles */ .share-btn { display: inline-flex; align-items: center; justify-content: center; gap: 0.25rem; cursor: pointer; } .share-btn .icon { font-size: 1.2rem; } /* Modal dialog for share link */ .share-modal { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; opacity: 1; transition: opacity 0.3s ease; } .share-modal-content { background-color: var(--surface-color); border-radius: var(--radius); padding: 1.5rem; width: 90%; max-width: 500px; box-shadow: var(--shadow); } .share-modal-content h3 { margin-bottom: 0.75rem; color: var(--text-color); } .share-modal input { width: 100%; padding: 0.75rem; margin: 1rem 0; font-family: var(--font-mono); border: 1px solid var(--border-color); border-radius: var(--radius); font-size: 0.875rem; background-color: var(--surface-color); color: var(--text-color); } .modal-actions { display: flex; justify-content: flex-end; margin-top: 1rem; } /* Notification system */ .notification { position: fixed; bottom: 1rem; right: 1rem; background-color: var(--primary-color); color: var(--text-inverse); padding: 0.75rem 1rem; border-radius: var(--radius); box-shadow: var(--shadow); z-index: 1000; opacity: 1; transition: opacity 0.3s ease; max-width: 300px; display: flex; align-items: center; gap: 0.5rem; } .notification-error { background-color: var(--error-color); } .notification-processing { background-color: var(--secondary-color); color: var(--text-color); border: 1px solid var(--border-color); } .notification-spinner { width: 16px; height: 16px; border: 2px solid var(--primary-color); border-top-color: transparent; border-radius: 50%; animation: spin 1s linear infinite; } body.dark-mode .notification-processing { background-color: var(--secondary-color); color: var(--text-color); border-color: var(--border-color); } body.dark-mode .notification-spinner { border-color: var(--primary-light); border-top-color: transparent; } /* Dark mode styles for share features */ body.dark-mode .share-modal-content { background-color: var(--surface-color); border: 1px solid var(--border-color); } body.dark-mode .share-modal input { background-color: var(--secondary-color); color: var(--text-color); border-color: var(--border-color); } /* Mobile responsive styles for share features */ @media (max-width: 768px) { .notification { max-width: 90%; font-size: 0.875rem; bottom: 0.5rem; right: 0.5rem; } .share-modal-content { width: 95%; padding: 1rem; } .share-modal-content h3 { font-size: 1.1rem; } .share-modal input { padding: 0.5rem; font-size: 0.75rem; } } /* Loading overlay for initial page load when shared link is detected */ .loading-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: var(--surface-color); display: flex; flex-direction: column; align-items: center; justify-content: center; z-index: 2000; opacity: 1; transition: opacity 0.3s ease; } .loading-spinner { width: 50px; height: 50px; border: 5px solid rgba(0, 0, 0, 0.1); border-radius: 50%; border-top-color: var(--primary-color); animation: spin 1s linear infinite; margin-bottom: 20px; } .loading-message { font-size: 1.2rem; color: var(--text-color); text-align: center; max-width: 80%; } /* Dark mode adjustments */ body.dark-mode .loading-overlay { background-color: var(--surface-color); } body.dark-mode .loading-spinner { border-color: rgba(255, 255, 255, 0.1); border-top-color: var(--primary-light); } body.dark-mode .loading-message { color: var(--text-color); } /* Hide content during loading */ .content-loading .app-main, .content-loading .tabs-container, .content-loading .editor-section { visibility: hidden; } /* Enhancing cursor visibility in dark mode */ body.dark-mode .CodeMirror-cursor { border-left: 1px solid #ffffff !important; /* White cursor */ width: 2px !important; /* Slightly thicker */ } /* Adding a subtle animation for better visibility */ @keyframes cursor-blink-dark { 0% { opacity: 1; } 100% { opacity: 1; } } body.dark-mode .CodeMirror.cm-fat-cursor .CodeMirror-cursor, body.dark-mode .CodeMirror .CodeMirror-cursor { animation: cursor-blink-dark 1.2s infinite; } /* Ensuring cursor is visible during selection */ body.dark-mode .CodeMirror-focused .CodeMirror-selected { background-color: rgba(66, 135, 255, 0.3) !important; /* Blue selection */ } .app-header .btn-icon:hover { background-color: var(--primary-dark); } html.dark-mode-preload, html.dark-mode-preload body { background-color: var(--surface-color); color: var(--text-color); } html.dark-mode-preload .app-header { background-color: #0f172a; color: #fff; } html.dark-mode-preload .btn-primary { background-color: #0f172a; color: #fff; border-color: #1e293b; } html.dark-mode-preload .btn-icon { color: white; } /* Character counter styles */ .char-counter { position: absolute; bottom: 0; right: 0; background-color: var(--secondary-color); padding: 2px 8px; font-size: 0.75rem; border-top-left-radius: var(--radius); border: 1px solid var(--border-color); border-right: none; border-bottom: none; color: var(--text-light); font-family: var(--font-mono); z-index: 5; user-select: none; transition: opacity 0.3s ease; opacity: 0.8; } .char-counter:hover { opacity: 1; } body.dark-mode .char-counter { background-color: var(--secondary-color); color: var(--text-color); } /* Mobile responsive adjustments */ @media (max-width: 768px) { .char-counter { padding: 1px 4px; font-size: 0.7rem; } }
zricethezav/wasmleaks
3
gitleaks wasm browser
JavaScript
zricethezav
Zachary Rice
gitleaks trufflesecurity
ui.js
JavaScript
/** * UI JavaScript for Secret Scanning * * This script handles all UI interactions including: * - Tab switching * - Theme toggling * - CodeMirror initialization * - Entropy calculation * - Resizable editor functionality * - State sharing via URL fragments */ // Global variables let editor; // CodeMirror instance for input text let configEditor; // CodeMirror instance for config let activeTab = 'scan'; // Currently active tab let isResizing = false; // Flag to track resize state // Initialize on document load document.addEventListener('DOMContentLoaded', () => { // Check if we have a hash in the URL - if so, show loading overlay if (window.location.hash && window.location.hash.length > 1) { showLoadingOverlay(); } initTabs(); initThemeToggle(); initCodeMirrorEditors(); addCharacterCounter(); initEntropyCalculator(); initScanButton(); initCopyRuleButton(); initResizableEditor(); initSharingFeature(); // Check for saved theme preference const savedTheme = localStorage.getItem('theme'); if (savedTheme === 'dark') { document.body.classList.add('dark-mode'); document.getElementById('toggle-theme-btn').textContent = '🌙'; } }); /** * Initialize tab switching functionality */ function initTabs() { const tabButtons = document.querySelectorAll('.tab-btn'); tabButtons.forEach(button => { button.addEventListener('click', () => { // Remove active class from all tabs tabButtons.forEach(btn => btn.classList.remove('active')); // Add active class to clicked tab button.classList.add('active'); // Hide all tab content document.querySelectorAll('.tab-content').forEach(content => { content.classList.remove('active'); content.style.display = 'none'; }); // Show the selected tab const tabId = button.getAttribute('data-tab'); const activeContent = document.getElementById(`${tabId}-tab`); if (activeContent) { activeContent.classList.add('active'); activeContent.style.display = 'flex'; // Update active tab activeTab = tabId; // Refresh CodeMirror instances when switching tabs to ensure they render correctly setTimeout(() => { if (editor) editor.refresh(); if (configEditor) configEditor.refresh(); }, 5); } }); }); } /** * Initialize theme toggle functionality */ function initThemeToggle() { const toggleBtn = document.getElementById('toggle-theme-btn'); // Remove preload class once ready document.documentElement.classList.remove('dark-mode-preload'); toggleBtn.addEventListener('click', () => { // Toggle dark mode class on body document.body.classList.toggle('dark-mode'); // Update button icon const isDarkMode = document.body.classList.contains('dark-mode'); toggleBtn.textContent = isDarkMode ? '🌙' : '💡'; // Save preference localStorage.setItem('theme', isDarkMode ? 'dark' : 'light'); // Refresh CodeMirror instances to update their theme if (editor) editor.refresh(); if (configEditor) configEditor.refresh(); }); } /** * Initialize CodeMirror editors */ function initCodeMirrorEditors() { // Initialize content editor const textArea = document.getElementById('inputText'); editor = CodeMirror.fromTextArea(textArea, { lineNumbers: true, theme: 'idea', mode: 'text/plain', // Using plain text mode without syntax highlighting viewportMargin: Infinity, lineWrapping: true, tabSize: 4, indentWithTabs: false }); // Initialize config editor const configTextArea = document.getElementById('configText'); configEditor = CodeMirror.fromTextArea(configTextArea, { lineNumbers: true, theme: 'idea', mode: 'text/x-toml', viewportMargin: Infinity, lineWrapping: true, tabSize: 4, indentWithTabs: false }); // Initialize load default config button document.getElementById('loadDefaultConfigBtn').addEventListener('click', loadDefaultConfig); } /** * Initialize resizable editor functionality */ function initResizableEditor() { const resizeHandle = document.getElementById('resizeHandle'); const editorSection = document.querySelector('.editor-section'); if (!resizeHandle || !editorSection) return; // Try to load saved height from localStorage const savedHeight = localStorage.getItem('editorHeight'); if (savedHeight) { editorSection.style.height = savedHeight; } // Set up resize event listeners resizeHandle.addEventListener('mousedown', (e) => { e.preventDefault(); isResizing = true; // Add resize events to document document.addEventListener('mousemove', handleMouseMove); document.addEventListener('mouseup', handleMouseUp); // Add a class to the body to change cursor while resizing document.body.style.cursor = 'ns-resize'; resizeHandle.classList.add('active'); }); // Touch support for mobile resizeHandle.addEventListener('touchstart', (e) => { e.preventDefault(); isResizing = true; // Add touch events to document document.addEventListener('touchmove', handleTouchMove); document.addEventListener('touchend', handleTouchEnd); resizeHandle.classList.add('active'); }); /** * Handle mouse movement during resize */ function handleMouseMove(e) { if (!isResizing) return; // Calculate new height const containerRect = document.querySelector('.resizable-container').getBoundingClientRect(); const containerTop = containerRect.top; const newHeight = Math.max(100, e.clientY - containerTop); // Update editor height editorSection.style.height = `${newHeight}px`; // Refresh CodeMirror if (editor) editor.refresh(); } /** * Handle touch movement during resize */ function handleTouchMove(e) { if (!isResizing || !e.touches[0]) return; // Calculate new height const containerRect = document.querySelector('.resizable-container').getBoundingClientRect(); const containerTop = containerRect.top; const newHeight = Math.max(100, e.touches[0].clientY - containerTop); // Update editor height editorSection.style.height = `${newHeight}px`; // Refresh CodeMirror if (editor) editor.refresh(); } /** * Handle mouse up to end resize */ function handleMouseUp() { isResizing = false; document.removeEventListener('mousemove', handleMouseMove); document.removeEventListener('mouseup', handleMouseUp); // Reset cursor document.body.style.cursor = ''; resizeHandle.classList.remove('active'); // Save the current height to localStorage localStorage.setItem('editorHeight', editorSection.style.height); } /** * Handle touch end to end resize */ function handleTouchEnd() { isResizing = false; document.removeEventListener('touchmove', handleTouchMove); document.removeEventListener('touchend', handleTouchEnd); resizeHandle.classList.remove('active'); // Save the current height to localStorage localStorage.setItem('editorHeight', editorSection.style.height); } // Add double-click handler to reset height to default resizeHandle.addEventListener('dblclick', () => { editorSection.style.height = 'var(--default-editor-height)'; if (editor) editor.refresh(); // Save the default height localStorage.setItem('editorHeight', editorSection.style.height); }); } /** * Initialize entropy calculator */ function initEntropyCalculator() { const entropyInput = document.getElementById('entropyInput'); const entropyOutput = document.getElementById('entropyOutput'); entropyInput.addEventListener('input', () => { const value = entropyInput.value; const entropy = shannonEntropy(value); entropyOutput.textContent = `Entropy: ${entropy.toFixed(2)}`; }); } /** * Initialize scan button */ function initScanButton() { document.getElementById('scanBtn').addEventListener('click', () => { // Call the scan function from gitleaks.js if (typeof scan === 'function') { scan(); } else { console.error('Scan function not available'); } }); } /** * Initialize copy rule button */ function initCopyRuleButton() { document.getElementById('copyRuleBtn').addEventListener('click', copyGeneratedRule); } /** * Initialize the sharing feature */ function initSharingFeature() { // Add share button event listener document.getElementById('share-btn').addEventListener('click', shareState); // Check for shared state when page loads checkForSharedState(); } /** * Serialize the current state for sharing * @param {boolean} includeInputText - Whether to include the input text * @returns {Object} Serialized state object */ function serializeState(includeInputText = false) { // Only collect content and config state const state = { config: configEditor.getValue(), activeTab: activeTab, logLevel: document.getElementById("logLevelSelect").value }; // Only include input text if explicitly requested if (includeInputText) { state.inputText = editor.getValue(); } return state; } /** * Serialize the current state for sharing * @param {boolean} includeInputText - Whether to include the input text * @returns {Object} Serialized state object */ function serializeState(includeInputText = false) { // Only collect content and config state const state = { config: configEditor.getValue(), activeTab: activeTab, logLevel: document.getElementById("logLevelSelect").value }; // Only include input text if explicitly requested if (includeInputText) { state.inputText = editor.getValue(); } return state; } /** * Compress state JSON to make URLs shorter using Pako (gzip) compression * @param {string} stateJson - JSON string to compress * @returns {Promise<string>} Compressed and encoded string */ async function compressState(stateJson) { try { // Check if pako is available if (!window.pako) { console.error("Pako library not loaded"); throw new Error("Compression library not available"); } // Convert string to Uint8Array const textEncoder = new TextEncoder(); const data = textEncoder.encode(stateJson); // Compress with pako (gzip) const compressed = window.pako.deflate(data, { level: 9 }); // Convert compressed bytes to Base64 const compressedBase64 = btoa( Array.from(compressed) .map(byte => String.fromCharCode(byte)) .join('') ); return compressedBase64; } catch (err) { console.error("Error during compression:", err); throw err; } } /** * Decompress data from URL fragment * @param {string} compressed - Compressed state string * @returns {Promise<Object>} Decompressed state object */ async function decompressState(compressed) { try { // Check if pako is available if (!window.pako) { throw new Error("Pako library not loaded"); } // Decode Base64 const byteCharacters = atob(compressed); // Convert string to byte array const byteArray = new Uint8Array(byteCharacters.length); for (let i = 0; i < byteCharacters.length; i++) { byteArray[i] = byteCharacters.charCodeAt(i); } // Decompress with pako const decompressed = window.pako.inflate(byteArray); // Convert Uint8Array back to string const textDecoder = new TextDecoder(); const jsonStr = textDecoder.decode(decompressed); return JSON.parse(jsonStr); } catch (err) { console.error("Decompression error:", err); throw new Error("Failed to decode shared state: " + err.message); } } /** * Check if the current configuration is the default one * @returns {boolean} True if using default config */ function isDefaultConfig() { if (!window.getDefaultConfig || typeof window.getDefaultConfig !== 'function') { return false; } try { const defaultConfig = window.getDefaultConfig(); const currentConfig = configEditor.getValue(); // Compare configs - ignoring whitespace variations const normalizedDefault = defaultConfig.replace(/\s+/g, ' ').trim(); const normalizedCurrent = currentConfig.replace(/\s+/g, ' ').trim(); return normalizedDefault === normalizedCurrent; } catch (err) { console.error("Error checking default config:", err); return false; } } /** * Share the current state via URL fragment with variable format * Always includes input text and always shows the share modal */ async function shareState() { try { // Show processing indicator showNotification("Generating share link...", "processing"); // Check if using default config const usingDefaultConfig = isDefaultConfig(); // Get and compress configuration if not using default let shareUrl = `${window.location.origin}${window.location.pathname}#`; if (!usingDefaultConfig) { const configState = { config: configEditor.getValue(), logLevel: document.getElementById("logLevelSelect").value, activeTab: activeTab }; const configStateJson = JSON.stringify(configState); const compressedConfig = await compressState(configStateJson); shareUrl += `conf=${compressedConfig}`; } else { // Just add a flag indicating default config with log level const logLevel = document.getElementById("logLevelSelect").value; shareUrl += `default=1&log=${logLevel}&tab=${activeTab}`; } // Always include input text const inputText = editor.getValue(); if (inputText && inputText.trim() !== "") { const contentState = { inputText }; const contentStateJson = JSON.stringify(contentState); const compressedContent = await compressState(contentStateJson); // Add appropriate connector shareUrl += shareUrl.includes('=') ? '&' : ''; shareUrl += `content=${compressedContent}`; } // Always show the share link modal (no clipboard copying) showShareLink(shareUrl); // Remove the processing notification document.querySelectorAll(`.notification.notification-processing`).forEach(el => el.remove()); } catch (err) { console.error("Failed to create share link:", err); showNotification("Error creating share link: " + err.message, "error"); } } /** * Parse URL parameters from the fragment * @returns {Object} Map of parameter name to value */ function parseUrlFragment() { if (!window.location.hash || window.location.hash.length <= 1) { return {}; } const fragment = window.location.hash.substring(1); const params = {}; // Split by & but not inside compressed data (which may contain &) let currentParam = ""; let inValue = false; for (let i = 0; i < fragment.length; i++) { const char = fragment[i]; if (char === '=' && !inValue) { inValue = true; const key = currentParam; currentParam = ""; params[key] = ""; } else if (char === '&' && !inValue) { // Skip empty parameters currentParam = ""; } else if (char === '&' && inValue) { inValue = false; currentParam = ""; } else { currentParam += char; if (inValue) { params[Object.keys(params).pop()] = currentParam; } } } return params; } /** * Check for shared state in URL fragment on page load */ async function checkForSharedState() { try { const params = parseUrlFragment(); if (Object.keys(params).length === 0) { // No shared state, remove loading overlay if it exists hideLoadingOverlay(); editor.setValue(`some fake secrets to mess around with\n\n` + `discord_client_secret = '8dyfuiRyq=vVc3RRr_edRk-fK__JItpZ'\n` + `const FastlyAPIToken = "uhZtofOcNnzoH6F5-m0bzsLvCqIjzNFG"` ); return; } // Show loading indicator if not already shown if (!window.loadingOverlay) { showLoadingOverlay(); } // Check for default config flag if (params.default === '1') { // Create a minimal state object with just log level and active tab window.pendingSharedState = { // Let loadDefaultConfig() handle setting the default config useDefaultConfig: true, logLevel: params.log || 'Info', activeTab: params.tab || 'scan' }; } // Parse configuration if provided else if (params.conf) { try { const configState = await decompressState(params.conf); window.pendingSharedState = configState; } catch (err) { console.error("Failed to parse configuration state:", err); showNotification("Failed to load shared configuration.", "error"); hideLoadingOverlay(); } } // Parse content if present if (params.content) { try { const contentState = await decompressState(params.content); if (contentState.inputText) { window.pendingInputText = contentState.inputText; } } catch (err) { console.error("Failed to parse content state:", err); showNotification("Failed to load shared content.", "error"); } } } catch (err) { console.error("Failed to process shared state:", err); showNotification("Failed to load shared configuration.", "error"); hideLoadingOverlay(); } } /** * Load shared state into the app * @param {Object} state - The state object to load */ window.loadSharedState = function(state) { // Load main state if (state.config) configEditor.setValue(state.config); if (state.logLevel) document.getElementById("logLevelSelect").value = state.logLevel; // Load input text if it exists if (state.inputText) editor.setValue(state.inputText); // Load wizard state if it exists if (state.wizard) { // Set basic fields document.getElementById('ruleType').value = state.wizard.ruleType; document.getElementById('ruleId').value = state.wizard.ruleId || ''; document.getElementById('ruleDescription').value = state.wizard.ruleDescription || ''; // Update visible fields based on rule type updateWizardFields(); // Set type-specific fields if (state.wizard.ruleType === 'semi') { document.getElementById('identifiers').value = state.wizard.identifiers || ''; document.getElementById('entropySemi').value = state.wizard.entropySemi || ''; document.getElementById('keywordSemi').value = state.wizard.keywordSemi || ''; document.getElementById('captureType').value = state.wizard.captureType || 'manual'; if (state.wizard.captureType === 'manual') { document.getElementById('captureManual').value = state.wizard.captureManual || ''; } else { document.getElementById('capturePreset').value = state.wizard.capturePreset || 'Numeric'; document.getElementById('captureMin').value = state.wizard.captureMin || ''; document.getElementById('captureMax').value = state.wizard.captureMax || ''; } updateCaptureTypeDisplay(); } else { document.getElementById('regexUnique').value = state.wizard.regexUnique || ''; document.getElementById('entropyUnique').value = state.wizard.entropyUnique || ''; document.getElementById('keyword').value = state.wizard.keyword || ''; } // Update generated rule updateGeneratedRule(); } // Switch to the saved active tab if (state.activeTab) { document.querySelector(`.tab-btn[data-tab="${state.activeTab}"]`).click(); } // Refresh editors if (editor) editor.refresh(); if (configEditor) configEditor.refresh(); // Show success notification showNotification("Shared configuration loaded successfully!"); } /** * Show a modal dialog with the share link * @param {string} url - The URL to display */ /** * Show a modal dialog with the share link * @param {string} url - The URL to display */ function showShareLink(url) { // Remove any existing share modals document.querySelectorAll('.share-modal').forEach(el => el.remove()); // Create a modal dialog with the URL const modal = document.createElement('div'); modal.className = 'share-modal'; modal.innerHTML = ` <div class="share-modal-content"> <h3>Share Link</h3> <p>Copy this link to share your configuration and content:</p> <input type="text" value="${url}" readonly onclick="this.select();"> <div class="modal-actions"> <button id="copy-share-link" class="btn btn-primary">Copy to Clipboard</button> <button class="btn btn-secondary" onclick="this.parentNode.parentNode.parentNode.remove()">Close</button> </div> </div> `; document.body.appendChild(modal); // Auto-select the input text for easy copying setTimeout(() => { const input = modal.querySelector('input'); input.select(); }, 100); // Add click handler for copy button modal.querySelector('#copy-share-link').addEventListener('click', () => { const input = modal.querySelector('input'); input.select(); navigator.clipboard.writeText(input.value) .then(() => { showNotification("Link copied to clipboard!"); }) .catch(err => { console.error("Failed to copy:", err); showNotification("Failed to copy link. Please select and copy manually.", "error"); }); }); } /** * Show a notification message * @param {string} message - The message to display * @param {string} type - The notification type (default, error, processing) * @param {boolean} autoRemove - Whether to auto-remove the notification * @returns {HTMLElement} The notification element */ function showNotification(message, type = 'default', autoRemove = true) { // Remove any existing notification with the same type document.querySelectorAll(`.notification.notification-${type}`).forEach(el => el.remove()); const notification = document.createElement('div'); notification.className = `notification notification-${type}`; if (type === 'processing') { notification.innerHTML = ` <div class="notification-spinner"></div> <span>${message}</span> `; } else { notification.textContent = message; } document.body.appendChild(notification); // Auto-remove after a few seconds if requested if (autoRemove) { setTimeout(() => { notification.style.opacity = '0'; setTimeout(() => { notification.remove(); }, 300); }, 5000); } return notification; } /** * Calculate Shannon entropy * @param {string} data - Input string * @returns {number} Entropy value */ function shannonEntropy(data) { if (!data || data.length === 0) { return 0; } const charCounts = {}; // Count occurrences of each character for (const char of data) { charCounts[char] = (charCounts[char] || 0) + 1; } // Calculate entropy let entropy = 0; const length = data.length; for (const char in charCounts) { const freq = charCounts[char] / length; entropy -= freq * Math.log2(freq); } return entropy; } /** * Updates the wizard fields based on the selected rule type */ function updateWizardFields() { const ruleType = document.getElementById('ruleType').value; if (ruleType === "semi") { document.getElementById('semiFields').style.display = 'block'; document.getElementById('uniqueFields').style.display = 'none'; } else { document.getElementById('semiFields').style.display = 'none'; document.getElementById('uniqueFields').style.display = 'block'; } updateCaptureTypeDisplay(); updateGeneratedRule(); } /** * Creates and shows a loading overlay while shared content is being loaded */ function showLoadingOverlay() { // Add a class to the body to hide content during loading document.body.classList.add('content-loading'); // Create the loading overlay const overlay = document.createElement('div'); overlay.className = 'loading-overlay'; overlay.innerHTML = ` <div class="loading-spinner"></div> <div class="loading-message">Loading shared configuration...</div> `; // Add to the DOM document.body.appendChild(overlay); // Store a reference to remove it later window.loadingOverlay = overlay; } /** * Removes the loading overlay and shows the content */ function hideLoadingOverlay() { // If we have a loading overlay, remove it gracefully if (window.loadingOverlay) { // Fade out window.loadingOverlay.style.opacity = '0'; // Remove the loading class to show content document.body.classList.remove('content-loading'); // Remove from DOM after animation completes setTimeout(() => { if (window.loadingOverlay && window.loadingOverlay.parentNode) { window.loadingOverlay.parentNode.removeChild(window.loadingOverlay); } window.loadingOverlay = null; // Refresh CodeMirror editors to ensure proper rendering if (editor) editor.refresh(); if (configEditor) configEditor.refresh(); }, 300); } } /** * Add character counter to bottom right of the editor * This will show the number of characters selected or current cursor position */ function addCharacterCounter() { // Create character counter element const counterElement = document.createElement('div'); counterElement.className = 'char-counter'; counterElement.innerHTML = 'Pos: 0:0 | Sel: 0'; // Find the editor container and append counter const editorContainer = document.querySelector('.editor-container'); editorContainer.style.position = 'relative'; editorContainer.appendChild(counterElement); // Add event listeners to update the counter editor.on('cursorActivity', function() { updateCharCounter(editor, counterElement); }); // Initial update updateCharCounter(editor, counterElement); } /** * Update the character counter with current selection or cursor info * @param {CodeMirror} cm - The CodeMirror instance * @param {HTMLElement} counterElement - The counter element to update */ function updateCharCounter(cm, counterElement) { const selection = cm.getSelection(); const cursor = cm.getCursor(); let message = `Pos: ${cursor.line + 1}:${cursor.ch + 1}`; if (selection && selection.length > 0) { message += ` | Sel: ${selection.length}`; // If selected text is longer than 3 characters, calculate and show entropy if (selection.length > 3) { const entropy = shannonEntropy(selection).toFixed(2); message += ` | Entropy: ${entropy}`; } } else { message += ` | Sel: 0`; } counterElement.innerHTML = message; }
zricethezav/wasmleaks
3
gitleaks wasm browser
JavaScript
zricethezav
Zachary Rice
gitleaks trufflesecurity
.eslintrc.js
JavaScript
module.exports = { parser: "@typescript-eslint/parser", // Specifies the ESLint parser parserOptions: { ecmaVersion: 2020, // Allows for the parsing of modern ECMAScript features sourceType: "module" // Allows for the use of imports }, extends: [ "plugin:@typescript-eslint/recommended" // Uses the recommended rules from the @typescript-eslint/eslint-plugin ], rules: { // Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs // e.g. "@typescript-eslint/explicit-function-return-type": "off", } };
zsarnett/Custom-Grid-View
109
Custom Drag and Drop Grid for Home Assistant
TypeScript
zsarnett
Zack Barett
.prettierrc.js
JavaScript
module.exports = { semi: true, trailingComma: 'all', singleQuote: true, printWidth: 120, tabWidth: 2, };
zsarnett/Custom-Grid-View
109
Custom Drag and Drop Grid for Home Assistant
TypeScript
zsarnett
Zack Barett
rollup.config.dev.js
JavaScript
import json from '@rollup/plugin-json'; import babel from 'rollup-plugin-babel'; import resolve from 'rollup-plugin-node-resolve'; import serve from 'rollup-plugin-serve'; import { terser } from 'rollup-plugin-terser'; import typescript from 'rollup-plugin-typescript2'; export default { input: ['src/grid-view.ts'], output: { dir: './dist', format: 'es', }, plugins: [ resolve(), typescript(), json(), babel({ exclude: 'node_modules/**', }), terser(), serve({ contentBase: './dist', host: '0.0.0.0', port: 5000, allowCrossOrigin: true, headers: { 'Access-Control-Allow-Origin': '*', }, }), ], };
zsarnett/Custom-Grid-View
109
Custom Drag and Drop Grid for Home Assistant
TypeScript
zsarnett
Zack Barett