summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/ide/stores/utils.js
blob: b7ced3a271a904588de5e2ba36274bd1739a1efa (plain)
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
import { commitActionTypes, FILE_VIEW_MODE_EDITOR } from '../constants';
import {
  relativePathToAbsolute,
  isAbsolute,
  isRootRelative,
  isBlobUrl,
} from '~/lib/utils/url_utility';

export const dataStructure = () => ({
  id: '',
  // Key will contain a mixture of ID and path
  // it can also contain a prefix `pending-` for files opened in review mode
  key: '',
  type: '',
  name: '',
  path: '',
  tempFile: false,
  tree: [],
  loading: false,
  opened: false,
  active: false,
  changed: false,
  staged: false,
  lastCommitSha: '',
  rawPath: '',
  raw: '',
  content: '',
  editorRow: 1,
  editorColumn: 1,
  fileLanguage: '',
  viewMode: FILE_VIEW_MODE_EDITOR,
  size: 0,
  parentPath: null,
  lastOpenedAt: 0,
  mrChange: null,
  deleted: false,
  prevPath: undefined,
});

export const decorateData = entity => {
  const {
    id,
    type,
    name,
    path,
    content = '',
    tempFile = false,
    active = false,
    opened = false,
    changed = false,
    rawPath = '',
    file_lock,
    parentPath = '',
  } = entity;

  return Object.assign(dataStructure(), {
    id,
    key: `${name}-${type}-${id}`,
    type,
    name,
    path,
    tempFile,
    opened,
    active,
    changed,
    content,
    rawPath,
    file_lock,
    parentPath,
  });
};

export const setPageTitle = title => {
  document.title = title;
};

export const setPageTitleForFile = (state, file) => {
  const title = [file.path, state.currentBranchId, state.currentProjectId, 'GitLab'].join(' ยท ');
  setPageTitle(title);
};

export const commitActionForFile = file => {
  if (file.prevPath) {
    return commitActionTypes.move;
  } else if (file.deleted) {
    return commitActionTypes.delete;
  } else if (file.tempFile) {
    return commitActionTypes.create;
  }

  return commitActionTypes.update;
};

export const getCommitFiles = stagedFiles =>
  stagedFiles.reduce((acc, file) => {
    if (file.type === 'tree') return acc;

    return acc.concat({
      ...file,
    });
  }, []);

export const createCommitPayload = ({
  branch,
  getters,
  newBranch,
  state,
  rootState,
  rootGetters,
}) => ({
  branch,
  commit_message: state.commitMessage || getters.preBuiltCommitMessage,
  actions: getCommitFiles(rootState.stagedFiles).map(f => {
    const isBlob = isBlobUrl(f.rawPath);
    const content = isBlob ? btoa(f.content) : f.content;

    return {
      action: commitActionForFile(f),
      file_path: f.path,
      previous_path: f.prevPath || undefined,
      content: f.prevPath && !f.changed ? null : content || undefined,
      encoding: isBlob ? 'base64' : 'text',
      last_commit_id: newBranch || f.deleted || f.prevPath ? undefined : f.lastCommitSha,
    };
  }),
  start_sha: newBranch ? rootGetters.lastCommit.id : undefined,
});

export const createNewMergeRequestUrl = (projectUrl, source, target) =>
  `${projectUrl}/-/merge_requests/new?merge_request[source_branch]=${source}&merge_request[target_branch]=${target}&nav_source=webide`;

const sortTreesByTypeAndName = (a, b) => {
  if (a.type === 'tree' && b.type === 'blob') {
    return -1;
  } else if (a.type === 'blob' && b.type === 'tree') {
    return 1;
  }
  if (a.name < b.name) return -1;
  if (a.name > b.name) return 1;
  return 0;
};

export const sortTree = sortedTree =>
  sortedTree
    .map(entity =>
      Object.assign(entity, {
        tree: entity.tree.length ? sortTree(entity.tree) : [],
      }),
    )
    .sort(sortTreesByTypeAndName);

