Skip to content

Instantly share code, notes, and snippets.

@spacejack
Created April 3, 2018 21:02
Show Gist options
  • Save spacejack/fb211c86c040f8413f6e7d6617b96ff1 to your computer and use it in GitHub Desktop.
Save spacejack/fb211c86c040f8413f6e7d6617b96ff1 to your computer and use it in GitHub Desktop.
Example of Mithril Modal component
import * as m from 'mithril'
// Modal state
let isOpen = false
let options: ModalOptions = {}
export interface ModalButton {
id: string
text: string
}
export interface ModalOptions {
title: string
content?: m.Children
buttons?: ModalButton[]
onclick?(id: string): any
}
export function openModal (opts: ModalOptions) {
if (isOpen) {
console.warn("Modal already open.")
//return
}
// Copy the supplied opts
options = {...opts}
if (opts.buttons) {
options.buttons = opts.buttons.map(b => ({...b}))
}
isOpen = true
}
export function closeModal() {
isOpen = false
}
export function modalIsOpen() {
return isOpen
}
export default {
oncreate ({dom}) {
readyDom(dom)
dom.classList.add('show')
},
onbeforeremove ({dom}) {
// Fade out menu on close
dom.classList.remove('show')
return new Promise(resolve => {
dom.addEventListener('transitionend', resolve)
})
},
view() {
return m('.modal-bg',
m('.modal',
m('.title', o.title),
options.content && m('.content', options.content),
options.buttons && m('.buttons',
options.buttons.map(b =>
m('button',
{
type: 'button',
disabled: !isOpen,
onclick() {
isOpen = false
options.onclick && options.onclick(b.id)
}
},
b.text
)
)
)
)
)
}
} as m.Component
// Reading from the DOM element ensures it is rendered,
// ready to animate
function readyDom (dom: Element) {
let temp = (dom as HTMLElement).offsetHeight
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment