1// Copyright (C) 2019 The Android Open Source Project 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15import * as MicroModal from 'micromodal'; 16import * as m from 'mithril'; 17 18// We need any here so we can accept vnodes with arbitrary attrs. 19// tslint:disable-next-line:no-any 20export type AnyAttrsVnode = m.Vnode<any, {}>; 21 22interface ModalDefinition { 23 title: string; 24 content: AnyAttrsVnode; 25 buttons: Button[]; 26} 27 28export interface Button { 29 text: string; 30 primary: boolean; 31 id: string; 32 action: () => void; 33} 34 35export async function showModal(attrs: ModalDefinition): Promise<void> { 36 const modal = document.querySelector('#main-modal') as HTMLElement; 37 m.render( 38 modal, 39 m('.modal-overlay[data-micromodal-close]', 40 {tabindex: -1}, 41 m('.modal-container[aria-labelledby=mm-title][aria-model][role=dialog]', 42 m('header.modal-header', 43 m('h2.modal-title', {id: 'mm-title'}, attrs.title), 44 m('button.modal-close[aria-label=Close Modal]' + 45 '[data-micromodal-close]')), 46 m('main.modal-content', attrs.content), 47 m('footer.modal-footer', ...makeButtons(attrs.buttons))))); 48 return new Promise(resolve => { 49 MicroModal.show( 50 'main-modal', {onClose: () => resolve(), awaitCloseAnimation: true}); 51 }); 52} 53 54export function hideModel() { 55 MicroModal.close(); 56} 57 58function makeButtons(buttonDefinition: Button[]): Array<m.Vnode<Button>> { 59 const buttons: Array<m.Vnode<Button>> = []; 60 buttonDefinition.forEach(button => { 61 buttons.push( 62 m('button[data-micromodal-close].modal-btn', 63 { 64 class: button.primary ? 'modal-btn-primary' : '', 65 id: button.id, 66 onclick: button.action 67 }, 68 button.text)); 69 }); 70 return buttons; 71} 72