|
| 1 | +class @NewBranchForm |
| 2 | + constructor: (form, availableRefs) -> |
| 3 | + @branchNameError = form.find('.js-branch-name-error') |
| 4 | + @name = form.find('.js-branch-name') |
| 5 | + @ref = form.find('#ref') |
| 6 | + |
| 7 | + @setupAvailableRefs(availableRefs) |
| 8 | + @setupRestrictions() |
| 9 | + @addBinding() |
| 10 | + @init() |
| 11 | + |
| 12 | + addBinding: -> |
| 13 | + @name.on 'blur', @validate |
| 14 | + |
| 15 | + init: -> |
| 16 | + @name.trigger 'blur'if @name.val().length > 0 |
| 17 | + |
| 18 | + setupAvailableRefs: (availableRefs) -> |
| 19 | + @ref.autocomplete { |
| 20 | + source: availableRefs, |
| 21 | + minLength: 1 |
| 22 | + } |
| 23 | + |
| 24 | + setupRestrictions: -> |
| 25 | + startsWith = { |
| 26 | + pattern: /^(\/|\.)/g, |
| 27 | + prefix: "can't start with ", |
| 28 | + conjunction: "or" |
| 29 | + } |
| 30 | + |
| 31 | + endsWith = { |
| 32 | + pattern: /(\/|\.|\.lock)$/g, |
| 33 | + prefix: "can't end in ", |
| 34 | + conjunction: "or" |
| 35 | + } |
| 36 | + |
| 37 | + characters = { |
| 38 | + pattern: /(\s|~|\^|:|\?|\*|\[|\\|\.\.|@\{|\/{2,}){1}/g |
| 39 | + prefix: "can't contains ", |
| 40 | + conjunction: ", " |
| 41 | + } |
| 42 | + |
| 43 | + @restrictions = [startsWith, characters, endsWith] |
| 44 | + |
| 45 | + validate: => |
| 46 | + @branchNameError.empty() |
| 47 | + |
| 48 | + unique = (values, value) -> |
| 49 | + values.push(value) unless value in values |
| 50 | + values |
| 51 | + |
| 52 | + formatter = (values, restriction) -> |
| 53 | + formatted = values.map (value) -> |
| 54 | + switch |
| 55 | + when /\s/.test value then 'spaces' |
| 56 | + when /\/{2,}/g.test value then 'consecutive slashes' |
| 57 | + else "'#{value}'" |
| 58 | + |
| 59 | + "#{restriction.prefix} #{formatted.join(restriction.conjunction)}" |
| 60 | + |
| 61 | + validator = (errors, restriction) => |
| 62 | + matched = @name.val().match(restriction.pattern) |
| 63 | + |
| 64 | + if matched |
| 65 | + errors.concat formatter(matched.reduce(unique, []), restriction) |
| 66 | + else |
| 67 | + errors |
| 68 | + |
| 69 | + errors = @restrictions.reduce validator, [] |
| 70 | + |
| 71 | + if errors.length > 0 |
| 72 | + errorMessage = $("<span/>").text(errors.join(', ')) |
| 73 | + @branchNameError.append(errorMessage) |
0 commit comments