repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
wingman-ai
github_2023
RussellCanfield
typescript
computeDiff
const computeDiff = ( oldValue: string | Object, newValue: string | Object, compareMethod: string = DiffMethod.CHARS ): ComputedDiffInformation => { const diffArray: JsDiffChangeObject[] = jsDiff[compareMethod]( oldValue, newValue ); const computedDiff: ComputedDiffInformation = { left: [], right: [], }; diffArray.forEach(({ added, removed, value }): DiffInformation => { const diffInformation: DiffInformation = {}; if (added) { diffInformation.type = DiffType.ADDED; diffInformation.value = value; computedDiff.right.push(diffInformation); } if (removed) { diffInformation.type = DiffType.REMOVED; diffInformation.value = value; computedDiff.left.push(diffInformation); } if (!removed && !added) { diffInformation.type = DiffType.DEFAULT; diffInformation.value = value; computedDiff.right.push(diffInformation); computedDiff.left.push(diffInformation); } return diffInformation; }); return computedDiff; };
/** * Computes word diff information in the line. * [TODO]: Consider adding options argument for JsDiff text block comparison * * @param oldValue Old word in the line. * @param newValue New word in the line. * @param compareMethod JsDiff text diff method from https://github.com/kpdecker/jsdiff/tree/v4.0.1#api */
https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/views-ui/src/Common/DiffView/compute-lines.ts#L76-L110
7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6
wingman-ai
github_2023
RussellCanfield
typescript
computeLineInformation
const computeLineInformation = ( oldString: string | Object, newString: string | Object, disableWordDiff: boolean = false, lineCompareMethod: string = DiffMethod.CHARS, linesOffset: number = 0, showLines: string[] = [] ): ComputedLineInformation => { let diffArray: Diff.Change[] = []; // Use diffLines for strings, and diffJson for objects... if (typeof oldString === "string" && typeof newString === "string") { diffArray = diff.diffLines( oldString.trimRight(), newString.trimRight(), { newlineIsToken: false, ignoreWhitespace: false, ignoreCase: false, } ); } else { diffArray = diff.diffJson(oldString, newString); } let rightLineNumber = linesOffset; let leftLineNumber = linesOffset; let lineInformation: LineInformation[] = []; let counter = 0; const diffLines: number[] = []; const ignoreDiffIndexes: string[] = []; const getLineInformation = ( value: string, diffIndex: number, added?: boolean, removed?: boolean, evaluateOnlyFirstLine?: boolean ): LineInformation[] => { const lines = constructLines(value); return lines .map((line: string, lineIndex): LineInformation => { const left: DiffInformation = {}; const right: DiffInformation = {}; if ( ignoreDiffIndexes.includes(`${diffIndex}-${lineIndex}`) || (evaluateOnlyFirstLine && lineIndex !== 0) ) { return undefined; } if (added || removed) { let countAsChange = true; if (removed) { leftLineNumber += 1; left.lineNumber = leftLineNumber; left.type = DiffType.REMOVED; left.value = line || " "; // When the current line is of type REMOVED, check the next item in // the diff array whether it is of type ADDED. If true, the current // diff will be marked as both REMOVED and ADDED. Meaning, the // current line is a modification. const nextDiff = diffArray[diffIndex + 1]; if (nextDiff && nextDiff.added) { const nextDiffLines = constructLines( nextDiff.value )[lineIndex]; if (nextDiffLines) { const nextDiffLineInfo = getLineInformation( nextDiffLines, diffIndex, true, false, true ); const { value: rightValue, lineNumber, type, } = nextDiffLineInfo[0].right; // When identified as modification, push the next diff to ignore // list as the next value will be added in this line computation as // right and left values. ignoreDiffIndexes.push( `${diffIndex + 1}-${lineIndex}` ); right.lineNumber = lineNumber; if (left.value === rightValue) { // The new value is exactly the same as the old countAsChange = false; right.type = 0; left.type = 0; right.value = rightValue; } else { right.type = type; // Do char level diff and assign the corresponding values to the // left and right diff information object. if (disableWordDiff) { right.value = rightValue; } else { const computedDiff = computeDiff( line, rightValue as string, lineCompareMethod ); right.value = computedDiff.right; left.value = computedDiff.left; } } } } } else { rightLineNumber += 1; right.lineNumber = rightLineNumber; right.type = DiffType.ADDED; right.value = line; } if (countAsChange && !evaluateOnlyFirstLine) { if (!diffLines.includes(counter)) { diffLines.push(counter); } } } else { leftLineNumber += 1; rightLineNumber += 1; left.lineNumber = leftLineNumber; left.type = DiffType.DEFAULT; left.value = line; right.lineNumber = rightLineNumber; right.type = DiffType.DEFAULT; right.value = line; } if ( showLines?.includes(`L-${left.lineNumber}`) || (showLines?.includes(`R-${right.lineNumber}`) && !diffLines.includes(counter)) ) { diffLines.push(counter); } if (!evaluateOnlyFirstLine) { counter += 1; } return { right, left }; }) .filter(Boolean); }; diffArray.forEach(({ added, removed, value }: diff.Change, index): void => { lineInformation = [ ...lineInformation, ...getLineInformation(value, index, added, removed), ]; }); return { lineInformation, diffLines, }; };
/** * [TODO]: Think about moving common left and right value assignment to a * common place. Better readability? * * Computes line wise information based in the js diff information passed. Each * line contains information about left and right section. Left side denotes * deletion and right side denotes addition. * * @param oldString Old string to compare. * @param newString New string to compare with old string. * @param disableWordDiff Flag to enable/disable word diff. * @param lineCompareMethod JsDiff text diff method from https://github.com/kpdecker/jsdiff/tree/v4.0.1#api * @param linesOffset line number to start counting from * @param showLines lines that are always shown, regardless of diff */
https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/views-ui/src/Common/DiffView/compute-lines.ts#L127-L290
7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6
wingman-ai
github_2023
RussellCanfield
typescript
VSCodeAPIWrapper.postMessage
public postMessage(message: unknown) { if (this.vsCodeApi) { this.vsCodeApi.postMessage(message); } else { console.log(message); } }
/** * Post a message (i.e. send arbitrary data) to the owner of the webview. * * @remarks When running webview code inside a web browser, postMessage will instead * log the given message to the console. * * @param message Abitrary data (must be JSON serializable) to send to the extension context. */
https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/views-ui/src/Config/utilities/vscode.ts#L31-L37
7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6
wingman-ai
github_2023
RussellCanfield
typescript
VSCodeAPIWrapper.getState
public getState(): unknown | undefined { if (this.vsCodeApi) { return this.vsCodeApi.getState(); } else { const state = localStorage.getItem("vscodeState"); return state ? JSON.parse(state) : undefined; } }
/** * Get the persistent state stored for this webview. * * @remarks When running webview source code inside a web browser, getState will retrieve state * from local storage (https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). * * @return The current state or `undefined` if no state has been set. */
https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/views-ui/src/Config/utilities/vscode.ts#L47-L54
7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6
wingman-ai
github_2023
RussellCanfield
typescript
VSCodeAPIWrapper.setState
public setState<T extends unknown | undefined>(newState: T): T { if (this.vsCodeApi) { return this.vsCodeApi.setState(newState); } else { localStorage.setItem("vscodeState", JSON.stringify(newState)); return newState; } }
/** * Set the persistent state stored for this webview. * * @remarks When running webview source code inside a web browser, setState will set the given * state using local storage (https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). * * @param newState New persisted state. This must be a JSON serializable object. Can be retrieved * using {@link getState}. * * @return The new state. */
https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/views-ui/src/Config/utilities/vscode.ts#L67-L74
7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6
wingman-ai
github_2023
RussellCanfield
typescript
VSCodeAPIWrapper.postMessage
public postMessage(message: unknown) { if (this.vsCodeApi) { this.vsCodeApi.postMessage(message); } else { console.log(message); } }
/** * Post a message (i.e. send arbitrary data) to the owner of the webview. * * @remarks When running webview code inside a web browser, postMessage will instead * log the given message to the console. * * @param message Abitrary data (must be JSON serializable) to send to the extension context. */
https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/views-ui/src/Diff/utilities/vscode.ts#L37-L43
7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6
wingman-ai
github_2023
RussellCanfield
typescript
VSCodeAPIWrapper.getState
public getState(): unknown | undefined { if (this.vsCodeApi) { return this.vsCodeApi.getState(); } else { const state = localStorage.getItem("vscodeState"); return state ? JSON.parse(state) : undefined; } }
/** * Get the persistent state stored for this webview. * * @remarks When running webview source code inside a web browser, getState will retrieve state * from local storage (https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). * * @return The current state or `undefined` if no state has been set. */
https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/views-ui/src/Diff/utilities/vscode.ts#L53-L60
7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6
wingman-ai
github_2023
RussellCanfield
typescript
VSCodeAPIWrapper.setState
public setState<T extends unknown | undefined>(newState: T): T { if (this.vsCodeApi) { return this.vsCodeApi.setState(newState); } else { localStorage.setItem("vscodeState", JSON.stringify(newState)); return newState; } }
/** * Set the persistent state stored for this webview. * * @remarks When running webview source code inside a web browser, setState will set the given * state using local storage (https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). * * @param newState New persisted state. This must be a JSON serializable object. Can be retrieved * using {@link getState}. * * @return The new state. */
https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/views-ui/src/Diff/utilities/vscode.ts#L73-L80
7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6
private-mirrors
github_2023
github-community-projects
typescript
normalizeExpirationDate
const normalizeExpirationDate = (seconds: number) => { return Date.now() + seconds * 1000 }
/** * Converts seconds until expiration to date in milliseconds * @param seconds Seconds until expiration to convert * @returns number — Expiration date in milliseconds */
https://github.com/github-community-projects/private-mirrors/blob/31ec702405e4e6afd34f7f68313492eb81367a31/src/app/api/auth/lib/nextauth-options.ts#L16-L18
31ec702405e4e6afd34f7f68313492eb81367a31
private-mirrors
github_2023
github-community-projects
typescript
createBranchProtectionRuleset
const createBranchProtectionRuleset = async ( context: ContextEvent, bypassActorId: string, ruleName: string, includeRefs: string[], isMirror = false, ) => { rulesLogger.info('Creating branch protection via rulesets', { isMirror, }) // Get the current branch protection rulesets const getBranchProtectionRuleset = await context.octokit.graphql<{ repository: Repository }>(getBranchProtectionRulesetGQL, { owner: context.payload.repository.owner.login, name: context.payload.repository.name, }) if ( getBranchProtectionRuleset.repository.rulesets?.nodes?.find( (ruleset) => ruleset?.name === ruleName, ) ) { rulesLogger.info('Branch protection ruleset already exists', { getBranchProtectionRuleset, }) return } const query = isMirror ? mirrorBranchProtectionRulesetGQL : forkBranchProtectionRulesetGQL // Create the branch protection ruleset const branchProtectionRuleset = await context.octokit.graphql(query, { repositoryId: context.payload.repository.node_id, ruleName, bypassActorId, includeRefs, }) rulesLogger.info('Created branch protection via rulesets', { branchProtectionRuleset, }) }
/** * Creates branch protections rulesets * @param context The context object * @param bypassActorId The actor node ID to bypass branch protections * @param ruleName The name of the branch protection ruleset * @param includeRefs The refs to include in the branch protection ruleset */
https://github.com/github-community-projects/private-mirrors/blob/31ec702405e4e6afd34f7f68313492eb81367a31/src/bot/rules.ts#L150-L196
31ec702405e4e6afd34f7f68313492eb81367a31
private-mirrors
github_2023
github-community-projects
typescript
createBranchProtection
const createBranchProtection = async ( context: ContextEvent, repositoryNodeId: string, pattern: string, actorId: string, isMirror = false, ) => { rulesLogger.info('Creating branch protection via GQL', { isMirror, }) const query = isMirror ? mirrorBranchProtectionGQL : forkBranchProtectionGQL const forkBranchProtection = await context.octokit.graphql(query, { repositoryId: repositoryNodeId, pattern, actorId, }) rulesLogger.info('Created branch protection via GQL', { forkBranchProtection, }) }
/** * Fallback function to create branch protection if ruleset creation fails * @param context The context object * @param repositoryNodeId The repository global node ID * @param pattern The branch pattern * @param actorId The bypass actor ID */
https://github.com/github-community-projects/private-mirrors/blob/31ec702405e4e6afd34f7f68313492eb81367a31/src/bot/rules.ts#L205-L227
31ec702405e4e6afd34f7f68313492eb81367a31
private-mirrors
github_2023
github-community-projects
typescript
createBranchProtectionREST
const createBranchProtectionREST = async ( context: ContextEvent, pattern: string, ) => { rulesLogger.info('Creating branch protection via REST') const res = await context.octokit.repos.updateBranchProtection({ branch: pattern, enforce_admins: true, owner: context.payload.repository.owner.login, repo: context.payload.repository.name, required_pull_request_reviews: { dismiss_stale_reviews: true, require_code_owner_reviews: false, required_approving_review_count: 1, dismissal_restrictions: { users: [], teams: [], }, }, required_status_checks: null, restrictions: null, }) rulesLogger.info('Created branch protection via REST', { res, repositoryOwner: context.payload.repository.owner.login, repositoryName: context.payload.repository.name, }) }
/** * The REST API fallback function to create branch protections in case GQL fails * @param context The context object * @param pattern The default branch pattern */
https://github.com/github-community-projects/private-mirrors/blob/31ec702405e4e6afd34f7f68313492eb81367a31/src/bot/rules.ts#L234-L263
31ec702405e4e6afd34f7f68313492eb81367a31
private-mirrors
github_2023
github-community-projects
typescript
stringify
const stringify = (obj: any) => { try { return JSON.stringify(obj) } catch { return safeStringify(obj) } }
// This is a workaround for the issue with JSON.stringify and circular references
https://github.com/github-community-projects/private-mirrors/blob/31ec702405e4e6afd34f7f68313492eb81367a31/src/utils/logger.ts#L7-L13
31ec702405e4e6afd34f7f68313492eb81367a31
private-mirrors
github_2023
github-community-projects
typescript
getLoggerType
const getLoggerType = () => { if (process.env.NODE_ENV === 'development') { return 'pretty' } if (process.env.NODE_ENV === 'test' || process.env.TEST_LOGGING === '1') { return 'pretty' } return 'json' }
// If you need logs during tests you can set the env var TEST_LOGGING=true
https://github.com/github-community-projects/private-mirrors/blob/31ec702405e4e6afd34f7f68313492eb81367a31/src/utils/logger.ts#L16-L26
31ec702405e4e6afd34f7f68313492eb81367a31
stratus
github_2023
cloudwalk
typescript
log
function log(event: any) { let payloads = null; let kind = ""; if (event.action == "sendRpcPayload") { [kind, payloads] = ["REQ -> ", event.payload]; } if (event.action == "receiveRpcResult") { [kind, payloads] = ["RESP <- ", event.result]; } if (!Array.isArray(payloads)) { payloads = [payloads]; } for (const payload of payloads) { console.log(kind, JSON.stringify(payload)); } }
// Configure RPC logger if RPC_LOG env-var is configured.
https://github.com/cloudwalk/stratus/blob/e2e1043f0d25caf2ebc9b063d4568f99545278ba/e2e/test/helpers/rpc.ts#L83-L98
e2e1043f0d25caf2ebc9b063d4568f99545278ba
stratus
github_2023
cloudwalk
typescript
addOpenListener
function addOpenListener(socket: WebSocket, subscription: string, params: any) { socket.addEventListener("open", function () { socket.send(JSON.stringify({ jsonrpc: "2.0", id: 0, method: "eth_subscribe", params: [subscription, params] })); }); }
/// Add an "open" event listener to a WebSocket
https://github.com/cloudwalk/stratus/blob/e2e1043f0d25caf2ebc9b063d4568f99545278ba/e2e/test/helpers/rpc.ts#L298-L302
e2e1043f0d25caf2ebc9b063d4568f99545278ba
stratus
github_2023
cloudwalk
typescript
addMessageListener
function addMessageListener( socket: WebSocket, messageToReturn: number, callback: (messageEvent: { data: string }) => Promise<void>, ): Promise<any> { return new Promise((resolve) => { let messageCount = 0; socket.addEventListener("message", async function (messageEvent: { data: string }) { // console.log("Received message: " + messageEvent.data); messageCount++; if (messageCount === messageToReturn) { const event = JSON.parse(messageEvent.data); socket.close(); resolve(event); } else { await callback(messageEvent); await send("evm_mine", []); } }); }); }
/// Generalized function to add a "message" event listener to a WebSocket
https://github.com/cloudwalk/stratus/blob/e2e1043f0d25caf2ebc9b063d4568f99545278ba/e2e/test/helpers/rpc.ts#L305-L325
e2e1043f0d25caf2ebc9b063d4568f99545278ba
stratus
github_2023
cloudwalk
typescript
asyncContractOperation
async function asyncContractOperation(contract: TestContractBalances, shouldMine: boolean = false) { let nonce = await sendGetNonce(CHARLIE.address); const contractOps = contract.connect(CHARLIE.signer()); if (shouldMine) { const signedTx = await prepareSignedTx({ contract, account: CHARLIE, methodName: "add", methodParameters: [CHARLIE.address, 10], custom_nonce: nonce++, }); await sendRawTransaction(signedTx); sendEvmMine(); } else { await contractOps.add(CHARLIE.address, 10, { nonce: nonce++ }); } return new Promise((resolve) => setTimeout(resolve, 1000)); }
/// Execute an async contract operation
https://github.com/cloudwalk/stratus/blob/e2e1043f0d25caf2ebc9b063d4568f99545278ba/e2e/test/helpers/rpc.ts#L328-L345
e2e1043f0d25caf2ebc9b063d4568f99545278ba
stratus
github_2023
cloudwalk
typescript
normalizePollingOptions
function normalizePollingOptions( options: { timeoutInMs?: number; pollingIntervalInMs?: number; } = {}, ): { timeoutInMs: number; pollingIntervalInMs: number } { const timeoutInMs: number = options.timeoutInMs ? options.timeoutInMs : DEFAULT_TX_TIMEOUT_IN_MS; const pollingIntervalInMs: number = options.pollingIntervalInMs ? options.pollingIntervalInMs : timeoutInMs / 100; return { timeoutInMs, pollingIntervalInMs, }; }
// Normalizes the options for poll functions
https://github.com/cloudwalk/stratus/blob/e2e1043f0d25caf2ebc9b063d4568f99545278ba/e2e/test/helpers/rpc.ts#L522-L534
e2e1043f0d25caf2ebc9b063d4568f99545278ba
action-table
github_2023
colinaut
typescript
ActionTableFilterMenu.connectedCallback
public connectedCallback(): void { const columnName = this.getAttribute("name"); // name is required if (!columnName) return; // If options are not specified then find them if (this.hasAttribute("options")) { this.options = this.getAttribute("options")?.split(",") || []; } else { this.findOptions(columnName); } this.render(columnName); }
// Using connectedCallback because options may need to be rerendered when added to the DOM
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table-filter-menu.ts#L66-L77
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTableFilterRange.constructor
constructor() { super(); // this.shadow = this.attachShadow({ mode: "open" }); this.render(); this.addEventListeners(); }
// private shadow: ShadowRoot;
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table-filter-range.ts#L4-L9
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
setAttributes
function setAttributes(element: Element, attributes: Record<string, string>) { for (const key in attributes) { element.setAttribute(key, attributes[key]); } }
// Helper function
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table-filter-range.ts#L95-L99
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTableFilters.connectedCallback
public connectedCallback(): void { // Grab current filters from action-table const filters: FiltersObject = this.actionTable.filters; // 4.1 If filters are not empty, set the select/checkbox/radio elements if (Object.keys(filters).length > 0) { this.setFilterElements(filters); } }
/* -------------------------------------------------------------------------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table-filters.ts#L16-L24
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTableFilters.toggleHighlight
private toggleHighlight(el: HTMLInputElement | HTMLSelectElement): void { if (el.value) { el.classList.add("selected"); } else { el.classList.remove("selected"); } }
/* -------------------------------------------------------------------------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table-filters.ts#L30-L36
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTableFilters.addEventListeners
private addEventListeners(): void { const hasAttr = (el: HTMLElement, attr: string) => { return el.hasAttribute(attr) || !!el.closest(`[${attr}]`); }; /* ------------ Event Listeners for select/checkbox/radio ------------ */ this.addEventListener("input", (e) => { const el = e.target; if (el instanceof HTMLSelectElement || el instanceof HTMLInputElement) { const exclusive = hasAttr(el, "exclusive"); const regex = hasAttr(el, "regex"); const exact = hasAttr(el, "exact"); const cols = el.dataset.cols ? el.dataset.cols.toLowerCase().split(",") : undefined; const columnName = el.name.toLowerCase(); if (el instanceof HTMLSelectElement) { this.toggleHighlight(el); const selectedOptions = Array.from(el.selectedOptions).map((option) => option.value); this.dispatch({ [columnName]: { values: selectedOptions, exclusive, regex, exact, cols } }); } if (el instanceof HTMLInputElement) { if (el.type === "checkbox") { // Casting to HTMLInputElement because we know it's a checkbox from selector const checkboxes = this.querySelectorAll("input[type=checkbox][name=" + el.name + "]") as NodeListOf<HTMLInputElement>; const checkboxValues = Array.from(checkboxes) .filter((e) => { return e.checked; }) .map((checkbox) => checkbox.value); this.dispatch({ [columnName]: { values: checkboxValues, exclusive, regex, exact, cols } }); } if (el.type === "radio") { this.dispatch({ [columnName]: { values: [el.value], exclusive, regex, exact, cols } }); } if (el.type === "range") { const sliders = this.querySelectorAll("input[type=range][name='" + el.name + "']") as NodeListOf<HTMLInputElement>; let minMax: string[] = []; const defaultMinMax: string[] = []; sliders.forEach((slider) => { if (slider.dataset.range === "min") { defaultMinMax[0] = slider.min; minMax[0] = slider.value; } if (slider.dataset.range === "max") { defaultMinMax[1] = slider.max; minMax[1] = slider.value; } }); if (minMax.every((item, i) => item === defaultMinMax[i])) { minMax = []; } this.dispatch({ [columnName]: { values: minMax, range: true } }); } } } }); const searchInputs = this.querySelectorAll("input[type='search']") as NodeListOf<HTMLInputElement>; searchInputs.forEach((el) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any function debounce<T extends (...args: any[]) => any>(func: T, timeout = 300) { let timer: ReturnType<typeof setTimeout>; return (...args: Parameters<T>) => { clearTimeout(timer); timer = setTimeout(() => { func(...args); }, timeout); }; } const event = el.dataset.event || "input"; el.addEventListener(event, () => { this.toggleHighlight(el); const exclusive = hasAttr(el, "exclusive"); const regex = hasAttr(el, "regex"); const exact = hasAttr(el, "exact"); const cols = el.dataset.cols ? el.dataset.cols.toLowerCase().split(",") : undefined; const debouncedFilter = debounce(() => this.dispatch({ [el.name]: { values: [el.value], exclusive, regex, exact, cols } })); debouncedFilter(); }); }); /* ------------------------------- Text Input ------------------------------- */ /* ------------------------------ Reset Button ------------------------------ */ this.resetButton?.addEventListener("click", () => { this.resetAllFilterElements(); this.dispatch(); }); /* ----------------- Reset Event Filters from action-table ----------------- */ // This is fired when the reset button is clicked in the tfoot section this.actionTable.addEventListener("action-table-filters-reset", () => { this.resetAllFilterElements(); }); }
/* -------------------------------------------------------------------------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table-filters.ts#L42-L136
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
debounce
function debounce<T extends (...args: any[]) => any>(func: T, timeout = 300) { let timer: ReturnType<typeof setTimeout>; return (...args: Parameters<T>) => { clearTimeout(timer); timer = setTimeout(() => { func(...args); }, timeout); }; }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table-filters.ts#L101-L109
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTableFilters.resetAllFilterElements
public resetAllFilterElements() { console.log("resetAllFilterElements"); // Casting to types as we know what it is from selector const filterElements = this.querySelectorAll("select, input") as NodeListOf<HTMLSelectElement | HTMLInputElement>; filterElements.forEach((el) => { if (el instanceof HTMLInputElement && (el.type === "checkbox" || el.type === "radio")) { if (el.value === "") { el.checked = true; } else { el.checked = false; } } if (el instanceof HTMLSelectElement || (el instanceof HTMLInputElement && el.type === "search")) { el.value = ""; this.toggleHighlight(el); } if (el instanceof HTMLInputElement && el.type === "range") { el.value = el.dataset.range === "max" ? el.max : el.min; // dispatch input event to trigger change for range slider this.dispatchInput(el); } }); }
/* -------------------------------------------------------------------------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table-filters.ts#L191-L215
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTableFilters.setFilterElements
public setFilterElements(filters: FiltersObject) { // 1. if there are filters then set the filters on all the elements if (this.hasFilters(filters)) { // enable reset button this.enableReset(); // set filter elements Object.keys(filters).forEach((key) => this.setFilterElement(key, filters[key].values)); } else { // else reset all filters this.resetAllFilterElements(); } }
/* ------------------ If no args are passed then it resets ------------------ */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table-filters.ts#L222-L233
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTableFilters.setSelectValueIgnoringCase
private setSelectValueIgnoringCase(selectElement: HTMLSelectElement, value: string) { value = value.toLowerCase(); Array.from(selectElement.options).some((option) => { const optionValue = option.value.toLowerCase() || option.text.toLowerCase(); if (optionValue === value) { option.selected = true; this.toggleHighlight(selectElement); return true; } else return false; }); }
/** * Sets the value of a select element, ignoring case, to match the provided value. * * @param {HTMLSelectElement} selectElement - The select element to set the value for. * @param {string} value - The value to set, case insensitive. */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table-filters.ts#L243-L254
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
pageButton
function pageButton(i: number, className: string = "", text?: string): string { return `<button type="button" class="${page === i ? `active ${className}` : `${className}`}" data-page="${i}" title="${className}">${text || i}</button>`; }
/* -------------------------------------------------------------------------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table-pagination.ts#L46-L48
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTableSwitch.checked
get checked(): boolean { return this.hasAttribute("checked"); }
/* -------------------------------------------------------------------------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table-switch.ts#L17-L19
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTableSwitch.addEventListeners
private addEventListeners() { const input = this.querySelector("input"); if (input) { input.addEventListener("change", () => { this.checked = input.checked; this.sendEvent(); }); } }
/* -------------------------------------------------------------------------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table-switch.ts#L43-L51
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTableSwitch.sendEvent
private async sendEvent() { const detail = { checked: this.checked, id: this.id || this.dataset.id, name: this.name, value: this.value }; this.dispatchEvent(new CustomEvent("action-table-switch", { detail, bubbles: true })); }
/* ----------------- Send Event Triggered by checkbox change ---------------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table-switch.ts#L59-L62
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
hasKeys
function hasKeys(obj: any): boolean { return Object.keys(obj).length > 0; }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L5-L7
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTable.sort
get sort(): string { return this.getCleanAttr("sort"); }
// sort attribute to set the sort column
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L78-L80
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTable.direction
get direction(): Direction { const direction = this.getCleanAttr("direction"); return direction === "descending" ? direction : "ascending"; }
// direction attribute to set the sort direction
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L86-L89
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTable.store
get store(): string { return this.hasAttribute("store") ? this.getCleanAttr("store") || "action-table" : ""; }
// store attribute to trigger loading and saving to sort and filters localStorage
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L95-L97
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTable.connectedCallback
public connectedCallback(): void { /* -------------- Init code which requires DOM to be ready -------------- */ console.time("Connected Callback"); // 1. Get table, tbody, rows, and column names in this.cols const table = this.querySelector("table"); // make sure table with thead and tbody exists if (table && table.querySelector("thead th") && table.querySelector("tbody td")) { this.table = table; // casting type as we know it exists due to querySelector above this.tbody = table.querySelector("tbody") as HTMLTableSectionElement; this.rows = Array.from(this.tbody.querySelectorAll("tr")) as Array<HTMLTableRowElement>; // add each row to rowsSet this.rowsSet = new Set(this.rows); } else { throw new Error("Could not find table with thead and tbody"); } // 2. Hide tbody if there is sort or filters; then sort and filter if (this.sort || hasKeys(this.filters)) { this.tbody.style.display = "none"; this.sortAndFilter(); } this.getColumns(); this.addObserver(); console.timeEnd("Connected Callback"); console.log("store:", this.store); }
/* ------------- Fires every time the event is added to the DOM ------------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L142-L172
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTable.observedAttributes
static get observedAttributes(): string[] { return ["sort", "direction", "pagination", "page"]; }
/* -------------------------------------------------------------------------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L178-L180
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTable.setFiltersObject
private setFiltersObject(filters: FiltersObject = {}): void { // If set empty it resets filters to default this.filters = filters; if (this.store) this.setStore({ filters: this.filters }); }
/* -------------------------------------------------------------------------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L204-L210
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTable.setFilters
private setFilters(filters: FiltersObject = {}) { this.setFiltersObject(filters); this.filterTable(); this.appendRows(); }
/* ----------- Used by reset button and action-table-filter event ----------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L213-L217
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTable.addEventListeners
private addEventListeners(): void { // Sort buttons this.addEventListener( "click", (event) => { const el = event.target; // only fire if event target is a button with data-col if (el instanceof HTMLButtonElement && el.dataset.col) { const name = el.dataset.col; let direction: Direction = "ascending"; if (this.sort === name && this.direction === "ascending") { direction = "descending"; } this.sort = name; this.direction = direction; if (this.store) this.setStore({ sort: this.sort, direction: direction }); } }, false ); const findCell = (el: HTMLElement) => { return (el.matches("td") ? el : el.closest("td")) as HTMLTableCellElement; }; // Listens for checkboxes in the table since mutation observer does not support checkbox changes this.addEventListener("change", (event) => { const el = event.target; // only fire if event target is a checkbox in a td; this stops it firing for filters if (el instanceof HTMLInputElement && el.closest("td") && el.type === "checkbox") { // get new content, sort and filter. This works for checkboxes and action-table-switch console.log("event change", el); this.updateCellValues(findCell(el)); } }); // Listens for action-table-filter event from action-table-filters this.addEventListener(`action-table-filter`, (event) => { if (event.detail) { // 1. If detail is defined then add it to the filters object const filters = { ...this.filters, ...event.detail }; // 2. Remove empty filters Object.keys(filters).forEach((key) => { if (filters[key].values.every((value) => value === "")) { delete filters[key]; } }); // 3. Set filters with new filters object this.setFilters(filters); } else { // 3. if no detail than reset filters by calling setFilters with empty object this.setFilters(); } }); // Listens for action-table-update event used by custom elements that want to announce content changes this.addEventListener(`action-table-update`, (event) => { const target = event.target; if (target instanceof HTMLElement) { let values: Partial<ActionTableCellData> = {}; if (typeof event.detail === "string") { values = { sort: event.detail, filter: event.detail }; } else values = event.detail; this.updateCellValues(findCell(target), values); } }); }
/* -------------------------------------------------------------------------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L223-L290
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTable.getStore
private getStore() { try { const ls = localStorage.getItem(this.store); const data = ls && JSON.parse(ls); if (typeof data === "object" && data !== null) { const hasKeys = ["sort", "direction", "filters"].some((key) => key in data); if (hasKeys) return data as ActionTableStore; } return false; } catch (e) { return false; } }
/* -------------------------------------------------------------------------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L296-L308
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTable.setStore
private setStore(data: ActionTableStore) { const lsData = this.getStore() || {}; if (lsData) { data = { ...lsData, ...data }; } localStorage.setItem(this.store, JSON.stringify(data)); }
/* -------------------------------------------------------------------------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L314-L320
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTable.delayUntilNoLongerCalled
private delayUntilNoLongerCalled(callback: () => void) { let timeoutId: number; let isCalling = false; function delayedCallback() { // Execute the callback callback(); // Reset the flag variable to false isCalling = false; } return function () { // If the function is already being called, clear the previous timeout if (isCalling) { clearTimeout(timeoutId); } else { // Set the flag variable to true if the function is not already being called isCalling = true; } // Set a new timeout to execute the delayed callback after 10ms timeoutId = setTimeout(delayedCallback, 10); }; }
/* -------------------------------------------------------------------------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L326-L350
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTable.getColumns
private getColumns(): void { // console.time("getColumns"); // 1. Get column headers // casting type as we know what it is from selector const ths = this.table.querySelectorAll("thead th") as NodeListOf<HTMLTableCellElement>; ths.forEach((th) => { // 2. Column name is based on data-col attribute or results of getCellContent() function const name = (th.dataset.col || this.getCellContent(th)).trim().toLowerCase(); const order = th.dataset.order ? th.dataset.order.split(",") : undefined; // 4. Add column name to cols array this.cols.push({ name, order }); // 5. if the column is sortable then wrap it in a button, and add aria if (!th.hasAttribute("no-sort")) { const button = document.createElement("button"); button.dataset.col = name; button.type = "button"; button.innerHTML = th.innerHTML; th.replaceChildren(button); } }); // 7. add colGroup unless it already exists if (!this.table.querySelector("colgroup")) { // 7.1 create colgroup const colGroup = document.createElement("colgroup"); // 7.2 add col for each column ths.forEach(() => { const col = document.createElement("col"); colGroup.appendChild(col); }); // 7.3 prepend colgroup this.table.prepend(colGroup); } // console.log("action-table cols", this.cols); // 8. Return cols array // console.timeEnd("getColumns"); }
/* -------------------------------------------------------------------------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L376-L415
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTable.getCellContent
private getCellContent(cell: HTMLTableCellElement): string { // 1. get cell content with innerText; set to empty string if null let cellContent: string = (cell.textContent || "").trim(); // 3. if there is no cell content then check... if (!cellContent) { // 3.1 if there is an svg then get title; otherwise return empty string const svg = cell.querySelector("svg"); if (svg instanceof SVGElement) { cellContent = svg.querySelector("title")?.textContent || cellContent; } // 3.2 if checkbox element then get value if checked const checkbox = cell.querySelector("input[type=checkbox]"); if (checkbox instanceof HTMLInputElement && checkbox.checked) { cellContent = checkbox.value; } // 3.3 if custom element with shadowRoot then get text content from shadowRoot const customElement = cell.querySelector(":defined"); if (customElement?.shadowRoot) { cellContent = customElement.shadowRoot.textContent || cellContent; } } return cellContent.trim(); }
/* -------------------------------------------------------------------------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L420-L444
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTable.getCellValues
public getCellValues(cell: HTMLTableCellElement): ActionTableCellData { // 1. If data exists return it; else get it if (this.tableContent.has(cell)) { // console.log("getCellValues: Cached"); // @ts-expect-error has checks for data return this.tableContent.get(cell); } else { const cellValues = this.setCellValues(cell); // console.log("getCellValues: Set", cellValues); return cellValues; } }
/* -------------------------------------------------------------------------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L450-L461
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTable.addObserver
private addObserver() { // Good reference for MutationObserver: https://davidwalsh.name/mutationobserver-api // 1. Create an observer instance const observer = new MutationObserver((mutations) => { // Make sure it only gets content once if there are several changes at the same time // 1.1 sort through all mutations mutations.forEach((mutation) => { let target = mutation.target; // If target is a text node, get its parentNode if (target.nodeType === 3 && target.parentNode) target = target.parentNode; // ignore if this is not an HTMLElement if (!(target instanceof HTMLElement)) return; // Get parent td const td = target.closest("td"); // Only act on HTMLTableCellElements if (td instanceof HTMLTableCellElement) { // If this is a contenteditable element that is focused then only update on blur if (td.hasAttribute("contenteditable") && td === document.activeElement) { // add function for event listener // Make sure that the event listener is only added once if (!td.dataset.edit) { td.dataset.edit = "true"; td.addEventListener("blur", () => { this.updateCellValues(td); }); } } else { // else update this.updateCellValues(td); } } // Ignore tbody changes which happens whenever a new row is added with sort }); }); observer.observe(this.tbody, { childList: true, subtree: true, attributes: true, characterData: true, attributeFilter: ["data-sort", "data-filter"] }); }
/* -------------------------------------------------------------------------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L479-L515
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTable.filterTable
private filterTable(): void { console.log("filterTable", this.filters); // eslint-disable-next-line no-console // console.time("filterTable"); // 1. Save current state of numberOfPages const currentNumberOfPages = this.numberOfPages; const currentRowsVisible = this.rowsSet.size; // 2. get filter value for whole row based on special reserved name "action-table" const filterForWholeRow = this.filters["action-table"]; this.rows.forEach((row) => { // 3.1 set base display value as "" let hide = false; // 3.2 get td cells const cells = row.querySelectorAll("td") as NodeListOf<HTMLTableCellElement>; // 3.3 if filter value for whole row exists then run filter against innerText of entire row content if (filterForWholeRow) { // 3.3.1 build string of all td data-filter values, ignoring checkboxes // console.log("filterForWholeRow"); // TODO: add ability to only filter some columns data-ignore with name or index or data-only attribute const cellsFiltered = Array.from(cells).filter((_c, i) => { console.log("🚀 ~ ActionTable ~ this.cols[i].name:", this.filters["action-table"].cols, this.cols[i].name); return this.filters["action-table"].cols ? this.filters["action-table"].cols.includes(this.cols[i].name.toLowerCase()) : true; }); console.log("🚀 ~ ActionTable ~ this.rows.forEach ~ cellsFiltered:", cellsFiltered); const content = cellsFiltered.map((cell) => (cell.querySelector('input[type="checkbox"]') ? "" : this.getCellValues(cell).filter)).join(" "); if (this.shouldHide(filterForWholeRow, content)) { hide = true; } } // 3.4 if columnName is not action-table then run filter against td cell content cells.forEach((cell, i) => { const filter = this.filters[this.cols[i].name]; if (!filter) return; // console.log("filter cell", filter); if (this.shouldHide(filter, this.getCellValues(cell).filter)) { hide = true; } }); // 3.5 set display if (hide) { this.rowsSet.delete(row); } else { this.rowsSet.add(row); } }); // 4. If number of pages changed, update pagination console.log("currentNumberOfPages", currentNumberOfPages, this.numberOfPages); if (this.numberOfPages !== currentNumberOfPages) { this.dispatch({ numberOfPages: this.numberOfPages }); } if (this.rowsSet.size !== currentRowsVisible) { this.dispatch({ rowsVisible: this.rowsSet.size }); } // console.timeEnd("filterTable"); }
/* ------------- Also triggered by local storage and URL params ------------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L523-L587
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTable.sortTable
private sortTable(columnName = this.sort, direction = this.direction) { if (!this.sort || !direction) return; // eslint-disable-next-line no-console // console.time("sortTable"); columnName = columnName.toLowerCase(); // 1. Get column index from column name const columnIndex = this.cols.findIndex((col) => col.name === columnName); // 2. If column exists and there are rows then sort if (columnIndex >= 0 && this.rows.length > 0) { console.log(`sort by ${columnName} ${direction}`); // 1 Get sort order for column if it exists const sortOrder = this.cols[columnIndex].order; // helper function to return sort order index for row sort const checkSortOrder = (value: string) => { return sortOrder?.includes(value) ? sortOrder.indexOf(value).toString() : value; }; // 2. Sort rows this.rows.sort((r1, r2) => { // 1. If descending sort, swap rows if (direction === "descending") { const temp = r1; r1 = r2; r2 = temp; } // 2. Get content from stored actionTable.sort; If it matches value in sort order exists then return index const a: string = checkSortOrder(this.getCellValues(r1.children[columnIndex] as HTMLTableCellElement).sort); const b: string = checkSortOrder(this.getCellValues(r2.children[columnIndex] as HTMLTableCellElement).sort); // console.log("a", a, "b", b); return this.alphaNumSort(a, b); }); // 3. Add sorted class to columns const colGroupCols = this.querySelectorAll("col"); colGroupCols.forEach((colGroupCol, i) => { if (i === columnIndex) { colGroupCol.classList.add("sorted"); } else { colGroupCol.classList.remove("sorted"); } }); // 3. set aria sorting direction const ths = this.table.querySelectorAll("thead th"); ths.forEach((th, i) => { const ariaSort = i === columnIndex ? direction : "none"; th.setAttribute("aria-sort", ariaSort); }); } // eslint-disable-next-line no-console // console.timeEnd("sortTable"); }
/* ------------- Also triggered by local storage and URL params ------------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L627-L683
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
checkSortOrder
const checkSortOrder = (value: string) => { return sortOrder?.includes(value) ? sortOrder.indexOf(value).toString() : value; };
// helper function to return sort order index for row sort
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L642-L644
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTable.alphaNumSort
public alphaNumSort(a: string, b: string): number { function isNumberOrDate(value: string): number | void { if (!isNaN(Number(value))) { return Number(value); } else if (!isNaN(Date.parse(value))) { return Date.parse(value); } } const aSort = isNumberOrDate(a); const bSort = isNumberOrDate(b); if (aSort && bSort) { return aSort - bSort; } return a.localeCompare(b); }
// Also used by action-table-filter-menu.js when building options menu
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L688-L704
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
ActionTable.appendRows
private appendRows(): void { console.time("appendRows"); // Helper function for hiding rows based on pagination const isActivePage = (i: number): boolean => { // returns if pagination is enabled (> 0) and row is on current page. // For instance if the current page is 2 and pagination is 10 then is greater than 10 and less than or equal to 20 const { pagination, page } = this; return pagination === 0 || (i >= pagination * (page - 1) + 1 && i <= pagination * page); }; // fragment for holding rows const fragment = document.createDocumentFragment(); // This includes both rows hidden by filter and by pagination let currentRowsVisible = 0; // loop through rows to set hide or show this.rows.forEach((row) => { let display = "none"; // if row not hidden by filter if (this.rowsSet.has(row)) { // increment current rows currentRowsVisible++; // if row not hidden by pagination if (isActivePage(currentRowsVisible)) { // set display to show and add row to fragment display = ""; fragment.appendChild(row); } } row.style.display = display; }); // prepend fragment to tbody this.tbody.prepend(fragment); console.timeEnd("appendRows"); if (this.pagination > 0) { // If page is greater than number of pages, set page to number of pages const page = this.checkPage(this.page); if (page !== this.page) { // update this.page this.page = page; // Dispatch current page this.dispatch({ page: page }); } } }
/* --------- Sets row visibility based on sort,filter and pagination -------- */
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L711-L760
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
action-table
github_2023
colinaut
typescript
isActivePage
const isActivePage = (i: number): boolean => { // returns if pagination is enabled (> 0) and row is on current page. // For instance if the current page is 2 and pagination is 10 then is greater than 10 and less than or equal to 20 const { pagination, page } = this; return pagination === 0 || (i >= pagination * (page - 1) + 1 && i <= pagination * page); };
// Helper function for hiding rows based on pagination
https://github.com/colinaut/action-table/blob/302c5f1f00aa26bc2b3e2f1a34f996711900dd7a/src/action-table.ts#L715-L720
302c5f1f00aa26bc2b3e2f1a34f996711900dd7a
Journey.js
github_2023
williamtroup
typescript
setupDefaultGroup
function setupDefaultGroup( groups: any = null ) : void { _groups = Default.getObject( groups, {} as Groups ); _groups[ Constant.DEFAULT_GROUP ] = { json: {} as BindingOptions, keys: [], position: 0 }; }
/* * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Groups * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
https://github.com/williamtroup/Journey.js/blob/d7a2f953051baa3e0bfcfd3bedbb3bbe92c3d432/src/journey.ts#L89-L97
d7a2f953051baa3e0bfcfd3bedbb3bbe92c3d432
Journey.js
github_2023
williamtroup
typescript
renderDialog
function renderDialog() : void { _element_Dialog = DomElement.create( "div", "journey-js-dialog" ); _element_Dialog.style.display = "none"; document.body.appendChild( _element_Dialog ); _element_Dialog_Close_Button = DomElement.create( "button", "close" ); _element_Dialog_Close_Button.onclick = () => onDialogClose(); _element_Dialog.appendChild( _element_Dialog_Close_Button ); ToolTip.add( _element_Dialog_Close_Button, _configuration.text!.closeButtonToolTipText!, _configuration ); _element_Dialog_Title = DomElement.create( "div", "title" ); _element_Dialog.appendChild( _element_Dialog_Title ); _element_Dialog_Description = DomElement.create( "div", "description" ); _element_Dialog.appendChild( _element_Dialog_Description ); _element_Dialog_CheckBox_Container = DomElement.create( "div", "checkbox-container" ); _element_Dialog.appendChild( _element_Dialog_CheckBox_Container ); _element_Dialog_CheckBox_Input = DomElement.createCheckBox( _element_Dialog_CheckBox_Container, _configuration.text!.doNotShowAgainText! ); _element_Dialog_CheckBox_Input.onchange = () => { if ( _configuration.showDoNotShowAgain ) { Trigger.customEvent( _configuration.events!.onDoNotShowAgainChange!, _element_Dialog_CheckBox_Input.checked ); } }; _element_Dialog_ProgressDots = DomElement.create( "div", "progress-dots" ); _element_Dialog.appendChild( _element_Dialog_ProgressDots ); _element_Dialog_ProgressBar = DomElement.create( "div", "progress-bar" ); _element_Dialog.appendChild( _element_Dialog_ProgressBar ); _element_Dialog_ProgressBar_Percentage = DomElement.create( "div", "progress-bar-percentage" ); _element_Dialog_ProgressBar.appendChild( _element_Dialog_ProgressBar_Percentage ); _element_Dialog_ProgressBar_Percentage_Text = DomElement.create( "p", "progress-bar-percentage-text" ); _element_Dialog_ProgressBar_Percentage.appendChild( _element_Dialog_ProgressBar_Percentage_Text ); _element_Dialog_Buttons = DomElement.create( "div", "buttons" ); _element_Dialog.appendChild( _element_Dialog_Buttons ); _element_Dialog_Buttons_Back_Button = DomElement.create( "button", "back" ) as HTMLInputElement; _element_Dialog_Buttons_Back_Button.onclick = onDialogBack; _element_Dialog_Buttons.appendChild( _element_Dialog_Buttons_Back_Button ); _element_Dialog_Buttons_Next_Button = DomElement.create( "button", "next" ) as HTMLInputElement; _element_Dialog_Buttons_Next_Button.onclick = onDialogNext; _element_Dialog_Buttons.appendChild( _element_Dialog_Buttons_Next_Button ); makeDialogMovable(); }
/* * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Render: Dialog * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
https://github.com/williamtroup/Journey.js/blob/d7a2f953051baa3e0bfcfd3bedbb3bbe92c3d432/src/journey.ts#L124-L176
d7a2f953051baa3e0bfcfd3bedbb3bbe92c3d432
Journey.js
github_2023
williamtroup
typescript
makeDialogMovable
function makeDialogMovable() : void { _element_Dialog_Title.onmousedown = onMoveTitleBarMouseDown; _element_Dialog_Title.onmouseup = onMoveTitleBarMouseUp; _element_Dialog_Title.oncontextmenu = onMoveTitleBarMouseUp; document.body.addEventListener( "mousemove", onMoveDocumentMouseMove ); document.body.addEventListener( "mouseleave", onMoveDocumentMouseLeave ); }
/* * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Render: Dialog - Move * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
https://github.com/williamtroup/Journey.js/blob/d7a2f953051baa3e0bfcfd3bedbb3bbe92c3d432/src/journey.ts#L456-L463
d7a2f953051baa3e0bfcfd3bedbb3bbe92c3d432
Journey.js
github_2023
williamtroup
typescript
getElements
function getElements() : void { const tagTypes: string[] = _configuration.domElementTypes as string[]; const tagTypesLength: number = tagTypes.length; for ( let tagTypeIndex: number = 0; tagTypeIndex < tagTypesLength; tagTypeIndex++ ) { const domElements: HTMLCollectionOf<Element> = document.getElementsByTagName( tagTypes[ tagTypeIndex ] ); const elements: HTMLElement[] = [].slice.call( domElements ); const elementsLength: number = elements.length; for ( let elementIndex: number = 0; elementIndex < elementsLength; elementIndex++ ) { if ( !getElement( elements[ elementIndex ] ) ) { break; } } } _groups[ _groups_Current ].keys.sort(); }
/* * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Rendering * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
https://github.com/williamtroup/Journey.js/blob/d7a2f953051baa3e0bfcfd3bedbb3bbe92c3d432/src/journey.ts#L511-L528
d7a2f953051baa3e0bfcfd3bedbb3bbe92c3d432
Journey.js
github_2023
williamtroup
typescript
buildDocumentEvents
function buildDocumentEvents( addEvents: boolean = true ) : void { const documentFunc: Function = addEvents ? document.addEventListener : document.removeEventListener; const windowFunc: Function = addEvents ? window.addEventListener : window.removeEventListener; if ( _configuration.shortcutKeysEnabled ) { documentFunc( "keydown", onWindowKeyDown ); } windowFunc( "resize", onWindowResize ); }
/* * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Document Events * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
https://github.com/williamtroup/Journey.js/blob/d7a2f953051baa3e0bfcfd3bedbb3bbe92c3d432/src/journey.ts#L616-L625
d7a2f953051baa3e0bfcfd3bedbb3bbe92c3d432
Journey.js
github_2023
williamtroup
typescript
getBrowserUrlParameters
function getBrowserUrlParameters() : boolean { let show: boolean = false; if ( _configuration.browserUrlParametersEnabled ) { const url: string = window.location.href; const urlArguments: any = getBrowserUrlArguments( url ); if ( Is.defined( urlArguments.sjOrderId ) ) { const orderId: number = parseInt( urlArguments.sjOrderId, 10 ); if ( !isNaN( orderId ) && orderId <= _groups[ _groups_Current ].keys.length - 1 ) { _groups[ _groups_Current ].position = orderId; } } if ( Is.defined( urlArguments.sjShow ) ) { show = urlArguments.sjShow === "true"; } } return show; }
/* * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Browser URL Parameters * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
https://github.com/williamtroup/Journey.js/blob/d7a2f953051baa3e0bfcfd3bedbb3bbe92c3d432/src/journey.ts#L689-L710
d7a2f953051baa3e0bfcfd3bedbb3bbe92c3d432
Journey.js
github_2023
williamtroup
typescript
getObjectFromString
function getObjectFromString( objectString: any ) : StringToJson { const result: StringToJson = { parsed: true, object: null } as StringToJson; try { if ( Is.definedString( objectString ) ) { result.object = JSON.parse( objectString ); } } catch ( e1: any ) { try { result.object = eval( `(${objectString})` ); if ( Is.definedFunction( result.object ) ) { result.object = result.object(); } } catch ( e2: any ) { if ( !_configuration.safeMode ) { console.error( _configuration.text!.objectErrorText!.replace( "{{error_1}}", e1.message ).replace( "{{error_2}}", e2.message ) ); result.parsed = false; } result.object = null; } } return result; }
/* * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Default Parameter/Option Handling * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
https://github.com/williamtroup/Journey.js/blob/d7a2f953051baa3e0bfcfd3bedbb3bbe92c3d432/src/journey.ts#L737-L767
d7a2f953051baa3e0bfcfd3bedbb3bbe92c3d432
Journey.js
github_2023
williamtroup
typescript
resetDialogPosition
function resetDialogPosition() : void { if ( _public.isOpen() ) { onDialogClose( false ); _groups[ _groups_Current ].position = 0; } }
/* * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Public API Functions: Helpers: Managing Steps * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
https://github.com/williamtroup/Journey.js/blob/d7a2f953051baa3e0bfcfd3bedbb3bbe92c3d432/src/journey.ts#L776-L782
d7a2f953051baa3e0bfcfd3bedbb3bbe92c3d432
vite-plugin-stylex
github_2023
HorusGoul
typescript
getAbsolutePath
function getAbsolutePath(value: string): any { return dirname(require.resolve(join(value, "package.json"))); }
/** * This function is used to resolve the absolute path of a package. * It is needed in projects that use Yarn PnP or are set up within a monorepo. */
https://github.com/HorusGoul/vite-plugin-stylex/blob/b6a179cf370dc8a1a60cadde383d8cba5ba8c67f/apps/storybook-demo/.storybook/main.ts#L9-L11
b6a179cf370dc8a1a60cadde383d8cba5ba8c67f
ts-regex-builder
github_2023
callstack
typescript
isAtomicPattern
function isAtomicPattern(pattern: string): boolean { // Simple char, char class [...] or group (...) return pattern.length === 1 || /^\[[^[\]]*\]$/.test(pattern) || /^\([^()]*\)$/.test(pattern); }
// This is intended to catch only some popular atomic patterns like char classes and groups.
https://github.com/callstack/ts-regex-builder/blob/8918ec1d6dd812d30c620617ceaf675ebc4bcf1b/src/encoder.ts#L70-L73
8918ec1d6dd812d30c620617ceaf675ebc4bcf1b
ts-regex-builder
github_2023
callstack
typescript
escapeText
function escapeText(text: string) { return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string }
// Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions#escaping
https://github.com/callstack/ts-regex-builder/blob/8918ec1d6dd812d30c620617ceaf675ebc4bcf1b/src/encoder.ts#L76-L78
8918ec1d6dd812d30c620617ceaf675ebc4bcf1b
ts-regex-builder
github_2023
callstack
typescript
escapeChar
function escapeChar(text: string): string { // anyOf(']-\\^') return text.replace(/[\]\-\\^]/g, '\\$&'); // "$&" is whole matched string }
/** Escape chars for usage inside char class */
https://github.com/callstack/ts-regex-builder/blob/8918ec1d6dd812d30c620617ceaf675ebc4bcf1b/src/constructs/char-class.ts#L74-L77
8918ec1d6dd812d30c620617ceaf675ebc4bcf1b
cloudfront-hosting-toolkit
github_2023
awslabs
typescript
checkWWW
function checkWWW(domainName: string): boolean { const regex = /^www\./; return regex.test(domainName); }
/** * Checks if the given domain name starts with "www.". * @param domainName The domain name to check. * @returns A boolean value indicating whether the domainName starts with "www." (true) or not (false). */
https://github.com/awslabs/cloudfront-hosting-toolkit/blob/199ce3142ba9f9c28f2849b78df387c8e59a26ec/bin/cli/utils/helper.ts#L645-L648
199ce3142ba9f9c28f2849b78df387c8e59a26ec
cloudfront-hosting-toolkit
github_2023
awslabs
typescript
DeployType.constructor
constructor( scope: Construct, id: string, hostingConfiguration: HostingConfiguration ) { //export function geteDeployIdentifier(stackConfig: IConfiguration) { super(scope, id); if (isRepoConfig(hostingConfiguration)) { const repoUrl = hostingConfiguration.repoUrl; const parsedUrl = parseRepositoryUrl(repoUrl as string); this.deployIdentifier = parsedUrl.repoOwner + " - " + parsedUrl.repoName + "-" + Stack.of(this).region; new CfnOutput(this, "Source", { value: hostingConfiguration.repoUrl, }); } else if (hostingConfiguration.s3bucket) { this.deployIdentifier = hostingConfiguration.s3bucket; new CfnOutput(this, "Source", { value: hostingConfiguration.s3bucket + "/" + hostingConfiguration.s3path, }); } else { console.log("Wrong configuration found. Exiting."); console.log( "Configuration found: " + JSON.stringify(hostingConfiguration) ); process.exit(1); } }
/** * Constructs a deployment stack based on the provided configuration. * Handles Git repository and S3 bucket deployment scenarios, setting up * deployment identifiers and CloudFormation outputs accordingly. * In case of incorrect configuration, logs an error and exits the process. * * @param stackConfig - Configuration object containing deployment details. */
https://github.com/awslabs/cloudfront-hosting-toolkit/blob/199ce3142ba9f9c28f2849b78df387c8e59a26ec/lib/deploy_type.ts#L31-L61
199ce3142ba9f9c28f2849b78df387c8e59a26ec
cloudfront-hosting-toolkit
github_2023
awslabs
typescript
pointsToFile
function pointsToFile(uri: string) { return /\/[^/]+\.[^/]+$/.test(uri); }
// URL rewriting rules
https://github.com/awslabs/cloudfront-hosting-toolkit/blob/199ce3142ba9f9c28f2849b78df387c8e59a26ec/test/uri_rewrite.test.ts#L5-L7
199ce3142ba9f9c28f2849b78df387c8e59a26ec
cloudfront-hosting-toolkit
github_2023
awslabs
typescript
updateURI
function updateURI(uri: string) { // Check for trailing slash and apply rule. if (uri.endsWith("/") && rulePatterns["/$"]) { return "/" + pathToAdd + uri.slice(0, -1) + rulePatterns["/$"]; } // Check if URI doesn't point to a specific file. if (!pointsToFile(uri)) { // If URI doesn't have a trailing slash, apply rule. if (!uri.endsWith("/") && rulePatterns["!file"]) { return "/" + pathToAdd + uri + rulePatterns["!file"]; } // If URI has a trailing slash, apply rule. if (uri.endsWith("/") && rulePatterns["!file/"]) { return "/" + pathToAdd + uri.slice(0, -1) + rulePatterns["!file/"]; } } // Default return return "/" + pathToAdd + uri; }
// Function to determine rule and update the URI
https://github.com/awslabs/cloudfront-hosting-toolkit/blob/199ce3142ba9f9c28f2849b78df387c8e59a26ec/test/uri_rewrite.test.ts#L17-L39
199ce3142ba9f9c28f2849b78df387c8e59a26ec
cloudfront-hosting-toolkit
github_2023
awslabs
typescript
updateURI
function updateURI(uri: string) { // Check for trailing slash and apply rule. if (!pointsToFile(uri)) { return `/${pathToAdd}/index.html`; } return `/${pathToAdd}${uri}`; }
// Function to determine rule and update the URI
https://github.com/awslabs/cloudfront-hosting-toolkit/blob/199ce3142ba9f9c28f2849b78df387c8e59a26ec/test/uri_rewrite.test.ts#L78-L85
199ce3142ba9f9c28f2849b78df387c8e59a26ec
nuxt-tiptap-editor
github_2023
modbender
typescript
ImageUploaderPlugin.newUploadingImageNode
public newUploadingImageNode(attrs: any): Node { // const empty_baseb4 = "data:image/svg+xml,%3Csvg width='20' height='20' xmlns='http://www.w3.org/2000/svg'/%3E\n"; const uploadId = this.config.id() fileCache[uploadId] = attrs.src || attrs['data-src'] return this.view.state.schema.nodes.imagePlaceholder.create({ ...attrs, src: '', // attrs.src, uploadId, }) }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
https://github.com/modbender/nuxt-tiptap-editor/blob/6e10b3c56e89ac672c7e5528bfdb716b79a94933/src/runtime/custom-extensions/extension-image-upload/imageUploader.ts#L185-L194
6e10b3c56e89ac672c7e5528bfdb716b79a94933
drag-and-drop
github_2023
formkit
typescript
checkTouchSupport
function checkTouchSupport() { if (!isBrowser) return false; return "ontouchstart" in window || navigator.maxTouchPoints > 0; }
/** * Function to check if touch support is enabled. * * @returns {boolean} */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L78-L82
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
handleRootPointerdown
function handleRootPointerdown(_e: PointerEvent) { if (state.activeState) setActive(state.activeState.parent, undefined, state); if (state.selectedState) deselect(state.selectedState.nodes, state.selectedState.parent, state); state.selectedState = state.activeState = undefined; }
/** * */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L204-L211
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
handleRootKeydown
function handleRootKeydown(e: KeyboardEvent) { if (e.key === "Escape") { if (state.selectedState) deselect(state.selectedState.nodes, state.selectedState.parent, state); if (state.activeState) setActive(state.activeState.parent, undefined, state); state.selectedState = state.activeState = undefined; } }
/** * Handles the keydown event on the root element. * * @param {KeyboardEvent} e - The keyboard event. */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L232-L242
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
handleRootDragover
function handleRootDragover(e: DragEvent) { if (!isDragState(state)) return; pd(e); }
/** * If we are currently dragging, then let's prevent default on dragover to avoid * the default behavior of the browser on drop. */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L258-L262
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
setActive
function setActive<T>( parent: ParentRecord<T>, newActiveNode: NodeRecord<T> | undefined, state: BaseDragState<T> ) { const activeDescendantClass = parent.data.config.activeDescendantClass; if (state.activeState) { { removeClass([state.activeState.node.el], activeDescendantClass); if (state.activeState.parent.el !== parent.el) state.activeState.parent.el.setAttribute("aria-activedescendant", ""); } } if (!newActiveNode) { state.activeState?.parent.el.setAttribute("aria-activedescendant", ""); state.activeState = undefined; return; } state.activeState = { node: newActiveNode, parent, }; addNodeClass([newActiveNode.el], activeDescendantClass); state.activeState.parent.el.setAttribute( "aria-activedescendant", state.activeState.node.el.id ); }
/** * This function sets the active node as well as removing any classes or * attribute set. * * @param {ParentEventData} data - The parent event data. * @param {NodeRecord} newActiveNode - The new active node. * @param {BaseDragState} state - The current drag state. */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L559-L594
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
deselect
function deselect<T>( nodes: Array<NodeRecord<T>>, parent: ParentRecord<T>, state: BaseDragState<T> ) { const selectedClass = parent.data.config.selectedClass; if (!state.selectedState) return; const iterativeNodes = Array.from(nodes); removeClass( nodes.map((x) => x.el), selectedClass ); for (const node of iterativeNodes) { node.el.setAttribute("aria-selected", "false"); const index = state.selectedState.nodes.findIndex((x) => x.el === node.el); if (index === -1) continue; state.selectedState.nodes.splice(index, 1); } clearLiveRegion(parent); }
/** * This function deselects the nodes. This will clean the prior selected state * as well as removing any classes or attributes set. * * @param {Array<NodeRecord<T>>} nodes - The nodes to deselect. * @param {ParentRecord<T>} parent - The parent record. * @param {BaseDragState<T>} state - The current drag state. */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L604-L631
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
setSelected
function setSelected<T>( parent: ParentRecord<T>, selectedNodes: Array<NodeRecord<T>>, newActiveNode: NodeRecord<T> | undefined, state: BaseDragState<T>, pointerdown = false ) { state.pointerSelection = pointerdown; for (const node of selectedNodes) { node.el.setAttribute("aria-selected", "true"); addNodeClass([node.el], parent.data.config.selectedClass, true); } state.selectedState = { nodes: selectedNodes, parent, }; const selectedItems = selectedNodes.map((x) => x.el.getAttribute("aria-label") ); if (selectedItems.length === 0) { state.selectedState = undefined; clearLiveRegion(parent); return; } setActive(parent, newActiveNode, state); updateLiveRegion( parent, `${selectedItems.join( ", " )} ready for dragging. Use arrow keys to navigate. Press enter to drop ${selectedItems.join( ", " )}.` ); }
/** * This function sets the selected nodes. This will clean the prior selected state * as well as removing any classes or attributes set. * * @param {ParentRecord<T>} parent - The parent record. * @param {Array<NodeRecord<T>>} selectedNodes - The nodes to select. * @param {NodeRecord<T> | undefined} newActiveNode - The new active node. * @param {BaseDragState<T>} state - The current drag state. * @param {boolean} pointerdown - Whether the pointerdown event was triggered. */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L643-L685
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
updateLiveRegion
function updateLiveRegion<T>(parent: ParentRecord<T>, message: string) { const liveRegion = document.querySelector('[data-dnd-live-region="true"]'); if (!liveRegion) return; liveRegion.id = parent.el.id + "-live-region"; liveRegion.textContent = message; }
/** * Update the live region. * * @param {ParentRecord<T>} parent - The parent record. * @param {string} message - The message to update the live region with. * * @returns void */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L695-L703
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
clearLiveRegion
function clearLiveRegion<T>(parent: ParentRecord<T>) { const liveRegion = document.getElementById(parent.el.id + "-live-region"); if (!liveRegion) return; liveRegion.textContent = ""; }
/** * Clear the live region. * * @param {ParentRecord<T>} parent - The parent record. * * @returns void */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L712-L718
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
setup
function setup<T>(parent: HTMLElement, parentData: ParentData<T>): void { parentData.abortControllers.mainParent = addEvents(parent, { keydown: parentEventData(parentData.config.handleParentKeydown), dragover: parentEventData(parentData.config.handleParentDragover), handleParentPointerover: parentData.config.handleParentPointerover, scroll: parentEventData(parentData.config.handleParentScroll), drop: parentEventData(parentData.config.handleParentDrop), hasNestedParent: (e: CustomEvent) => { const parent = parents.get(e.target as HTMLElement); if (!parent) return; parent.nestedParent = e.detail.parent; }, focus: parentEventData(parentData.config.handleParentFocus), }); if ( parentData.config.externalDragHandle && parentData.config.externalDragHandle.el && parentData.config.externalDragHandle.callback ) { parentData.abortControllers.externalDragHandle = addEvents( parentData.config.externalDragHandle.el, { pointerdown: (_e: PointerEvent) => { if ( !parentData.config.externalDragHandle || !parentData.config.externalDragHandle.callback ) return; const draggableItem = parentData.config.externalDragHandle.callback(); if (!isNode(draggableItem)) { console.warn( "No draggable item found from external drag handle callback" ); return; } const nodeData = nodes.get(draggableItem); if (!nodeData) return; const parentNode = draggableItem.parentNode; if (!(parentNode instanceof HTMLElement)) return; const parent = parents.get(parentNode); if (!parent) return; state.pointerDown = { parent: { el: parentNode, data: parent, }, node: { el: draggableItem, data: nodeData, }, validated: true, }; draggableItem.draggable = true; }, } ); } if (parent.id) setAttrs(parent, { role: "listbox", tabindex: "0", "aria-multiselectable": parentData.config.multiDrag ? "true" : "false", "aria-activedescendant": "", "aria-describedby": parent.id + "-live-region", }); }
/** * Setup the parent. * * @param parent - The parent element. * @param parentData - The parent data. * * @returns void */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L977-L1057
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
reapplyDragClasses
function reapplyDragClasses<T>(node: Node, parentData: ParentData<T>) { if (!isDragState(state)) return; const dropZoneClass = isSynthDragState(state) ? parentData.config.synthDropZoneClass : parentData.config.dropZoneClass; if (state.draggedNode.el !== node) return; addNodeClass([node], dropZoneClass, true); }
/** * Reapply the drag classes to the node. * * @param node - The node. * @param parentData - The parent data. * * @returns void */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L1139-L1149
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
nodesMutated
function nodesMutated(mutationList: MutationRecord[]) { // TODO: This could be better, but using it as a way to ignore comments and text if ( mutationList.length === 1 && mutationList[0].addedNodes.length === 1 && !(mutationList[0].addedNodes[0] instanceof HTMLElement) ) return; const parentEl = mutationList[0].target; if (!(parentEl instanceof HTMLElement)) return; const allSelectedAndActiveNodes = document.querySelectorAll( `[aria-selected="true"]` ); const parentData = parents.get(parentEl); if (!parentData) return; for (let x = 0; x < allSelectedAndActiveNodes.length; x++) { const node = allSelectedAndActiveNodes[x]; node.setAttribute("aria-selected", "false"); removeClass([node], parentData.config.selectedClass); } remapNodes(parentEl); }
/** * Called when the nodes of a given parent element are mutated. * * @param mutationList - The list of mutations. * * @returns void * * @internal */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L1191-L1221
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
draggedNodes
function draggedNodes<T>(pointerDown: { parent: ParentRecord<T>; node: NodeRecord<T>; }): Array<NodeRecord<T>> { if (!pointerDown.parent.data.config.multiDrag) { return [pointerDown.node]; } else if (state.selectedState) { return [ pointerDown.node, ...(state.selectedState?.nodes.filter( (x) => x.el !== pointerDown.node.el ) as Array<NodeRecord<T>>), ]; } return []; }
/** * Get the dragged nodes. * * @param pointerDown - The pointer down data. * * @returns The dragged nodes. */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L1421-L1437
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
handleParentScroll
function handleParentScroll<T>(_data: ParentEventData<T>) { if (!isDragState(state)) return; state.emit("scrollStarted", state); if (isSynthDragState(state)) return; state.preventEnter = true; if (scrollTimeout) clearTimeout(scrollTimeout); scrollTimeout = setTimeout(() => { state.preventEnter = false; state.emit("scrollEnded", state); }, 100); }
/** * Handle the parent scroll. * * @param data - The parent event data. * * @returns void */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L1446-L1462
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
initSynthDrag
function initSynthDrag<T>( node: NodeRecord<T>, parent: ParentRecord<T>, e: PointerEvent, _state: BaseDragState<T>, draggedNodes: Array<NodeRecord<T>> ): SynthDragState<T> { const config = parent.data.config; let dragImage: HTMLElement | undefined; let display = node.el.style.display; let result = undefined; if (config.synthDragImage) { result = config.synthDragImage(node, parent, e, draggedNodes); dragImage = result.dragImage; dragImage.setAttribute("popover", "manual"); dragImage.id = "dnd-dragged-node-clone"; display = dragImage.style.display; Object.assign(dragImage.style, { position: "absolute", zIndex: 9999, pointerEvents: "none", margin: 0, willChange: "transform", overflow: "hidden", display: "none", }); } else { if (!config.multiDrag || draggedNodes.length === 1) { dragImage = node.el.cloneNode(true) as HTMLElement; dragImage.id = "dnd-dragged-node-clone"; display = dragImage.style.display; dragImage.setAttribute("popover", "manual"); Object.assign(dragImage.style, { position: "absolute", height: node.el.getBoundingClientRect().height + "px", width: node.el.getBoundingClientRect().width + "px", overflow: "hidden", margin: 0, willChange: "transform", pointerEvents: "none", zIndex: 9999, }); } else { const wrapper = document.createElement("div"); wrapper.setAttribute("popover", "manual"); for (const node of draggedNodes) { const clonedNode = node.el.cloneNode(true) as HTMLElement; clonedNode.style.pointerEvents = "none"; clonedNode.style.margin = "0"; wrapper.append(clonedNode); } display = wrapper.style.display; wrapper.id = "dnd-dragged-node-clone"; dragImage = wrapper; Object.assign(dragImage.style, { display: "flex", flexDirection: "column", position: "absolute", overflow: "hidden", margin: 0, padding: 0, pointerEvents: "none", zIndex: 9999, }); } } dragImage.style.position = "absolute"; parent.el.appendChild(dragImage); dragImage.showPopover(); const synthDragStateProps = { clonedDraggedEls: [], clonedDraggedNode: dragImage, draggedNodeDisplay: display, synthDragScrolling: false, synthDragging: true, rootScrollWidth: document.scrollingElement?.scrollWidth, rootScrollHeight: document.scrollingElement?.scrollHeight, rootOverScrollBehavior: document.documentElement.style.overscrollBehavior, rootTouchAction: document.documentElement.style.touchAction, }; document.documentElement.style.overscrollBehavior = "none"; document.documentElement.style.touchAction = "none"; const synthDragState = setDragState({ ...dragStateProps( node, parent, e, draggedNodes, result?.offsetX, result?.offsetY ), ...synthDragStateProps, }) as SynthDragState<T>; synthDragState.clonedDraggedNode.style.display = synthDragState.draggedNodeDisplay || ""; return synthDragState; }
/** * Initialize the synth drag. * * @param node - The node. * @param parent - The parent. * @param e - The pointer event. * @param _state - The drag state. * @param draggedNodes - The dragged nodes. * * @returns The synth drag state. */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L2178-L2305
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
handleNodeDragenter
function handleNodeDragenter<T>( data: NodeDragEventData<T>, _state: DragState<T> ) { pd(data.e); }
/** * Handle the node drag enter. * * @param data - The node drag event data. * @param _state - The drag state. * * @returns void */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L2571-L2576
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
handleNodeDragleave
function handleNodeDragleave<T>( data: NodeDragEventData<T>, _state: DragState<T> ) { pd(data.e); }
/** * Handle the node drag leave. * * @param data - The node drag event data. * @param _state - The drag state. * * @returns void */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L2586-L2591
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
isScrollX
function isScrollX<T>( el: HTMLElement, e: PointerEvent, style: CSSStyleDeclaration, rect: DOMRect, state: SynthDragState<T> ): { left: boolean; right: boolean } { const threshold = 0.1; if (el === document.scrollingElement) { const canScrollLeft = el.scrollLeft > 0; const canScrollRight = el.scrollLeft + window.innerWidth < (state.rootScrollWidth || 0); return { right: canScrollRight && e.clientX > el.clientWidth * (1 - threshold), left: canScrollLeft && e.clientX < el.clientWidth * threshold, }; } if ( (style.overflowX === "auto" || style.overflowX === "scroll") && el !== document.body && el !== document.documentElement ) { const scrollWidth = el.scrollWidth; const offsetWidth = el.offsetWidth; const scrollLeft = el.scrollLeft; return { right: e.clientX > rect.left + offsetWidth * (1 - threshold) && scrollLeft < scrollWidth - offsetWidth, left: e.clientX < rect.left + offsetWidth * threshold && scrollLeft > 0, }; } return { right: false, left: false, }; }
/** * Check if the element is scrollable on the x axis. * * @param el - The element. * @param e - The event. * @param style - The style. * @param rect - The rect. * @param state - The state. * * @returns void */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L3023-L3064
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
isScrollY
function isScrollY( el: HTMLElement, e: PointerEvent, style: CSSStyleDeclaration, rect: DOMRect ): { up: boolean; down: boolean } { const threshold = 0.1; if (el === document.scrollingElement) { return { down: e.clientY > el.clientHeight * (1 - threshold), up: e.clientY < el.clientHeight * threshold, }; } if ( (style.overflowY === "auto" || style.overflowY === "scroll") && el !== document.body && el !== document.documentElement ) { const scrollHeight = el.scrollHeight; const offsetHeight = el.offsetHeight; const scrollTop = el.scrollTop; return { down: e.clientY > rect.top + offsetHeight * (1 - threshold) && scrollTop < scrollHeight - offsetHeight, up: e.clientY < rect.top + offsetHeight * threshold && scrollTop > 0, }; } return { down: false, up: false, }; }
/** * Check if the element is scrollable on the y axis. * * @param el - The element. * @param e - The event. * @param style - The style. * @param rect - The rect. * * @returns void */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L3076-L3112
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
scrollX
function scrollX<T>( el: HTMLElement, e: PointerEvent, state: SynthDragState<T>, right = true ) { state.preventEnter = true; const incr = right ? 5 : -5; function scroll(el: HTMLElement) { el.scrollBy({ left: incr }); moveNode(e, state, incr, 0); state.animationFrameIdX = requestAnimationFrame(scroll.bind(null, el)); } state.animationFrameIdX = requestAnimationFrame(scroll.bind(null, el)); }
/** * Scroll the element on the x axis. * * @param el - The element. * @param e - The event. * @param state - The state. * @param right - Whether to scroll right. * * @returns void */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L3124-L3143
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
scrollY
function scrollY<T>( el: Element, e: PointerEvent, state: SynthDragState<T>, up = true ) { state.preventEnter = true; const incr = up ? -5 : 5; function scroll() { el.scrollBy({ top: incr }); moveNode(e, state, 0, incr); state.animationFrameIdY = requestAnimationFrame(scroll); } state.animationFrameIdY = requestAnimationFrame(scroll); }
/** * Scroll the element on the y axis. * * @param el - The element. * @param e - The event. * @param state - The state. * @param up - Whether to scroll up. * * @returns void */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L3155-L3174
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
handleSynthScroll
function handleSynthScroll<T>( coordinates: { x: number; y: number }, e: PointerEvent, state: SynthDragState<T> ) { cancelSynthScroll(state); const scrollables: Record<"x" | "y", HTMLElement | null> = { x: null, y: null, }; const els = document.elementsFromPoint(coordinates.x, coordinates.y); for (const el of els) { if (scrollables.x && scrollables.y) break; if (!(el instanceof HTMLElement)) continue; const rect = el.getBoundingClientRect(); const style = window.getComputedStyle(el); if (!scrollables.x) { const { left, right } = isScrollX(el, e, style, rect, state); if (left || right) { scrollables.x = el; scrollX(el, e, state, right); } } if (!scrollables.y) { const { up, down } = isScrollY(el, e, style, rect); if (up || down) { scrollables.y = el; scrollY(el, e, state, up); } } } }
/** * Handle the synth scroll. * * @param coordinates - The coordinates. * @param e - The event. * @param state - The state. * * @returns void */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/index.ts#L3185-L3228
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
getValues
function getValues(parent: HTMLElement): Array<any> { const values = parentValues.get(parent); if (!values) { console.warn("No values found for parent element"); return []; } return "value" in values ? values.value : values; }
/** * Returns the values of the parent element. * * @param parent - The parent element. * * @returns The values of the parent element. */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/vue/index.ts#L21-L31
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
setValues
function setValues(newValues: Array<any>, parent: HTMLElement): void { const currentValues = parentValues.get(parent); // Only update reactive values. If static, let's not update. if (currentValues && "value" in currentValues) currentValues.value = newValues; //else if (currentValues) parentValues.set(parent, newValues); }
/** * Sets the values of the parent element. * * @param parent - The parent element. * * @param newValues - The new values for the parent element. * * @returns void */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/vue/index.ts#L42-L49
f987d198587ffa9b7b937fdc2375f88b4497a4dd
drag-and-drop
github_2023
formkit
typescript
handleParent
function handleParent<T>( config: Partial<VueParentConfig<T>>, values: Ref<Array<T>> | Array<T> ) { return (parent: HTMLElement) => { parentValues.set(parent, values); initParent({ parent, getValues, setValues, config: { ...config, }, }); }; }
/** * Sets the HTMLElement parent to weakmap with provided values and calls * initParent. * * @param config - The config of the parent. * * @param values - The values of the parent element. * */
https://github.com/formkit/drag-and-drop/blob/f987d198587ffa9b7b937fdc2375f88b4497a4dd/src/vue/index.ts#L111-L127
f987d198587ffa9b7b937fdc2375f88b4497a4dd
ai-group-tabs
github_2023
MichaelYuhe
typescript
htmlToElement
const htmlToElement = <T extends ChildNode>(html: string) => { const template = document.createElement("template"); html = html.trim(); // Never return a text node of whitespace as the result template.innerHTML = html; return template.content.firstChild as T; };
/** * DO NOT USE FOR USER INPUT * * See https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro/35385518#35385518 */
https://github.com/MichaelYuhe/ai-group-tabs/blob/36100d3f93028e72faa498b419be6ff226becd76/src/components/toast.ts#L9-L14
36100d3f93028e72faa498b419be6ff226becd76
gzm-design
github_2023
LvHuaiSheng
typescript
config
const config=({mode})=>{ return{ plugins: [ vue(), // 自动按需引入组件 AutoImport({ resolvers: [ ArcoResolver({ // importStyle: 'less', }), ], imports: ['vue', 'vue-router', 'pinia', '@vueuse/core'], eslintrc: { enabled: true, }, }), Components({ directoryAsNamespace: true, resolvers: [ // 自动引入arco ArcoResolver({ // importStyle: 'less', resolveIcons: true, }), ], }), UnoCSS(), createSvgIconsPlugin({ // 指定需要缓存的图标文件夹 iconDirs: [resolve(process.cwd(), 'src/assets/icons')], // 指定symbolId格式 symbolId: 'icon-[dir]-[name]', }), ], resolve: { alias: { '@': resolve(__dirname, './src'), }, }, } }
// https://vitejs.dev/config/
https://github.com/LvHuaiSheng/gzm-design/blob/6dc166eb6fd4b39cde64544180242ab2dce4ff4c/vite.config.ts#L10-L50
6dc166eb6fd4b39cde64544180242ab2dce4ff4c