export const filePathMatches = (filePath, path) => filePath.indexOf(`${path}/`) === 0;

export const getChangesCountForFiles = (files, path) =>
  files.filter(f => filePathMatches(f.path, path)).length;

export const mergeTrees = (fromTree, toTree) => {
  if (!fromTree || !fromTree.length) {
    return toTree;
  }

  const recurseTree = (n, t) => {
    if (!n) {
      return t;
    }
    const existingTreeNode = t.find(el => el.path === n.path);

    if (existingTreeNode && n.tree.length > 0) {
      existingTreeNode.opened = true;
      recurseTree(n.tree[0], existingTreeNode.tree);
    } else if (!existingTreeNode) {
      const sorted = sortTree(t.concat(n));
      t.splice(0, t.length + 1, ...sorted);
    }
    return t;
  };

  for (let i = 0, l = fromTree.length; i < l; i += 1) {
    recurseTree(fromTree[i], toTree);
  }

  return toTree;
};

export const swapInStateArray = (state, arr, key, entryPath) =>
  Object.assign(state, {
    [arr]: state[arr].map(f => (f.key === key ? state.entries[entryPath] : f)),
  });

export const getEntryOrRoot = (state, path) =>
  path ? state.entries[path] : state.trees[`${state.currentProjectId}/${state.currentBranchId}`];

export const swapInParentTreeWithSorting = (state, oldKey, newPath, parentPath) => {
  if (!newPath) {
    return;
  }

  const parent = getEntryOrRoot(state, parentPath);

  if (parent) {
    const tree = parent.tree
      // filter out old entry && new entry
      .filter(({ key, path }) => key !== oldKey && path !== newPath)
      // concat new entry
      .concat(state.entries[newPath]);

    parent.tree = sortTree(tree);
  }
};

export const removeFromParentTree = (state, oldKey, parentPath) => {
  const parent = getEntryOrRoot(state, parentPath);

  if (parent) {
    parent.tree = sortTree(parent.tree.filter(({ key }) => key !== oldKey));
  }
};

export const updateFileCollections = (state, key, entryPath) => {
  ['openFiles', 'changedFiles', 'stagedFiles'].forEach(fileCollection => {
    swapInStateArray(state, fileCollection, key, entryPath);
  });
};

export const cleanTrailingSlash = path => path.replace(/\/$/, '');

export const pathsAreEqual = (a, b) => {
  const cleanA = a ? cleanTrailingSlash(a) : '';
  const cleanB = b ? cleanTrailingSlash(b) : '';

  return cleanA === cleanB;
};

export function extractMarkdownImagesFromEntries(mdFile, entries) {
  /**
   * Regex to identify an image tag in markdown, like:
   *
   * ![img alt goes here](/img.png)
   * ![img alt](../img 1/img.png "my image title")
   * ![img alt](https://gitlab.com/assets/logo.svg "title here")
   *
   */
  const reMdImage = /!\[([^\]]*)\]\((.*?)(?:(?="|\))"([^"]*)")?\)/gi;
  const prefix = 'gl_md_img_';
  const images = {};

  let content = mdFile.content || mdFile.raw;
  let i = 0;

  content = content.replace(reMdImage, (_, alt, path, title) => {
    const imagePath = (isRootRelative(path) ? path : relativePathToAbsolute(path, mdFile.path))
      .substr(1)
      .trim();

    const imageContent = entries[imagePath]?.content || entries[imagePath]?.raw;

    if (!isAbsolute(path) && imageContent) {
      const ext = path.includes('.')
        ? path
            .split('.')
            .pop()
            .trim()
        : 'jpeg';
      const src = `data:image/${ext};base64,${imageContent}`;
      i += 1;
      const key = `{{${prefix}${i}}}`;
      images[key] = { alt, src, title };
      return key;
    }
    return title ? `![${alt}](${path}"${title}")` : `![${alt}](${path})`;
  });

  return { content, images };
}