Skip to content

Commit

Permalink
fixup! fixup! fixup! refactor(utils): Replace GenRandomId with `get…
Browse files Browse the repository at this point in the history
…RandomId`
  • Loading branch information
susnux committed Jan 24, 2025
1 parent 9d885b8 commit c42a4c2
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 14 deletions.
30 changes: 19 additions & 11 deletions src/utils/getElementId.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,37 @@
*/

import { beforeEach, describe, expect, test, vi } from 'vitest'
import { getElementId } from './getElementId.ts'

const vue = vi.hoisted(() => ({ useId: vi.fn() }))
vi.mock('vue', () => vue)
const md5 = vi.hoisted(() => vi.fn())
vi.mock('md5', () => ({ default: md5 }))

describe('getElementId', () => {

beforeEach(() => vue.useId.mockReset())
beforeEach(() => {
md5.mockReset()
vi.resetModules()
})

test('getting an id', async () => {
md5.mockImplementationOnce(() => 'hash')
const { getElementId } = await import('./getElementId.ts')

test('getting an id', () => {
vue.useId.mockImplementationOnce(() => 'vueid')
const id = getElementId()
expect(id).toEqual('nextcloud-vue-vueid')
expect(id).toEqual('nchash-0')
expect(md5).toHaveBeenCalledTimes(1)
})

test('getting multiple ids', () => {
let index = 0
vue.useId.mockImplementation(() => index++)
test('getting multiple ids', async () => {
md5.mockImplementationOnce(() => 'hash')
const { getElementId } = await import('./getElementId.ts')

const id = getElementId()
const id2 = getElementId()

// only once call the hash
expect(md5).toHaveBeenCalledTimes(1)
// both ids are different
expect(id).not.toEqual(id2)
expect(vue.useId).toBeCalledTimes(2)
})

})
8 changes: 5 additions & 3 deletions src/utils/getElementId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { useId } from 'vue'
import md5 from 'md5'

const sanitizedAppName = String(appName).replaceAll(/[^a-z0-9-_]/gi, '') || 'nc'
// unique hash for this app and library version (make sure that there is no clash with different apps)
const instanceId = md5(`${appName}@${SCOPE_VERSION}`).slice(0, 5)
let id = 0

/**
* Get the next element id for use with HTML / CSS.
* We can not be sure that the app has a prefix setup so we prefix ourself
*/
export function getElementId() {
return `${sanitizedAppName}-${useId()}`
return `nc${instanceId}-${id++}`
}

0 comments on commit c42a4c2

Please sign in to comment.