repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
hsr-optimizer | github_2023 | fribbels | typescript | generateSubStats | function generateSubStats(grade: RelicGrade, sub1: subStat, sub2?: subStat, sub3?: subStat, sub4?: subStat): subStat[] {
const substats = [{
stat: sub1.stat,
value: sub1.value,
rolls: {
high: SubStatValues[sub1.stat][grade as 2 | 3 | 4 | 5].high,
mid: SubStatValues[sub1.stat][grade as 2 | 3 | 4 | 5].mid,
low: SubStatValues[sub1.stat][grade as 2 | 3 | 4 | 5].low,
},
addedRolls: 0,
}]
if (sub2) substats.push({
stat: sub2.stat,
value: sub2.value,
rolls: {
high: SubStatValues[sub2.stat][grade as 2 | 3 | 4 | 5].high,
mid: SubStatValues[sub2.stat][grade as 2 | 3 | 4 | 5].mid,
low: SubStatValues[sub2.stat][grade as 2 | 3 | 4 | 5].low,
},
addedRolls: 0,
})
if (sub3) substats.push({
stat: sub3.stat,
value: sub3.value,
rolls: {
high: SubStatValues[sub3.stat][grade as 2 | 3 | 4 | 5].high,
mid: SubStatValues[sub3.stat][grade as 2 | 3 | 4 | 5].mid,
low: SubStatValues[sub3.stat][grade as 2 | 3 | 4 | 5].low,
},
addedRolls: 0,
})
if (sub4) substats.push({
stat: sub4.stat,
value: sub4.value,
rolls: {
high: SubStatValues[sub4.stat][grade as 2 | 3 | 4 | 5].high,
mid: SubStatValues[sub4.stat][grade as 2 | 3 | 4 | 5].mid,
low: SubStatValues[sub4.stat][grade as 2 | 3 | 4 | 5].low,
},
addedRolls: 0,
})
return substats
} | /**
* used to generate substats for fakeRelic() more easily
* @param grade relic rarity
* @param sub1 substat line 1
* @param sub2 substat line 2
* @param sub3 substat line 3
* @param sub4 substat line 4
* @returns array of substats for a relic
*/ | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicScorerPotential.ts#L832-L874 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | getHandlingCase | function getHandlingCase(scoringMetadata: ScoringMetadata) {
const substats = scoringMetadata.sortedSubstats
if (substats[0][1] == 0) return relicPotentialCases.NONE
if (substats[1][1] == 0) return relicPotentialCases.SINGLE_STAT
if (substats[2][1] > 0) return relicPotentialCases.NORMAL
if (substats[1][0] == Stats.HP && substats[0][0] == Stats.HP_P) return relicPotentialCases.HP
if (substats[1][0] == Stats.HP_P && substats[0][0] == Stats.HP) return relicPotentialCases.HP
if (substats[1][0] == Stats.ATK && substats[0][0] == Stats.ATK_P) return relicPotentialCases.ATK
if (substats[1][0] == Stats.ATK_P && substats[0][0] == Stats.ATK) return relicPotentialCases.ATK
if (substats[1][0] == Stats.DEF && substats[0][0] == Stats.DEF_P) return relicPotentialCases.DEF
if (substats[1][0] == Stats.DEF_P && substats[0][0] == Stats.DEF) return relicPotentialCases.DEF
return relicPotentialCases.NORMAL
} | /**
* Analyses the scoringMetadata to determine in which way it should be handled
* @param scoringMetadata The scoring metadata for the character
*/ | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicScorerPotential.ts#L880-L892 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | findHighestWeight | function findHighestWeight(substats: subStat[] | Stat[], scoringMetadata: ScoringMetadata) {
let index = 0
let weight = 0
let stat = '' as SubStats
for (let i = 0; i < substats.length; i++) {
const newWeight = scoringMetadata.stats[substats[i].stat]
if (newWeight > weight || i == 0) {
weight = newWeight
index = i
stat = substats[i].stat as SubStats
}
}
return {
index,
weight,
stat,
}
} | /**
* @param substats array of substats to search across
* @param scoringMetadata character scoring metadata
* @returns lowest index in the substats array of highest weight substat
*/ | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicScorerPotential.ts#L899-L916 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | findLowestWeight | function findLowestWeight(substats: subStat[] | Stat[], scoringMetadata: ScoringMetadata) {
let index = 0
let weight = 1
let stat = '' as SubStats
for (let i = 0; i < substats.length; i++) {
const newWeight = scoringMetadata.stats[substats[i].stat]
if (newWeight < weight || i == 0) {
weight = newWeight
index = i
stat = substats[i].stat as SubStats
}
}
return {
index,
weight,
stat,
}
} | /**
* @param substats array of substats to search across
* @param scoringMetadata character scoring metadata
* @returns lowest index in the substats array of lowest weight substat
*/ | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicScorerPotential.ts#L923-L940 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | maxEnhance | function maxEnhance(grade: 2 | 3 | 4 | 5) {
switch (grade) {
case 2:
return 6
case 3:
return 9
case 4:
return 12
default:
return 15
}
} | /**
* converts grade to (max) enhance while preserving type check compliance
*/ | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicScorerPotential.ts#L945-L956 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | getMainStatWeight | function getMainStatWeight(relic: Relic, scoringMetadata: ScoringMetadata) {
if (!Utils.hasMainStat(relic.part)) {
return 0
}
if (scoringMetadata.parts[relic.part].includes(relic.main.stat)) {
return 1
}
return scoringMetadata.stats[relic.main.stat]
} | // Hands/Head have no weight. Optimal main stats are 1.0 weight, and anything else inherits the substat weight. | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/relics/relicScorerPotential.ts#L973-L981 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | getImageUrl | function getImageUrl(name: string) {
return new URL(BASE_PATH + `/assets` + name, import.meta.url).href
} | // let baseUrl = process.env.PUBLIC_URL // Local testing; | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/rendering/assets.ts#L8-L10 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | applyScoringFunction | const applyScoringFunction: ScoringFunction = (result: SimulationResult, penalty = true) => {
if (!result) return
result.unpenalizedSimScore = result.x.COMBO_DMG
result.penaltyMultiplier = calculatePenaltyMultiplier(result, metadata, benchmarkScoringParams)
result.simScore = result.unpenalizedSimScore * (penalty ? result.penaltyMultiplier : 1)
} | // Generate scoring function | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/scoring/characterScorer.ts#L199-L205 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | generatePartialSimulations | function generatePartialSimulations(
character: Character,
metadata: SimulationMetadata,
simulationSets: SimulationSets,
originalSim: Simulation,
) {
const forceSpdBoots = false // originalBaseSpeed - baselineSimResult.x[Stats.SPD] > 2.0 * 2 * 5 // 3 min spd rolls per piece
const feetParts: string[] = forceSpdBoots ? [Stats.SPD] : metadata.parts[Parts.Feet]
const forceErrRope = originalSim.request.simLinkRope == Stats.ERR && metadata.errRopeEidolon != null && character.form.characterEidolon >= metadata.errRopeEidolon
const ropeParts: string[] = forceErrRope ? [Stats.ERR] : metadata.parts[Parts.LinkRope]
const { relicSet1, relicSet2, ornamentSet } = simulationSets
const results: PartialSimulationWrapper[] = []
for (const body of metadata.parts[Parts.Body]) {
for (const feet of feetParts) {
for (const planarSphere of metadata.parts[Parts.PlanarSphere]) {
for (const linkRope of ropeParts) {
const request: SimulationRequest = {
name: '',
simRelicSet1: relicSet1,
simRelicSet2: relicSet2,
simOrnamentSet: ornamentSet,
simBody: body,
simFeet: feet,
simPlanarSphere: planarSphere,
simLinkRope: linkRope,
stats: {
[Stats.HP_P]: 0,
[Stats.ATK_P]: 0,
[Stats.DEF_P]: 0,
[Stats.HP]: 0,
[Stats.ATK]: 0,
[Stats.DEF]: 0,
[Stats.SPD]: 0,
[Stats.CR]: 0,
[Stats.CD]: 0,
[Stats.EHR]: 0,
[Stats.RES]: 0,
[Stats.BE]: 0,
},
}
const simulation: Simulation = {
name: '',
key: '',
simType: StatSimTypes.SubstatRolls,
request: request,
}
const partialSimulationWrapper: PartialSimulationWrapper = {
simulation: simulation,
finalSpeed: 0,
speedRollsDeduction: 0,
}
results.push(partialSimulationWrapper)
}
}
}
}
return results
} | // Generate all main stat possibilities | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/scoring/characterScorer.ts#L832-L893 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | simulateOriginalCharacter | function simulateOriginalCharacter(
displayRelics: RelicBuild,
simulationSets: SimulationSets,
simulationForm: Form,
context: OptimizerContext,
scoringParams: ScoringParams,
simulationFlags: SimulationFlags,
mainStatMultiplier = 1,
overwriteSets = false,
) {
const relicsByPart: RelicBuild = TsUtils.clone(displayRelics)
Object.values(Parts).forEach((part) => relicsByPart[part].part = part)
const { relicSetNames, ornamentSetName } = calculateSetNames(relicsByPart)
const originalSimRequest = convertRelicsToSimulation(relicsByPart, relicSetNames[0], relicSetNames[1], ornamentSetName, scoringParams.quality, scoringParams.speedRollValue)
if (overwriteSets) {
const { relicSet1, relicSet2, ornamentSet } = simulationSets
originalSimRequest.simRelicSet1 = relicSet1
originalSimRequest.simRelicSet2 = relicSet2
originalSimRequest.simOrnamentSet = ornamentSet
}
const originalSim: Simulation = {
name: '',
key: '',
simType: StatSimTypes.SubstatRolls,
request: originalSimRequest,
}
const originalSimResult = runSimulations(simulationForm, context, [originalSim], {
...scoringParams,
substatRollsModifier: (rolls: number) => rolls,
mainStatMultiplier: mainStatMultiplier,
simulationFlags: simulationFlags,
})[0]
originalSim.result = originalSimResult
return {
originalSimResult,
originalSim,
}
} | // TODO: why is this function used twice | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/scoring/characterScorer.ts#L933-L977 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | compareSameTypeSubstat | function compareSameTypeSubstat(oldSubstat: Stat, newSubstat: Stat) {
let oldValue: number
let newValue: number
if (Utils.isFlat(oldSubstat.stat)) {
// Flat atk/def/hp/spd values we floor to an int
oldValue = Math.floor(oldSubstat.value)
newValue = Math.floor(newSubstat.value)
} else {
// Other values we match to 1 decimal point due to OCR
oldValue = Utils.precisionRound(Utils.truncate10ths(oldSubstat.value))
newValue = Utils.precisionRound(Utils.truncate10ths(newSubstat.value))
}
if (oldValue == newValue) return 0
if (oldValue < newValue) return 1
return -1
} | // -1: old > new, 0: old == new, 1, new > old | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/state/db.ts#L1210-L1226 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | setRelic | function setRelic(relic: Relic) {
const relicsById = window.store.getState().relicsById
relicsById[relic.id] = relic
window.store.getState().setRelicsById(relicsById)
} | /**
* Sets the provided relic in the application's state.
*/ | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/state/db.ts#L1242-L1246 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | getLightConeOverrideCenter | function getLightConeOverrideCenter(): Record<string, number> {
return {
20000: 270,
20001: 220,
20002: 160,
20003: 310,
20004: 180,
20005: 210,
20006: 390,
20007: 180,
20008: 220,
20009: 230,
20010: 250,
20011: 390,
20012: 300,
20013: 220,
20014: 210,
20015: 270,
20016: 270,
20017: 410,
20018: 190,
20019: 230,
20020: 250,
21000: 150,
21001: 290,
21002: 160,
21003: 195,
21004: 150,
21005: 250,
21006: 170,
21007: 240,
21008: 140,
21009: 140,
21010: 160,
21011: 115,
21012: 160,
21013: 200,
21014: 140,
21015: 125,
21016: 180,
21017: 140,
21018: 210,
21019: 180,
21020: 230,
21021: 180,
21022: 300,
21023: 240,
21024: 140,
21025: 125,
21026: 160,
21027: 200,
21028: 250,
21029: 160,
21030: 305,
21031: 190,
21032: 245,
21033: 140,
21034: 220,
21035: 300,
21036: 220,
21037: 210,
21038: 130,
21039: 220,
21040: 150,
21041: 160,
21042: 200,
21043: 220,
21044: 150,
21045: 160,
21046: 145,
21047: 145,
21048: 250,
22000: 275,
22001: 220,
22002: 160,
22003: 185,
23000: 140,
23001: 150,
23002: 160,
23003: 250,
23004: 140,
23005: 150,
23006: 200,
23007: 210,
23008: 160,
23009: 130,
23010: 180,
23011: 180,
23012: 300,
23013: 180,
23014: 120,
23015: 190,
23016: 130,
23017: 190,
23018: 170,
23019: 270,
23020: 220,
23021: 150,
23022: 190,
23023: 140,
23024: 80,
23025: 125,
23026: 180,
23027: 140,
23028: 150,
23029: 140,
23031: 145,
23032: 180,
23033: 175,
23034: 175, // TODO
23035: 175, // TODO
24000: 170,
24001: 270,
24002: 170,
24003: 250,
24004: 270,
// TODO
23037: 150,
23036: 180,
21052: 200,
21051: 180,
21050: 170,
20022: 305,
20021: 320,
23038: 210,
23039: 165,
24005: 300,
}
} | // Standardized to 450 width | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/state/metadata.ts#L737-L868 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | saveFile | const saveFile = async (blob: Blob, suggestedName: string) => {
// Feature detection. The API needs to be supported and the app not run in an iframe.
const supportsFileSystemAccess
= 'showSaveFilePicker' in window
&& (() => {
try {
return window.self === window.top
} catch {
return false
}
})()
// If the File System Access API is supported…
if (supportsFileSystemAccess) {
try {
// Show the file save dialog.
const handle = await window.showSaveFilePicker({
suggestedName,
types: [{
description: 'JSON',
accept: { 'text/json': ['.json'] },
}],
})
// Write the blob to the file.
const writable = await handle.createWritable()
await writable.write(blob)
await writable.close()
} catch (err: unknown) {
TsUtils.consoleWarnWrapper(err)
}
} else {
// Fallback if the File System Access API is not supported…
// Create the blob URL.
const blobURL = URL.createObjectURL(blob)
// Create the `<a download>` element and append it invisibly.
const a = document.createElement('a')
a.href = blobURL
a.download = suggestedName
a.style.display = 'none'
document.body.append(a)
// Programmatically click the element.
a.click()
// Revoke the blob URL and remove the element.
setTimeout(() => {
URL.revokeObjectURL(blobURL)
a.remove()
}, 1000)
}
} | // https://web.dev/patterns/files/save-a-file | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/tabs/tabImport/ImportTab.tsx#L17-L64 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | getNumber | function getNumber(value: number, defaultValue: number, divide: number = 0) {
if (value == null) {
return defaultValue
}
divide = divide || 1
return value / divide
} | // Convert a display value to its internal form value | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/tabs/tabOptimizer/optimizerForm/optimizerFormTransform.ts#L325-L331 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | unsetMin | function unsetMin(value: number, percent: boolean = false) {
if (value == undefined) return undefined
return value == 0 ? undefined : parseFloat((percent ? value * 100 : value).toFixed(3))
} | // Display a number, rendering 0 as blank | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/tabs/tabOptimizer/optimizerForm/optimizerFormTransform.ts#L334-L337 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | unsetMax | function unsetMax(value: number, percent: boolean = false) {
if (value == undefined) return undefined
return value == Constants.MAX_INT ? undefined : parseFloat((percent ? value * 100 : value).toFixed(3))
} | // Display a number, rendering MAX_INT as blank | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/tabs/tabOptimizer/optimizerForm/optimizerFormTransform.ts#L340-L343 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | cloneTeammate | function cloneTeammate(teammate: Teammate | undefined) {
if (!teammate?.characterId) return defaultTeammate() as Teammate
return {
characterId: teammate.characterId ?? null,
characterEidolon: teammate.characterEidolon ?? null,
lightCone: teammate.lightCone ?? null,
lightConeSuperimposition: teammate.lightConeSuperimposition ?? null,
} as Teammate
} | // Clone teammate and replace undefined values with null to force the form to keep the null | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/tabs/tabOptimizer/optimizerForm/optimizerFormTransform.ts#L346-L355 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | redistributePityCumulative | function redistributePityCumulative(pity: number, warpCap: number, distribution: number[]) {
const redistributedCumulative: number[] = []
for (let i = 0; i < pity; i++) {
redistributedCumulative[i] = 0
}
for (let i = pity; i < warpCap; i++) {
redistributedCumulative[i] = i == 0 ? distribution[i] : redistributedCumulative[i - 1] + distribution[i]
}
const diff = 1 - redistributedCumulative[warpCap - 1]
for (let i = pity; i < warpCap; i++) {
redistributedCumulative[i] += diff * (redistributedCumulative[i])
}
return redistributedCumulative
} | // We have the cumulative distribution of warp results for 0 pity counter. | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/tabs/tabWarp/warpCalculatorController.ts#L282-L297 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | getNextSuccessIndex | function getNextSuccessIndex(cumulative: number[], warpCap: number, pity: number) {
const rand = Math.random() * cumulative[warpCap - 1]
return getIndex(rand, cumulative, pity)
} | // Adjust the random number to account for pity counter since anything before the pity is impossible | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/tabs/tabWarp/warpCalculatorController.ts#L300-L303 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | getIndex | function getIndex(random: number, cumulativeDistribution: number[], pity: number) {
let left = pity
let right = cumulativeDistribution.length - 1
while (left < right) {
const mid = Math.floor((left + right) / 2)
if (random > cumulativeDistribution[mid]) {
left = mid + 1
} else {
right = mid
}
}
return left
} | // Binary search the index of random number within the distribution | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/tabs/tabWarp/warpCalculatorController.ts#L306-L320 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
hsr-optimizer | github_2023 | fribbels | typescript | animation | function animation(currentTime: number) {
const elapsedTime = currentTime - startTime
const progress = Math.min(elapsedTime / duration, 1)
// Ease-in-out function
const easeInOut = progress < 0.5
? 2 * progress * progress
: 1 - Math.pow(-2 * progress + 2, 2) / 2
parent.scrollTo(0, startPosition + distance * easeInOut)
if (elapsedTime < duration) {
requestAnimationFrame(animation)
}
} | // Smooth scroll animation | https://github.com/fribbels/hsr-optimizer/blob/dcd874755b98536e01ee8cc1c099aa8f55dd2d5e/src/lib/utils/TsUtils.ts#L114-L128 | dcd874755b98536e01ee8cc1c099aa8f55dd2d5e |
lowstorage | github_2023 | good-lly | typescript | lowstorage.checkIfStorageExists | async checkIfStorageExists(): Promise<boolean> {
try {
const exists = await this._s3.bucketExists();
return !!exists;
} catch (error: any) {
if (error.message.includes('Not Found')) {
return false;
}
throw new lowstorageError(`${error.message}`, lowstorage_ERROR_CODES.S3_OPERATION_ERROR);
}
} | /**
* Check if a bucket exists.
* @returns {Promise<boolean>} True if the bucket exists, false otherwise.
* @throws {lowstorageError} If there's an error.
*/ | https://github.com/good-lly/lowstorage/blob/d009434f995ba3b3869666d3f68a09738b891345/src/lowstorage.ts#L136-L146 | d009434f995ba3b3869666d3f68a09738b891345 |
lowstorage | github_2023 | good-lly | typescript | lowstorage.createStorage | async createStorage(): Promise<boolean> {
try {
const exists = await this.checkIfStorageExists();
if (!exists) {
const createdBucket = await this._s3.createBucket();
return !!createdBucket;
}
return exists;
} catch (error: any) {
if (error instanceof lowstorageError) {
throw error;
}
throw new lowstorageError(`${error.message}`, lowstorage_ERROR_CODES.S3_OPERATION_ERROR);
}
} | /**
* Create a new storage bucket if it doesn't exist.
* @returns {Promise<boolean>} A Promise that resolves to true if the bucket was created or already exists, false otherwise.
* @throws {lowstorageError} If there's an error.
*/ | https://github.com/good-lly/lowstorage/blob/d009434f995ba3b3869666d3f68a09738b891345/src/lowstorage.ts#L153-L167 | d009434f995ba3b3869666d3f68a09738b891345 |
lowstorage | github_2023 | good-lly | typescript | lowstorage.listCollections | async listCollections(): Promise<string[]> {
try {
const listed = await this._s3.list(DELIMITER, this._dirPrefix);
if (Array.isArray(listed)) {
// filter only the collection name, not the full path and remove files without COL_SUFFIX
const filtered = listed.filter((entry) => entry.key.endsWith(COL_SUFFIX));
return filtered.map((entry) => entry.key.slice(this._dirPrefix.length + 1, -COL_SUFFIX.length));
} else if (typeof listed === 'object' && listed !== null && 'keyCount' in listed && listed.keyCount === '0') {
return [];
}
return [];
} catch (error: any) {
if (error instanceof S3OperationError) {
throw error;
}
throw new lowstorageError(`${error.message}`, lowstorage_ERROR_CODES.LIST_COLLECTIONS_ERROR);
}
} | /**
* List all collections.
* @returns {Promise<string[]>} An array of collection names.
* @throws {S3OperationError} If there's an error during S3 operation.
* @throws {lowstorageError} If there's an error.
*/ | https://github.com/good-lly/lowstorage/blob/d009434f995ba3b3869666d3f68a09738b891345/src/lowstorage.ts#L176-L193 | d009434f995ba3b3869666d3f68a09738b891345 |
lowstorage | github_2023 | good-lly | typescript | lowstorage.collectionExists | async collectionExists(colName: string = ''): Promise<boolean> {
try {
_hasColName(colName);
const exists = await this._s3.fileExists(`${this._dirPrefix}${DELIMITER}${colName}${COL_SUFFIX}`);
return !!exists;
} catch (error: any) {
if (error.message.includes('Not Found')) {
return false;
}
throw new lowstorageError(`${error.message}`, lowstorage_ERROR_CODES.COLLECTION_NOT_FOUND);
}
} | /**
* Check if a collection exists.
* @param {string} colName - The name of the collection.
* @returns {Promise<boolean>} True if the collection exists, false otherwise.
* @throws {lowstorageError} If there's an error.
*/ | https://github.com/good-lly/lowstorage/blob/d009434f995ba3b3869666d3f68a09738b891345/src/lowstorage.ts#L201-L212 | d009434f995ba3b3869666d3f68a09738b891345 |
lowstorage | github_2023 | good-lly | typescript | lowstorage.createCollection | async createCollection(colName: string = '', data: any[] = []): Promise<Collection> {
try {
_hasColName(colName);
const exists = await this.collectionExists(colName);
if (!exists) {
if (data.length > 0) {
const packr = new Packr();
await this._s3.put(`${this._dirPrefix}${DELIMITER}${colName}${COL_SUFFIX}`, packr.pack(data));
} else {
await this._s3.put(`${this._dirPrefix}${DELIMITER}${colName}${COL_SUFFIX}`, EMPTY_DATA);
}
return this.collection(colName);
}
throw new lowstorageError(`Collection ${colName} already exists`, lowstorage_ERROR_CODES.COLLECTION_EXISTS);
} catch (error: any) {
throw new lowstorageError(`${error.message}`, lowstorage_ERROR_CODES.CREATE_COLLECTION_ERROR);
}
} | /**
* Create a new collection.
* @param {string} colName - The name of the collection.
* @param {Array} [data=[]] - The initial data for the collection.
* @returns {Promise<Collection>} A Promise that resolves to a Collection object.
* @throws {lowstorageError} If there's an error.
*/ | https://github.com/good-lly/lowstorage/blob/d009434f995ba3b3869666d3f68a09738b891345/src/lowstorage.ts#L221-L238 | d009434f995ba3b3869666d3f68a09738b891345 |
lowstorage | github_2023 | good-lly | typescript | lowstorage.removeCollection | async removeCollection(colName: string = ''): Promise<boolean> {
try {
_hasColName(colName);
const deleted = await this._s3.delete(`${this._dirPrefix}${DELIMITER}${colName}${COL_SUFFIX}`);
const exists = await this.collectionExists(colName);
if (!deleted || exists) {
return false;
}
if (deleted && !exists) {
return true;
}
if (typeof exists !== 'boolean') {
throw new lowstorageError(`Failed to delete collection ${colName}`, lowstorage_ERROR_CODES.S3_OPERATION_ERROR);
}
throw new lowstorageError(`Collection ${colName} does not exist`, lowstorage_ERROR_CODES.REMOVE_COLLECTION_ERROR);
} catch (error: any) {
if (error instanceof S3OperationError) {
throw error;
}
throw new lowstorageError(`Failed to remove collection: ${error.message}`, lowstorage_ERROR_CODES.REMOVE_COLLECTION_ERROR);
}
} | /**
* Remove a collection.
* @param {string} colName - The name of the collection.
* @returns {Promise<boolean>} A Promise that resolves to true if the collection is removed, false otherwise.
* @throws {lowstorageError} If there's an error.
*/ | https://github.com/good-lly/lowstorage/blob/d009434f995ba3b3869666d3f68a09738b891345/src/lowstorage.ts#L246-L267 | d009434f995ba3b3869666d3f68a09738b891345 |
lowstorage | github_2023 | good-lly | typescript | lowstorage.collection | async collection(colName: string = '', autoCreate: boolean = true): Promise<Collection> {
try {
_hasColName(colName);
const colPath = `${this._dirPrefix}${DELIMITER}${colName}${COL_SUFFIX}`;
const exists = await this._s3.fileExists(colPath);
if (!exists) {
if (!autoCreate) {
throw new lowstorageError(`Collection ${colName} does not exist`, lowstorage_ERROR_CODES.COLLECTION_NOT_FOUND);
}
// TODO: check if this is the right way to handle empty data
await this._s3.put(colPath, EMPTY_DATA);
}
return new Collection(colName, this._s3, this._dirPrefix);
} catch (error: any) {
throw new lowstorageError(`${error.message}`, lowstorage_ERROR_CODES.COLLECTION_NOT_FOUND);
}
} | /**
* Get or create a collection.
* @param {string} colName - The name of the collection.
* @param {boolean} [autoCreate=true] - Whether to automatically create the collection if it doesn't exist.
* @returns {Promise<Collection>} A Promise that resolves to a Collection object.
* @throws {lowstorageError} If there's an error.
*/ | https://github.com/good-lly/lowstorage/blob/d009434f995ba3b3869666d3f68a09738b891345/src/lowstorage.ts#L276-L292 | d009434f995ba3b3869666d3f68a09738b891345 |
lowstorage | github_2023 | good-lly | typescript | lowstorage.s3 | s3 = (): S3 => {
return this._s3;
} | /**
* Get the S3 instance associated with the lowstorage instance.
* @returns {S3} The S3 instance. Use this to perform S3 operations. Check for ultralight-s3 for more details.
*/ | https://github.com/good-lly/lowstorage/blob/d009434f995ba3b3869666d3f68a09738b891345/src/lowstorage.ts | d009434f995ba3b3869666d3f68a09738b891345 |
lowstorage | github_2023 | good-lly | typescript | Collection.insert | async insert(doc: Object | Array<Object>): Promise<Object[]> {
try {
if (doc === undefined || doc === null) {
throw new lowstorageError(`Document is required for insert`, lowstorage_ERROR_CODES.INSERT_ERROR);
}
if (typeof doc !== 'object' && !Array.isArray(doc)) {
throw new DocumentValidationError(
`${MOD_NAME}: Document must be an object or an array`,
lowstorage_ERROR_CODES.DOCUMENT_VALIDATION_ERROR,
);
}
const items = !Array.isArray(doc) ? [doc] : doc;
const data = await this._loadData();
for (let item of items) {
if (typeof item !== 'object' || item === null) {
throw new DocumentValidationError(
`${MOD_NAME}: Invalid input: input must be an object or an array of objects`,
lowstorage_ERROR_CODES.DOCUMENT_VALIDATION_ERROR,
);
}
item._id = item._id || (await generateUUID());
data.push(item);
}
const success = await this._saveData(data);
if (!success) {
throw new S3OperationError(`${MOD_NAME}: Failed to insert document`, lowstorage_ERROR_CODES.S3_OPERATION_ERROR);
}
return items;
} catch (error: any) {
throw new lowstorageError(`Insert operation failed: ${error.message}`, lowstorage_ERROR_CODES.INSERT_ERROR);
}
} | /**
* Insert a document into the collection.
* @param {Object|Array} doc - The document to insert.
* @returns {Promise<Array>} A Promise that resolves to the array of inserted document(s).
* @throws {lowstorageError} If there's an error.
*/ | https://github.com/good-lly/lowstorage/blob/d009434f995ba3b3869666d3f68a09738b891345/src/lowstorage.ts#L450-L481 | d009434f995ba3b3869666d3f68a09738b891345 |
lowstorage | github_2023 | good-lly | typescript | Collection.find | async find(query: Object = {}, options: Object = {}): Promise<Object[]> {
try {
if (query === undefined || query === null) {
throw new lowstorageError(`Query is required for update`, lowstorage_ERROR_CODES.MISSING_ARGUMENT);
}
const data = await this._loadData();
const start = (options as { skip?: number }).skip !== undefined ? parseInt(String((options as { skip?: number }).skip), 10) : 0;
const end =
(options as { limit?: number }).limit !== undefined
? start + parseInt(String((options as { limit?: number }).limit), 10)
: undefined;
const filteredData = data.filter((doc) => matchesQuery(doc, query)).slice(start, end);
return filteredData;
} catch (error: any) {
throw new lowstorageError(`Find operation failed: ${error.message}`, lowstorage_ERROR_CODES.FIND_ERROR);
}
} | /**
* Find documents in the collection.
* @param {Object} [query={}] - The query to filter documents.
* @param {Object} [options={}] - The options for pagination.
* @param {number} [options.skip=0] - The number of documents to skip. Default is 0.
* @param {number} [options.limit=undefined] - The maximum number of documents to return. Default is undefined, which means no limit.
* @returns {Promise<Array>} A Promise that resolves to an array of matching documents.
* @throws {lowstorageError} If there's an error.
*/ | https://github.com/good-lly/lowstorage/blob/d009434f995ba3b3869666d3f68a09738b891345/src/lowstorage.ts#L492-L508 | d009434f995ba3b3869666d3f68a09738b891345 |
lowstorage | github_2023 | good-lly | typescript | Collection.findOne | async findOne(query: Object = {}): Promise<Object | null> {
try {
if (query === null) {
throw new lowstorageError(`${MOD_NAME}: Query cannot be null`, lowstorage_ERROR_CODES.INVALID_ARGUMENT);
}
const result = await this.find(query, { limit: 1 });
return result[0] || null;
} catch (error: any) {
if (error instanceof lowstorageError) {
throw error;
}
throw new lowstorageError(`${MOD_NAME}: FindOne operation failed: ${error.message}`, lowstorage_ERROR_CODES.FIND_ONE_ERROR);
}
} | /**
* Find the first document in the collection that matches the query.
* @param {Object} [query={}] - The query to filter documents.
* @returns {Promise<Object|null>} A Promise that resolves to the first matching document or null if no match is found.
* @throws {lowstorageError} If there's an error.
*/ | https://github.com/good-lly/lowstorage/blob/d009434f995ba3b3869666d3f68a09738b891345/src/lowstorage.ts#L516-L529 | d009434f995ba3b3869666d3f68a09738b891345 |
lowstorage | github_2023 | good-lly | typescript | Collection.update | async update(query: Object = {}, update: Object = {}, options: Object = {}): Promise<number> {
try {
if (query === undefined || query === null || update === undefined || update === null) {
throw new lowstorageError(`Query and update values are required for update`, lowstorage_ERROR_CODES.MISSING_ARGUMENT);
}
const data = await this._loadData();
if (data.length === 0) return 0;
let updatedCount = 0;
for (let i = 0; i < data.length; i++) {
if (matchesQuery(data[i], query)) {
const updatedDoc = { ...data[i], ...update };
data[i] = updatedDoc;
updatedCount++;
}
}
if (updatedCount > 0) {
const success = await this._saveData(data);
if (!success) {
throw new S3OperationError(`${MOD_NAME}: Failed to update document`, lowstorage_ERROR_CODES.S3_OPERATION_ERROR);
}
} else if (options && 'upsert' in options && options.upsert) {
// If upsert is true, we need to insert the document
const success = await this.insert(update);
if (!success) {
throw new S3OperationError(`${MOD_NAME}: Failed to update document`, lowstorage_ERROR_CODES.S3_OPERATION_ERROR);
}
updatedCount = 1;
}
return updatedCount;
} catch (error: any) {
if (error instanceof S3OperationError) {
throw error;
}
throw new lowstorageError(`Update operation failed: ${error.message}`, lowstorage_ERROR_CODES.UPDATE_ERROR);
}
} | /**
* Update a single document in the collection that matches the query.
* @param {Object} [query={}] - The query to filter the document to update.
* @param {Object} [update={}] - The update operations to apply to the matching document.
* @returns {Promise<number>} A Promise that resolves to number of documents updated.
* @throws {lowstorageError} If the updateOne operation fails.
* @throws {DocumentValidationError} If the updated document is invalid.
* @throws {S3OperationError} If the S3 operation fails.
*/ | https://github.com/good-lly/lowstorage/blob/d009434f995ba3b3869666d3f68a09738b891345/src/lowstorage.ts#L540-L576 | d009434f995ba3b3869666d3f68a09738b891345 |
lowstorage | github_2023 | good-lly | typescript | Collection.updateOne | async updateOne(query: Record<string, any> = {}, update: Record<string, any> = {}, options: Record<string, any> = {}): Promise<number> {
try {
if (query === undefined || query === null || update === undefined || update === null) {
throw new lowstorageError(`Query is required`, lowstorage_ERROR_CODES.MISSING_ARGUMENT);
}
const data = await this._loadData();
if (data.length === 0) return 0;
const docIndex = data.findIndex((doc) => matchesQuery(doc, query));
if (docIndex !== -1) {
const updatedDoc = { ...data[docIndex], ...update };
data[docIndex] = updatedDoc;
const success = await this._saveData(data);
if (!success) {
throw new S3OperationError(`${MOD_NAME}: Failed to update document`, lowstorage_ERROR_CODES.S3_OPERATION_ERROR);
}
return 1;
}
if (options && 'upsert' in options && options.upsert) {
// If upsert is true, we need to insert the document
const success = await this.insert(update);
if (!success) {
throw new S3OperationError(`${MOD_NAME}: Failed to update document`, lowstorage_ERROR_CODES.S3_OPERATION_ERROR);
}
return 1;
}
return 0;
} catch (error: any) {
throw new lowstorageError(`UpdateOne operation failed: ${error.message}`, lowstorage_ERROR_CODES.UPDATE_ONE_ERROR);
}
} | /**
* Update a single document in the collection that matches the query.
* @param {Object} [query={}] - The query to filter the document to update.
* @param {Object} [update={}] - The update operations to apply to the matching document.
* @returns {Promise<number>} A Promise that resolves to 1 if a document was updated, 0 otherwise.
/**
* Update a single document in the collection that matches the query.
* @throws {lowstorageError} If the updateOne operation fails.
* @throws {DocumentValidationError} If the updated document is invalid.
* @throws {S3OperationError} If the S3 operation fails.
*/ | https://github.com/good-lly/lowstorage/blob/d009434f995ba3b3869666d3f68a09738b891345/src/lowstorage.ts#L589-L619 | d009434f995ba3b3869666d3f68a09738b891345 |
lowstorage | github_2023 | good-lly | typescript | Collection.delete | async delete(query: Object = {}): Promise<number> {
try {
if (query === undefined || query === null) {
throw new lowstorageError(`Query is required`, lowstorage_ERROR_CODES.MISSING_ARGUMENT);
}
const data = await this._loadData();
if (data.length === 0) return 0;
const initialLength = data.length;
const newData = data.filter((doc) => !matchesQuery(doc, query));
const success = await this._saveData(newData);
if (!success) {
throw new S3OperationError(`${MOD_NAME}: Failed to delete document`, lowstorage_ERROR_CODES.S3_OPERATION_ERROR);
}
return initialLength - newData.length;
} catch (error: any) {
if (error instanceof S3OperationError) {
throw error;
}
throw new lowstorageError(`Delete operation failed: ${error.message}`, lowstorage_ERROR_CODES.DELETE_ERROR);
}
} | /**
* Delete documents from the collection.
* @param {Object} [query={}] - The query to filter documents to delete.
* @returns {Promise<number>} A Promise that resolves to the number of documents deleted.
* @throws {lowstorageError} If the delete operation fails.
* @throws {S3OperationError} If the S3 operation fails.
*/ | https://github.com/good-lly/lowstorage/blob/d009434f995ba3b3869666d3f68a09738b891345/src/lowstorage.ts#L628-L649 | d009434f995ba3b3869666d3f68a09738b891345 |
lowstorage | github_2023 | good-lly | typescript | Collection.deleteAll | async deleteAll(): Promise<number> {
try {
const data = await this._loadData();
const initialLength = data.length;
const success = await this._saveData([]);
if (!success) {
throw new S3OperationError(`${MOD_NAME}: Failed to delete document`, lowstorage_ERROR_CODES.S3_OPERATION_ERROR);
}
return initialLength;
} catch (error: any) {
if (error instanceof S3OperationError) {
throw error;
}
throw new lowstorageError(`Delete operation failed: ${error.message}`, lowstorage_ERROR_CODES.DELETE_ERROR);
}
} | /**
* Delete all documents from the collection.
* @returns {Promise<number>} A Promise that resolves to the number of documents deleted.
* @throws {lowstorageError} If the delete operation fails.
* @throws {S3OperationError} If the S3 operation fails.
*/ | https://github.com/good-lly/lowstorage/blob/d009434f995ba3b3869666d3f68a09738b891345/src/lowstorage.ts#L657-L672 | d009434f995ba3b3869666d3f68a09738b891345 |
lowstorage | github_2023 | good-lly | typescript | Collection.count | async count(query: Object = {}): Promise<number> {
try {
const data = await this.find(query);
return data.length;
} catch (error: any) {
throw new lowstorageError(`Count operation failed: ${error.message}`, lowstorage_ERROR_CODES.COUNT_ERROR);
}
} | /**
* Count the number of documents in the collection.
* @param {Object} [query={}] - The query to filter documents.
* @returns {Promise<number>} A Promise that resolves to the number of documents in the collection.
* @throws {lowstorageError} If the count operation fails.
*/ | https://github.com/good-lly/lowstorage/blob/d009434f995ba3b3869666d3f68a09738b891345/src/lowstorage.ts#L680-L687 | d009434f995ba3b3869666d3f68a09738b891345 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | pathResolve | const pathResolve = (dir = ".", metaUrl = import.meta.url) => {
// 当前文件目录的绝对路径
const currentFileDir = dirname(fileURLToPath(metaUrl));
// build 目录的绝对路径
const buildDir = resolve(currentFileDir, "build");
// 解析的绝对路径
const resolvedPath = resolve(currentFileDir, dir);
// 检查解析的绝对路径是否在 build 目录内
if (resolvedPath.startsWith(buildDir)) {
// 在 build 目录内,返回当前文件路径
return fileURLToPath(metaUrl);
}
// 不在 build 目录内,返回解析后的绝对路径
return resolvedPath;
}; | /**
* @description 根据可选的路径片段生成一个新的绝对路径
* @param dir 路径片段,默认`build`
* @param metaUrl 模块的完整`url`,如果在`build`目录外调用必传`import.meta.url`
*/ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/build/utils.ts#L22-L36 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | wrapperEnv | const wrapperEnv = (envConf: Recordable): ViteEnv => {
// 默认值
const ret: ViteEnv = {
VITE_PORT: 8848,
VITE_PUBLIC_PATH: "",
VITE_ROUTER_HISTORY: "",
VITE_CDN: false,
VITE_HIDE_HOME: "false",
VITE_COMPRESSION: "none",
VITE_APP_BASE_API: "",
VITE_APP_BASE_URL: "",
VITE_APP_BASE_URL_WS: "",
VITE_APP_BASE_WS: ""
};
for (const envName of Object.keys(envConf)) {
let realName = envConf[envName].replace(/\\n/g, "\n");
realName =
realName === "true" ? true : realName === "false" ? false : realName;
if (envName === "VITE_PORT") {
realName = Number(realName);
}
ret[envName] = realName;
if (typeof realName === "string") {
process.env[envName] = realName;
} else if (typeof realName === "object") {
process.env[envName] = JSON.stringify(realName);
}
}
return ret;
}; | /** 处理环境变量 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/build/utils.ts#L51-L82 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | getPackageSize | const getPackageSize = options => {
const { folder = "dist", callback, format = true } = options;
readdir(folder, (err, files: string[]) => {
if (err) throw err;
let count = 0;
const checkEnd = () => {
++count == files.length &&
callback(format ? formatBytes(sum(fileListTotal)) : sum(fileListTotal));
};
files.forEach((item: string) => {
stat(`${folder}/${item}`, async (err, stats) => {
if (err) throw err;
if (stats.isFile()) {
fileListTotal.push(stats.size);
checkEnd();
} else if (stats.isDirectory()) {
getPackageSize({
folder: `${folder}/${item}/`,
callback: checkEnd
});
}
});
});
files.length === 0 && callback(0);
});
}; | /** 获取指定文件夹中所有文件的总大小 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/build/utils.ts#L87-L112 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | pauseResume | function pauseResume() {
if (state.paused) {
resume();
state.paused = false;
} else {
pause();
state.paused = true;
}
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/components/ReCountTo/src/normal/index.tsx#L65-L73 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | reset | function reset() {
state.startTime = null;
cancelAnimationFrame(state.rAF);
state.displayValue = formatNumber(props.startVal);
} | // eslint-disable-next-line @typescript-eslint/no-unused-vars | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/components/ReCountTo/src/normal/index.tsx#L87-L91 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | addDialog | const addDialog = (options: DialogOptions) => {
const open = () =>
dialogStore.value.push(Object.assign(options, { visible: true }));
if (options?.openDelay) {
useTimeoutFn(() => {
open();
}, options.openDelay);
} else {
open();
}
}; | /** 打开弹框 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/components/ReDialog/index.ts#L16-L26 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | closeDialog | const closeDialog = (options: DialogOptions, index: number, args?: any) => {
dialogStore.value[index].visible = false;
options.closeCallBack && options.closeCallBack({ options, index, args });
const closeDelay = options?.closeDelay ?? 200;
useTimeoutFn(() => {
dialogStore.value.splice(index, 1);
}, closeDelay);
}; | /** 关闭弹框 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/components/ReDialog/index.ts#L29-L37 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | updateDialog | const updateDialog = (value: any, key = "title", index = 0) => {
dialogStore.value[index][key] = value;
}; | /**
* @description 更改弹框自身属性值
* @param value 属性值
* @param key 属性,默认`title`
* @param index 弹框索引(默认`0`,代表只有一个弹框,对于嵌套弹框要改哪个弹框的属性值就把该弹框索引赋给`index`)
*/ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/components/ReDialog/index.ts#L45-L47 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | closeAllDialog | const closeAllDialog = () => {
dialogStore.value = [];
}; | /** 关闭所有弹框 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/components/ReDialog/index.ts#L50-L52 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | flipDown | const flipDown = (front: any, back: any): void => {
flip("down", front, back);
}; | // 下翻牌 | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/components/ReFlop/src/filpper.tsx#L49-L51 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | flipUp | const flipUp = (front: any, back: any): void => {
flip("up", front, back);
}; | // 上翻牌 | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/components/ReFlop/src/filpper.tsx#L54-L56 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | setFront | function setFront(text: number): void {
frontTextFromData.value = text;
} | // 设置前牌文字 | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/components/ReFlop/src/filpper.tsx#L59-L61 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | setBack | const setBack = (text: number): void => {
backTextFromData.value = text;
}; | // 设置后牌文字 | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/components/ReFlop/src/filpper.tsx#L64-L66 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | drawLogoWithImage | const drawLogoWithImage = (image: HTMLImageElement) => {
ctx.drawImage(image, logoXY, logoXY, logoWidth, logoWidth);
}; | // 使用image绘制可以避免某些跨域情况 | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/components/ReQrcode/src/index.tsx#L160-L162 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | drawLogoWithCanvas | const drawLogoWithCanvas = (image: HTMLImageElement) => {
const canvasImage = document.createElement("canvas");
canvasImage.width = logoXY + logoWidth;
canvasImage.height = logoXY + logoWidth;
const imageCanvas = canvasImage.getContext("2d");
if (!imageCanvas || !ctx) return;
imageCanvas.drawImage(image, logoXY, logoXY, logoWidth, logoWidth);
canvasRoundRect(ctx)(logoXY, logoXY, logoWidth, logoWidth, logoRadius);
if (!ctx) return;
const fillStyle = ctx.createPattern(canvasImage, "no-repeat");
if (fillStyle) {
ctx.fillStyle = fillStyle;
ctx.fill();
}
}; | // 使用canvas绘制以获得更多的功能 | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/components/ReQrcode/src/index.tsx#L164-L178 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | throwError | function throwError(message: string) {
throw new TypeError(message);
} | /**
* 输出错误信息
* @param message 错误信息
*/ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/components/ReTypeit/src/index.tsx#L19-L21 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | getBrowserLanguage | function getBrowserLanguage() {
return navigator.language;
} | /**
* 获取浏览器默认语言
*/ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/components/ReTypeit/src/index.tsx#L26-L28 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | responsiveStorageNameSpace | const responsiveStorageNameSpace = () => getConfig().ResponsiveStorageNameSpace; | /** 本地响应式存储的命名空间 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/config/index.ts#L53-L53 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | setLayoutThemeColor | function setLayoutThemeColor(
theme = getConfig().Theme ?? "light",
isClick = true
) {
layoutTheme.value.theme = theme;
toggleTheme({
scopeName: `layout-theme-${theme}`
});
// 如果非isClick,保留之前的themeColor
const storageThemeColor = $storage.layout.themeColor;
$storage.layout = {
layout: layout.value,
theme,
darkMode: dataTheme.value,
sidebarStatus: $storage.layout?.sidebarStatus,
epThemeColor: $storage.layout?.epThemeColor,
themeColor: isClick ? theme : storageThemeColor,
overallStyle: overallStyle.value
};
if (theme === "default" || theme === "light") {
setEpThemeColor(getConfig().EpThemeColor);
} else {
const colors = themeColors.value.find(v => v.themeColor === theme);
setEpThemeColor(colors.color);
}
} | /** 设置导航主题色 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/layout/hooks/useDataThemeChange.ts#L52-L78 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | setEpThemeColor | const setEpThemeColor = (color: string) => {
useEpThemeStoreHook().setEpThemeColor(color);
document.documentElement.style.setProperty("--el-color-primary", color);
for (let i = 1; i <= 2; i++) {
setPropertyPrimary("dark", i, color);
}
for (let i = 1; i <= 9; i++) {
setPropertyPrimary("light", i, color);
}
}; | /** 设置 `element-plus` 主题色 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/layout/hooks/useDataThemeChange.ts#L88-L97 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | dataThemeChange | function dataThemeChange(overall?: string) {
overallStyle.value = overall;
if (useEpThemeStoreHook().epTheme === "light" && dataTheme.value) {
setLayoutThemeColor("default", false);
} else {
setLayoutThemeColor(useEpThemeStoreHook().epTheme, false);
}
if (dataTheme.value) {
document.documentElement.classList.add("dark");
} else {
if ($storage.layout.themeColor === "light") {
setLayoutThemeColor("light", false);
}
document.documentElement.classList.remove("dark");
}
} | /** 浅色、深色整体风格切换 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/layout/hooks/useDataThemeChange.ts#L100-L116 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | onReset | function onReset() {
removeToken();
storageLocal().clear();
const { Grey, Weak, MultiTagsCache, EpThemeColor, Layout } = getConfig();
useAppStoreHook().setLayout(Layout);
setEpThemeColor(EpThemeColor);
useMultiTagsStoreHook().multiTagsCacheChange(MultiTagsCache);
toggleClass(Grey, "html-grey", document.querySelector("html"));
toggleClass(Weak, "html-weakness", document.querySelector("html"));
router.push("/login");
useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
resetRouter();
} | /** 清空缓存并返回登录页 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/layout/hooks/useDataThemeChange.ts#L119-L131 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | changeTitle | function changeTitle(meta: routeMetaType) {
const Title = getConfig().Title;
if (Title) document.title = `${transformI18n(meta.title)} | ${Title}`;
else document.title = transformI18n(meta.title);
} | /** 动态title */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/layout/hooks/useNav.ts#L92-L96 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | logout | function logout() {
useUserStoreHook().logOut();
} | /** 退出登录 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/layout/hooks/useNav.ts#L99-L101 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | isRemaining | function isRemaining(path: string) {
return remainingPaths.includes(path);
} | /** 判断路径是否参与菜单 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/layout/hooks/useNav.ts#L140-L142 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | getLogo | function getLogo() {
return new URL("/logo.svg", import.meta.url).href;
} | /** 获取`logo` */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/layout/hooks/useNav.ts#L145-L147 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | onMouseenter | function onMouseenter(index) {
if (index) activeIndex.value = index;
if (unref(showModel) === "smart") {
if (hasClass(instance.refs["schedule" + index][0], "schedule-active"))
return;
toggleClass(true, "schedule-in", instance.refs["schedule" + index][0]);
toggleClass(false, "schedule-out", instance.refs["schedule" + index][0]);
} else {
if (hasClass(instance.refs["dynamic" + index][0], "is-active")) return;
toggleClass(true, "card-in", instance.refs["dynamic" + index][0]);
toggleClass(false, "card-out", instance.refs["dynamic" + index][0]);
}
} | /** 鼠标移入添加激活样式 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/layout/hooks/useTag.ts#L169-L181 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | onMouseleave | function onMouseleave(index) {
activeIndex.value = -1;
if (unref(showModel) === "smart") {
if (hasClass(instance.refs["schedule" + index][0], "schedule-active"))
return;
toggleClass(false, "schedule-in", instance.refs["schedule" + index][0]);
toggleClass(true, "schedule-out", instance.refs["schedule" + index][0]);
} else {
if (hasClass(instance.refs["dynamic" + index][0], "is-active")) return;
toggleClass(false, "card-in", instance.refs["dynamic" + index][0]);
toggleClass(true, "card-out", instance.refs["dynamic" + index][0]);
}
} | /** 鼠标移出恢复默认样式 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/layout/hooks/useTag.ts#L184-L196 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | getObjectKeys | function getObjectKeys(obj) {
const stack = [];
const keys: Set<string> = new Set();
stack.push({ obj, key: "" });
while (stack.length > 0) {
const { obj, key } = stack.pop();
for (const k in obj) {
const newKey = key ? `${key}.${k}` : k;
if (obj[k] && isObject(obj[k])) {
stack.push({ obj: obj[k], key: newKey });
} else {
keys.add(newKey);
}
}
}
return keys;
} | /** 获取对象中所有嵌套对象的key键,并将它们用点号分割组成字符串 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/plugins/i18n.ts#L38-L59 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | toCorrectRoute | function toCorrectRoute() {
whiteList.includes(to.fullPath) ? next(_from.fullPath) : next();
} | /** 如果已经登录并存在登录信息后不能跳转到路由白名单,而是继续保持在当前页面 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/router/index.ts#L130-L132 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | ascending | function ascending(arr: any[]) {
arr.forEach((v, index) => {
// 当rank不存在时,根据顺序自动创建,首页路由永远在第一位
if (handRank(v)) v.meta.rank = index + 2;
});
return arr.sort(
(a: { meta: { rank: number } }, b: { meta: { rank: number } }) => {
return a?.meta.rank - b?.meta.rank;
}
);
} | /** 按照路由中meta下的rank等级升序来排序路由 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/router/utils.ts#L44-L54 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | filterTree | function filterTree(data: RouteComponent[]) {
const newTree = cloneDeep(data).filter(
(v: { meta: { showLink: boolean } }) => v.meta?.showLink !== false
);
newTree.forEach(
(v: { children }) => v.children && (v.children = filterTree(v.children))
);
return newTree;
} | /** 过滤meta中showLink为false的菜单 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/router/utils.ts#L57-L65 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | filterChildrenTree | function filterChildrenTree(data: RouteComponent[]) {
const newTree = cloneDeep(data).filter((v: any) => v?.children?.length !== 0);
newTree.forEach(
(v: { children }) => v.children && (v.children = filterTree(v.children))
);
return newTree;
} | /** 过滤children长度为0的的目录,当目录下没有菜单时,会过滤此目录,目录没有赋予roles权限,当目录下只要有一个菜单有显示权限,那么此目录就会显示 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/router/utils.ts#L68-L74 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | isOneOfArray | function isOneOfArray(a: Array<string>, b: Array<string>) {
return Array.isArray(a) && Array.isArray(b)
? intersection(a, b).length > 0
? true
: false
: true;
} | /** 判断两个数组彼此是否存在相同值 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/router/utils.ts#L77-L83 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | filterNoPermissionTree | function filterNoPermissionTree(data: RouteComponent[]) {
const currentRoles =
storageLocal().getItem<DataInfo<number>>(userKey)?.roles ?? [];
const newTree = cloneDeep(data).filter((v: any) =>
isOneOfArray(v.meta?.roles, currentRoles)
);
newTree.forEach(
(v: any) => v.children && (v.children = filterNoPermissionTree(v.children))
);
return filterChildrenTree(newTree);
} | /** 从localStorage里取出当前登录用户的角色roles,过滤无权限的菜单 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/router/utils.ts#L86-L96 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | getParentPaths | function getParentPaths(value: string, routes: RouteRecordRaw[], key = "path") {
// 深度遍历查找
function dfs(routes: RouteRecordRaw[], value: string, parents: string[]) {
for (let i = 0; i < routes.length; i++) {
const item = routes[i];
// 返回父级path
if (item[key] === value) return parents;
// children不存在或为空则不递归
if (!item.children || !item.children.length) continue;
// 往下查找时将当前path入栈
parents.push(item.path);
if (dfs(item.children, value, parents).length) return parents;
// 深度遍历查找未找到时当前path 出栈
parents.pop();
}
// 未找到时返回空数组
return [];
}
return dfs(routes, value, []);
} | /** 通过指定 `key` 获取父级路径集合,默认 `key` 为 `path` */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/router/utils.ts#L99-L120 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | dfs | function dfs(routes: RouteRecordRaw[], value: string, parents: string[]) {
for (let i = 0; i < routes.length; i++) {
const item = routes[i];
// 返回父级path
if (item[key] === value) return parents;
// children不存在或为空则不递归
if (!item.children || !item.children.length) continue;
// 往下查找时将当前path入栈
parents.push(item.path);
if (dfs(item.children, value, parents).length) return parents;
// 深度遍历查找未找到时当前path 出栈
parents.pop();
}
// 未找到时返回空数组
return [];
} | // 深度遍历查找 | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/router/utils.ts#L101-L117 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | findRouteByPath | function findRouteByPath(path: string, routes: RouteRecordRaw[]) {
let res = routes.find((item: { path: string }) => item.path == path);
if (res) {
return isProxy(res) ? toRaw(res) : res;
} else {
for (let i = 0; i < routes.length; i++) {
if (
routes[i].children instanceof Array &&
routes[i].children.length > 0
) {
res = findRouteByPath(path, routes[i].children);
if (res) {
return isProxy(res) ? toRaw(res) : res;
}
}
}
return null;
}
} | /** 查找对应 `path` 的路由信息 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/router/utils.ts#L123-L141 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | handleAsyncRoutes | function handleAsyncRoutes(routeList) {
if (routeList.length === 0) {
usePermissionStoreHook().handleWholeMenus(routeList);
} else {
formatFlatteningRoutes(addAsyncRoutes(routeList)).map(
(v: RouteRecordRaw) => {
// 防止重复添加路由
if (
router.options.routes[0].children.findIndex(
value => value.path === v.path
) !== -1
) {
return;
} else {
// 切记将路由push到routes后还需要使用addRoute,这样路由才能正常跳转
router.options.routes[0].children.push(v);
// 最终路由进行升序
ascending(router.options.routes[0].children);
if (!router.hasRoute(v?.name)) router.addRoute(v);
const flattenRouters: any = router
.getRoutes()
.find(n => n.path === "/");
router.addRoute(flattenRouters);
}
}
);
usePermissionStoreHook().handleWholeMenus(routeList);
}
if (!useMultiTagsStoreHook().getMultiTagsCache) {
useMultiTagsStoreHook().handleTags("equal", [
...routerArrays,
...usePermissionStoreHook().flatteningRoutes.filter(
v => v?.meta?.fixedTag
)
]);
}
addPathMatch();
} | /** 处理动态路由(后端返回的路由) */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/router/utils.ts#L154-L191 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | initRouter | function initRouter() {
if (getConfig()?.CachingAsyncRoutes) {
// 开启动态路由缓存本地localStorage
const key = "async-routes";
const asyncRouteList = storageLocal().getItem(key) as any;
if (asyncRouteList && asyncRouteList?.length > 0) {
return new Promise(resolve => {
handleAsyncRoutes(asyncRouteList);
resolve(router);
});
} else {
return new Promise(resolve => {
getRoutes().then(({ data }) => {
handleAsyncRoutes(cloneDeep(data));
storageLocal().setItem(key, data);
resolve(router);
});
});
}
} else {
return new Promise(resolve => {
getRoutes().then(({ data }) => {
handleAsyncRoutes(cloneDeep(data));
resolve(router);
});
});
}
} | /** 初始化路由(`new Promise` 写法防止在异步请求中造成无限循环)*/ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/router/utils.ts#L194-L221 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | formatFlatteningRoutes | function formatFlatteningRoutes(routesList: RouteRecordRaw[]) {
if (routesList.length === 0) return routesList;
let hierarchyList = buildHierarchyTree(routesList);
for (let i = 0; i < hierarchyList.length; i++) {
if (hierarchyList[i].children) {
hierarchyList = hierarchyList
.slice(0, i + 1)
.concat(hierarchyList[i].children, hierarchyList.slice(i + 1));
}
}
return hierarchyList;
} | /**
* 将多级嵌套路由处理成一维数组
* @param routesList 传入路由
* @returns 返回处理后的一维路由
*/ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/router/utils.ts#L228-L239 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | formatTwoStageRoutes | function formatTwoStageRoutes(routesList: RouteRecordRaw[]) {
if (routesList.length === 0) return routesList;
const newRoutesList: RouteRecordRaw[] = [];
routesList.forEach((v: RouteRecordRaw) => {
if (v.path === "/") {
newRoutesList.push({
component: v.component,
name: v.name,
path: v.path,
redirect: v.redirect,
meta: v.meta,
children: []
});
} else {
newRoutesList[0]?.children.push({ ...v });
}
});
return newRoutesList;
} | /**
* 一维数组处理成多级嵌套数组(三级及以上的路由全部拍成二级,keep-alive 只支持到二级缓存)
* https://github.com/pure-admin/vue-pure-admin/issues/67
* @param routesList 处理后的一维路由菜单数组
* @returns 返回将一维数组重新处理成规定路由的格式
*/ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/router/utils.ts#L247-L265 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | handleAliveRoute | function handleAliveRoute({ name }: ToRouteType, mode?: string) {
switch (mode) {
case "add":
usePermissionStoreHook().cacheOperate({
mode: "add",
name
});
break;
case "delete":
usePermissionStoreHook().cacheOperate({
mode: "delete",
name
});
break;
case "refresh":
usePermissionStoreHook().cacheOperate({
mode: "refresh",
name
});
break;
default:
usePermissionStoreHook().cacheOperate({
mode: "delete",
name
});
useTimeoutFn(() => {
usePermissionStoreHook().cacheOperate({
mode: "add",
name
});
}, 100);
}
} | /** 处理缓存路由(添加、删除、刷新) */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/router/utils.ts#L268-L300 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | addAsyncRoutes | function addAsyncRoutes(arrRoutes: Array<RouteRecordRaw>) {
if (!arrRoutes || !arrRoutes.length) return;
const modulesRoutesKeys = Object.keys(modulesRoutes);
arrRoutes.forEach((v: RouteRecordRaw) => {
if (v.children == null) {
v.children = undefined;
}
// 将backstage属性加入meta,标识此路由为后端返回路由
v.meta.backstage = true;
// 父级的redirect属性取值:如果子级存在且父级的redirect属性不存在,默认取第一个子级的path;如果子级存在且父级的redirect属性存在,取存在的redirect属性,会覆盖默认值
if (v?.children && v.children.length && !v.redirect)
v.redirect = v.children[0].path;
// 父级的name属性取值:如果子级存在且父级的name属性不存在,默认取第一个子级的name;如果子级存在且父级的name属性存在,取存在的name属性,会覆盖默认值(注意:测试中发现父级的name不能和子级name重复,如果重复会造成重定向无效(跳转404),所以这里给父级的name起名的时候后面会自动加上`Parent`,避免重复)
if (v?.children && v.children.length && !v.name)
v.name = (v.children[0].name as string) + "Parent";
if (v.meta?.frameSrc) {
v.component = IFrame;
} else {
// 对后端传component组件路径和不传做兼容(如果后端传component组件路径,那么path可以随便写,如果不传,component组件路径会跟path保持一致)
const index = v?.component
? modulesRoutesKeys.findIndex(ev => ev.includes(v.component as any))
: modulesRoutesKeys.findIndex(ev => ev.includes(v.path));
v.component = modulesRoutes[modulesRoutesKeys[index]];
}
if (v?.children && v.children.length) {
addAsyncRoutes(v.children);
}
});
return arrRoutes;
} | /** 过滤后端传来的动态路由 重新生成规范路由 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/router/utils.ts#L303-L332 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | getHistoryMode | function getHistoryMode(routerHistory): RouterHistory {
// len为1 代表只有历史模式 为2 代表历史模式中存在base参数 https://next.router.vuejs.org/zh/api/#%E5%8F%82%E6%95%B0-1
const historyMode = routerHistory.split(",");
const leftMode = historyMode[0];
const rightMode = historyMode[1];
// no param
if (historyMode.length === 1) {
if (leftMode === "hash") {
return createWebHashHistory("");
} else if (leftMode === "h5") {
return createWebHistory("");
}
} //has param
else if (historyMode.length === 2) {
if (leftMode === "hash") {
return createWebHashHistory(rightMode);
} else if (leftMode === "h5") {
return createWebHistory(rightMode);
}
}
} | /** 获取路由历史模式 https://next.router.vuejs.org/zh/guide/essentials/history-mode.html */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/router/utils.ts#L335-L355 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | getAuths | function getAuths(): Array<string> {
return router.currentRoute.value.meta.auths as Array<string>;
} | /** 获取当前页面按钮级别的权限 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/router/utils.ts#L358-L360 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | hasAuth | function hasAuth(value: string | Array<string>): boolean {
if (!value) return false;
/** 从当前路由的`meta`字段里获取按钮级别的所有自定义`code`值 */
const metaAuths = getAuths();
if (!metaAuths) return false;
const isAuths = isString(value)
? metaAuths.includes(value)
: isIncludeAllChildren(value, metaAuths);
return isAuths ? true : false;
} | /** 是否有按钮级别的权限(根据路由`meta`中的`auths`字段进行判断)*/ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/router/utils.ts#L363-L372 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | getTopMenu | function getTopMenu(tag = false): menuType {
const topMenu = handleTopMenu(
usePermissionStoreHook().wholeMenus[0]?.children[0]
);
tag && useMultiTagsStoreHook().handleTags("push", topMenu);
return topMenu;
} | /** 获取所有菜单中的第一个菜单(顶级菜单)*/ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/router/utils.ts#L387-L393 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | convertTextToCode | function convertTextToCode(
provinceText: string,
cityText: string,
regionText?: string
): string {
let code = "";
if (provinceText && TextToCode[provinceText]) {
const province = TextToCode[provinceText];
code = province.code;
if (cityText && province[cityText]) {
const city = province[cityText];
code = `${code}${cityText === ALL_TEXT ? "" : ", "}${city.code}`;
if (regionText && city[regionText]) {
code = `${code}${regionText === ALL_TEXT ? "" : ", "}${
city[regionText].code
}`;
}
}
}
return code;
} | /**
* 汉字转区域码
* @param provinceText 省
* @param cityText 市
* @param regionText 区
* @returns
*/ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/utils/chinaArea.ts#L159-L181 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | message | const message = (
message: string | VNode | (() => VNode),
params?: MessageParams
): MessageHandler => {
if (!params) {
return ElMessage({
message,
customClass: "pure-message"
});
} else {
const {
icon,
type = "info",
dangerouslyUseHTMLString = false,
customClass = "antd",
duration = 2000,
showClose = false,
center = false,
offset = 20,
appendTo = document.body,
grouping = false,
onClose
} = params;
return ElMessage({
message,
type,
icon,
dangerouslyUseHTMLString,
duration,
showClose,
center,
offset,
appendTo,
grouping,
// 全局搜 pure-message 即可知道该类的样式位置
customClass: customClass === "antd" ? "pure-message" : "",
onClose: () => (isFunction(onClose) ? onClose() : null)
});
}
}; | /** 用法非常简单,参考 src/views/components/message/index.vue 文件 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/utils/message.ts#L38-L78 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | closeAllMessage | const closeAllMessage = (): void => ElMessage.closeAll(); | /**
* 关闭所有 `Message` 消息提示函数
*/ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/utils/message.ts#L83-L83 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | isImgElement | function isImgElement(element) {
return typeof HTMLImageElement !== "undefined"
? element instanceof HTMLImageElement
: element.tagName.toLowerCase() === "img";
} | /** 是否为`img`标签 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/utils/preventDefault.ts#L4-L8 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | propTypes.style | static get style() {
return toValidableType("style", {
type: [String, Object]
});
} | // a native-like validator that supports the `.validable` method | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/utils/propTypes.ts#L28-L32 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | PureHttp.retryOriginalRequest | private static retryOriginalRequest(config: PureHttpRequestConfig) {
return new Promise(resolve => {
PureHttp.requests.push((token: string) => {
config.headers["Authorization"] = formatToken(token);
resolve(config);
});
});
} | /** 重连原始请求 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/utils/http/index.ts#L48-L55 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | PureHttp.httpInterceptorsRequest | private httpInterceptorsRequest(): void {
PureHttp.axiosInstance.interceptors.request.use(
async (config: PureHttpRequestConfig): Promise<any> => {
// 开启进度条动画
NProgress.start();
// 优先判断post/get等方法是否传入回调,否则执行初始化设置等回调
if (typeof config.beforeRequestCallback === "function") {
config.beforeRequestCallback(config);
return config;
}
if (PureHttp.initConfig.beforeRequestCallback) {
PureHttp.initConfig.beforeRequestCallback(config);
return config;
}
/** 请求白名单,放置一些不需要`token`的接口(通过设置请求白名单,防止`token`过期后再请求造成的死循环问题) */
const whiteList = ["/refresh-token", "/login"];
return whiteList.some(url => config.url.endsWith(url))
? config
: new Promise(resolve => {
const data = getToken();
if (data) {
const now = new Date().getTime();
const expired = parseInt(data.expires) - now <= 0;
if (expired) {
if (!PureHttp.isRefreshing) {
PureHttp.isRefreshing = true;
// token过期刷新
useUserStoreHook()
.handRefreshToken({ refreshToken: data.refreshToken })
.then(res => {
const token = res.data.accessToken;
config.headers["Authorization"] = formatToken(token);
PureHttp.requests.forEach(cb => cb(token));
PureHttp.requests = [];
})
.finally(() => {
PureHttp.isRefreshing = false;
});
}
resolve(PureHttp.retryOriginalRequest(config));
} else {
config.headers["Authorization"] = formatToken(
data.accessToken
);
resolve(config);
}
} else {
resolve(config);
}
});
},
error => {
return Promise.reject(error);
}
);
} | /** 请求拦截 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/utils/http/index.ts#L58-L113 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | PureHttp.httpInterceptorsResponse | private httpInterceptorsResponse(): void {
const instance = PureHttp.axiosInstance;
instance.interceptors.response.use(
(response: any) => {
const $config = response.config;
// 关闭进度条动画
NProgress.done();
// 优先判断post/get等方法是否传入回调,否则执行初始化设置等回调
if (typeof $config.beforeResponseCallback === "function") {
$config.beforeResponseCallback(response);
return response;
}
if (PureHttp.initConfig.beforeResponseCallback) {
PureHttp.initConfig.beforeResponseCallback(response);
return response;
}
return response;
},
(error: any) => {
const $error = error;
message(error.response.data.error.message, { type: "error" });
$error.isCancelRequest = Axios.isCancel($error);
// 关闭进度条动画
NProgress.done();
// 所有的响应异常 区分来源为取消请求/非取消请求
return Promise.reject($error);
}
);
} | /** 响应拦截 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/utils/http/index.ts#L116-L144 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | PureHttp.request | public request<T>(
method: RequestMethods,
url: string,
param?: AxiosRequestConfig,
axiosConfig?: PureHttpRequestConfig
): Promise<T> {
const config = {
method,
url,
...param,
...axiosConfig
} as PureHttpRequestConfig;
// 单独处理自定义请求/响应回调
return new Promise((resolve, reject) => {
PureHttp.axiosInstance
.request(config)
.then((response: undefined) => {
resolve(response);
})
.catch(error => {
reject(error);
});
});
} | /** 通用请求工具函数 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/utils/http/index.ts#L147-L171 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | PureHttp.post | public post<T, P>(
url: string,
params?: AxiosRequestConfig<P>,
config?: PureHttpRequestConfig
): Promise<T> {
return this.request<T>("post", url, params, config);
} | /** 单独抽离的`post`工具函数 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/utils/http/index.ts#L174-L180 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | PureHttp.get | public get<T, P>(
url: string,
params?: AxiosRequestConfig<P>,
config?: PureHttpRequestConfig
): Promise<T> {
return this.request<T>("get", url, params, config);
} | /** 单独抽离的`get`工具函数 */ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/utils/http/index.ts#L183-L189 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | StorageProxy.setItem | public async setItem<T>(k: string, v: T, m = 0): Promise<T> {
return new Promise((resolve, reject) => {
this.storage
.setItem(k, {
data: v,
expires: m ? new Date().getTime() + m * 60 * 1000 : 0
})
.then(value => {
resolve(value.data);
})
.catch(err => {
reject(err);
});
});
} | /**
* @description 将对应键名的数据保存到离线仓库
* @param k 键名
* @param v 键值
* @param m 缓存时间(单位`分`,默认`0`分钟,永久缓存)
*/ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/utils/localforage/index.ts#L21-L35 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | StorageProxy.getItem | public async getItem<T>(k: string): Promise<T> {
return new Promise((resolve, reject) => {
this.storage
.getItem(k)
.then((value: ExpiresData<T>) => {
value && (value.expires > new Date().getTime() || value.expires === 0)
? resolve(value.data)
: resolve(null);
})
.catch(err => {
reject(err);
});
});
} | /**
* @description 从离线仓库中获取对应键名的值
* @param k 键名
*/ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/utils/localforage/index.ts#L41-L54 | e03895bcb6eca1f1894af1de15784838172956d5 |
Yi.Abp.Admin | github_2023 | ccnetcore | typescript | StorageProxy.removeItem | public async removeItem(k: string) {
return new Promise<void>((resolve, reject) => {
this.storage
.removeItem(k)
.then(() => {
resolve();
})
.catch(err => {
reject(err);
});
});
} | /**
* @description 从离线仓库中删除对应键名的值
* @param k 键名
*/ | https://github.com/ccnetcore/Yi.Abp.Admin/blob/e03895bcb6eca1f1894af1de15784838172956d5/Yi.Pure.Vue3/src/utils/localforage/index.ts#L60-L71 | e03895bcb6eca1f1894af1de15784838172956d5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.