File size: 8,003 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import { AdminJSOptions, Assets } from '../../../adminjs-options.interface.js'
import type { PathsInState } from '../../../index.js'

type Paths = PathsInState

let globalAny: any = {}

try {
  globalAny = window
} catch (error) {
  if (!(error instanceof ReferenceError)) {
    throw error
  }
} finally {
  if (!globalAny) {
    globalAny = {}
  }
}

/**
 * Base Params for a any function
 * @alias ActionParams
 * @memberof ViewHelpers
 */
export type ActionParams = {
  /**
   * Unique Resource ID
   */
  resourceId: string
  /**
   * Action name
   */
  actionName: string
  /**
   * Optional query string: ?....
   */
  search?: string
}

/**
 * Params for a record action
 * @alias RecordActionParams
 * @extends ActionParams
 * @memberof ViewHelpers
 */
export type RecordActionParams = ActionParams & {
  /**
   * Record ID
   */
  recordId: string
}

/**
 * Params for a bulk action
 * @alias BulkActionParams
 * @extends ActionParams
 * @memberof ViewHelpers
 */
export type BulkActionParams = ActionParams & {
  /**
   * Array of Records ID
   */
  recordIds?: Array<string>
}

/**
 * Params for a resource action
 * @alias ResourceActionParams
 * @extends ActionParams
 * @memberof ViewHelpers
 */
export type ResourceActionParams = ActionParams

const runDate = new Date()

/**
 * Collection of helper methods available in the views
 */
export class ViewHelpers {
  public options: Paths

  constructor({ options }: { options?: AdminJSOptions } = {}) {
    let opts: Paths = ViewHelpers.getPaths(options)

    opts = opts || {
      rootPath: '/admin',
    }

    // when ViewHelpers are used on the frontend, paths are taken from global Redux State
    this.options = opts
  }

  static getPaths(options?: AdminJSOptions): Paths {
    return options || globalAny.REDUX_STATE?.paths
  }

  /**
   * To each related path adds rootPath passed by the user, as well as a query string
   * @private
   * @param  {Array<string>} [paths]      list of parts of the url
   * @return {string}       path
   * @return {query}        [search=''] query string which can be fetch
   *                                    from `location.search`
   */
  urlBuilder(paths: Array<string> = [], search = ''): string {
    const separator = '/'
    const replace = new RegExp(`${separator}{1,}`, 'g')

    let { rootPath } = this.options
    if (!rootPath.startsWith(separator)) {
      rootPath = `${separator}${rootPath}`
    }

    const parts = [rootPath, ...paths]
    return `${parts.join(separator).replace(replace, separator)}${search}`
  }

  /**
   * Returns login URL
   * @return {string}
   */
  loginUrl(): string {
    return this.options.loginPath
  }

  /**
   * Returns logout URL
   * @return {string}
   */
  logoutUrl(): string {
    return this.options.logoutPath
  }

  /**
   * Returns URL for the dashboard
   * @return {string}
   */
  dashboardUrl(): string {
    return this.options.rootPath
  }

  /**
   * Returns URL for given page name
   * @param {string} pageName       page name which is a unique key specified in
   *                                {@link AdminJSOptions}
   * @return {string}
   */
  pageUrl(pageName: string): string {
    return this.urlBuilder(['pages', pageName])
  }

  /**
   * Returns url for a `edit` action in given Resource. Uses {@link recordActionUrl}
   *
   * @param {string} resourceId  id to the resource
   * @param {string} recordId    id to the record
   * @param {string} [search]        optional query string
   */
  editUrl(resourceId: string, recordId: string, search?: string): string {
    return this.recordActionUrl({ resourceId, recordId, actionName: 'edit', search })
  }

  /**
   * Returns url for a `show` action in given Resource. Uses {@link recordActionUrl}
   *
   * @param {string} resourceId  id to the resource
   * @param {string} recordId    id to the record
   * @param {string} [search]        optional query string
   */
  showUrl(resourceId: string, recordId: string, search?: string): string {
    return this.recordActionUrl({ resourceId, recordId, actionName: 'show', search })
  }

