$ -> # An editor for CMS referencelist attributes. # Creates the DOM for one reference element of the referencelist and substitutes the # name and id attribute. itemTemplate = -> $("
") contentBrowserButtonTemplate = -> icon = $('') .addClass('editing-icon') .addClass('editing-icon-plus') button = $('') .addClass('editing-button') .addClass('editing-green') .addClass('content-browser-open') .html(icon) button # Returns the closest referencelist DOM element. getCmsField = (element) -> element.closest('[data-scrivito-field-type=referencelist]') # Saves the referencelist to the CMS when changed and stores the last successfully saved value. save = (ids, cmsField, reload = true) -> lastSaved = getLastSaved(cmsField) unless JSON.stringify(ids) == JSON.stringify(lastSaved) cmsField.scrivito('save', ids) .done -> storeLastSaved(cmsField, ids) cmsField.trigger('save.scrivito_editors') cmsField.scrivito('reload') if reload # Run when clicking the content browser button. onContentBrowserOpen = (event) -> event.preventDefault() cmsField = getCmsField($(event.currentTarget)) filters = cmsField.data('filters') filterContext = cmsField.data('filterContext') scrivito.content_browser.open filters: filters filter_context: filterContext .done (selection) => ids = getIds(cmsField).concat(selection) save(ids, cmsField) # Collects all reference ids for a given referencelist. getIds = (cmsField) -> items = $(cmsField).find('[data-id]') value = for item in items $(item).data('id') # Removes a single reference from the referencelist. remove = (event) -> event.preventDefault() target = $(event.currentTarget) cmsField = getCmsField(target) target.closest('li').remove() ids = getIds(cmsField) save(ids, cmsField, false) # Turns the server side generated referencelist data into the reference editor using a template. transform = (elements) -> elements.append(contentBrowserButtonTemplate) items = elements.find('li') for item in items $(item).append(itemTemplate) # Returns the last saved value. getLastSaved = (cmsField) -> $(cmsField).data('last-saved') # Stores a given value as last saved. storeLastSaved = (cmsField, value) -> $(cmsField).data('last-saved', value) # Initialize referencelist editor and setup event callbacks. scrivito.on 'content', (root) -> if scrivito.in_editable_view() elements = $(root).find('[data-scrivito-field-type="referencelist"]:not([data-editor]), [data-editor~="referencelist"]') if elements.length transform(elements) for element in elements ids = getIds(element) storeLastSaved(element, ids) elements.on 'click', 'li a.delete', remove elements.on 'click', 'button.content-browser-open', onContentBrowserOpen elements.find('ul').sortable update: (event) -> cmsField = getCmsField($(event.target)) ids = getIds(cmsField) save(ids, cmsField)