  /**
   * Returns url for a `delete` action in given Resource. Uses {@link recordActionUrl}
   *
   * @param {string} resourceId  id to the resource
   * @param {string} recordId    id to the record
   * @param {string} [search]        optional query string
   */
  deleteUrl(resourceId: string, recordId: string, search?: string): string {
    return this.recordActionUrl({ resourceId, recordId, actionName: 'delete', search })
  }

  /**
   * Returns url for a `new` action in given Resource. Uses {@link resourceActionUrl}
   *
   * @param {string} resourceId  id to the resource
   * @param {string} [search]        optional query string
   */
  newUrl(resourceId: string, search?: string): string {
    return this.resourceActionUrl({ resourceId, actionName: 'new', search })
  }

  /**
   * Returns url for a `list` action in given Resource. Uses {@link resourceActionUrl}
   *
   * @param {string} resourceId  id to the resource
   * @param {string} [search]        optional query string
   */
  listUrl(resourceId: string, search?: string): string {
    return this.resourceActionUrl({ resourceId, actionName: 'list', search })
  }

  /**
   * Returns url for a `bulkDelete` action in given Resource. Uses {@link bulkActionUrl}
   *
   * @param {string} resourceId  id to the resource
   * @param {Array<string>} recordIds   separated by comma records
   * @param {string} [search]        optional query string
   */
  bulkDeleteUrl(resourceId: string, recordIds: Array<string>, search?: string): string {
    return this.bulkActionUrl({ resourceId, recordIds, actionName: 'bulkDelete', search })
  }

  /**
   * Returns resourceAction url
   *
   * @param   {ResourceActionParams}  options
   * @param   {string}  options.resourceId
   * @param   {string}  options.actionName
   * @param   {string}  [options.search]        optional query string
   *
   * @return  {string}
   */
  resourceActionUrl({ resourceId, actionName, search }: ResourceActionParams): string {
    return this.urlBuilder(['resources', resourceId, 'actions', actionName], search)
  }

  resourceUrl({ resourceId, search }: Omit<ResourceActionParams, 'actionName'>): string {
    return this.urlBuilder(['resources', resourceId], search)
  }

  /**
   * Returns recordAction url
   *
   * @param   {RecordActionParams}  options
   * @param   {string}  options.resourceId
   * @param   {string}  options.recordId
   * @param   {string}  options.actionName
   *
   * @return  {string}
   */
  recordActionUrl({ resourceId, recordId, actionName, search }: RecordActionParams): string {
    return this.urlBuilder(['resources', resourceId, 'records', recordId, actionName], search)
  }

  /**
   * Returns bulkAction url
   *
   * @param   {BulkActionParams}  options
   * @param   {string}  options.resourceId
   * @param   {Array<string>}  [options.recordIds]
   * @param   {string}  options.actionName
   *
   * @return  {string}
   */
  bulkActionUrl({ resourceId, recordIds, actionName, search }: BulkActionParams): string {
    const url = this.urlBuilder(['resources', resourceId, 'bulk', actionName])
    if (recordIds && recordIds.length) {
      const query = new URLSearchParams(search)
      query.set('recordIds', recordIds.join(','))
      return `${url}?${query.toString()}`
    }
    return `${url}${search || ''}`
  }

  /**
   * Returns absolute path to a given asset.
   * @private
   *
   * @param  {string} asset
   * @param  {Assets | undefined} assetsConfig
   * @return {string}
   */
  assetPath(asset: string, assetsConfig?: Assets): string {
    if (this.options.assetsCDN) {
      const pathname = assetsConfig?.coreScripts?.[asset] ?? asset
      const url = new URL(pathname, this.options.assetsCDN).href

      // adding timestamp to the href invalidates the CDN cache
      return `${url}?date=${runDate.getTime()}`
    }
    return this.urlBuilder(['frontend', 'assets', asset])
  }
}

export default ViewHelpers