選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

pico.js 14KB

6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
6年前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. const isLandscape = screen.width > screen.height
  2. const State = {
  3. username: null,
  4. websocket: null,
  5. online: [],
  6. posts: [],
  7. rpcs: {},
  8. streams: {},
  9. options: {},
  10. }
  11. const markedOptions = {
  12. breaks: true,
  13. }
  14. marked.setOptions(markedOptions)
  15. /*
  16. *
  17. * SIGNALING
  18. *
  19. */
  20. const wire = (message) => State.websocket.send(JSON.stringify(message))
  21. const signal = (message) => dispatchEvent(new CustomEvent(message.kind, {detail: message}))
  22. const signalPeerStop = (username) => signal({kind: 'peerInfo', value: {type: 'stop'}, source: username})
  23. const listen = (kind, handler) => addEventListener(kind, handler)
  24. listen('login', ({detail}) => State.username = detail.value)
  25. listen('state', ({detail}) => Object.assign(State, detail))
  26. listen('post', ({detail}) => State.posts.push(detail))
  27. listen('peerInfo', (e) => onPeerInfo(e))
  28. const doNotLog = new Set(['login', 'state', 'post', 'peerInfo'])
  29. /*
  30. *
  31. * ALERTS
  32. *
  33. */
  34. State.unseen = 0
  35. listen('post', () => {State.unseen += !document.hasFocus(); updateTitle()})
  36. listen('focus', () => {State.unseen = 0; updateTitle()})
  37. const updateTitle = () => {
  38. document.title = `pico.chat` + (State.unseen ? ` (${State.unseen})` : ``)
  39. }
  40. /*
  41. *
  42. * WEBRTC
  43. *
  44. */
  45. const getOrCreateRpc = (username) => {
  46. if(State.username === username) {
  47. return
  48. }
  49. if(!State.rpcs[username]) {
  50. const rpc = new RTCPeerConnection({iceServers: [{urls: 'stun:stun.sipgate.net:3478'}]})
  51. rpc.onicecandidate = ({candidate}) => {
  52. if(candidate) {
  53. wire({kind: 'peerInfo', value: {type: 'candidate', candidate}})
  54. }
  55. }
  56. rpc.ontrack = (e) => {
  57. State.streams[username] = e.streams[0]
  58. m.redraw()
  59. }
  60. rpc.onclose = (e) => {
  61. console.log(username, e)
  62. }
  63. rpc.oniceconnectionstatechange = (e) => {
  64. m.redraw()
  65. }
  66. State.rpcs[username] = rpc
  67. }
  68. return State.rpcs[username]
  69. }
  70. const setSelectedMedia = async () => {
  71. const localStream = State.streams[State.username]
  72. if(!localStream) {
  73. return
  74. }
  75. localStream.getTracks().forEach(track => {
  76. track.stop()
  77. localStream.removeTrack(track)
  78. })
  79. const addTrack = localStream.addTrack.bind(localStream)
  80. const muted = document.querySelector('#mute-check').checked
  81. if(!muted) {
  82. const audio = Media.audioDefaults
  83. await navigator.mediaDevices.getUserMedia({audio})
  84. .then(s => s.getAudioTracks().forEach(addTrack))
  85. .catch(e => console.error(e))
  86. }
  87. const source = document.querySelector('#media-source').value
  88. if(source === 'camera') {
  89. const video = {width: {ideal: 320}, facingMode: 'user', frameRate: 26}
  90. await navigator.mediaDevices.getUserMedia({video})
  91. .then(s => s.getVideoTracks().forEach(addTrack))
  92. .catch(e => console.error(e))
  93. }
  94. if(source === 'screen' && navigator.mediaDevices.getDisplayMedia) {
  95. await navigator.mediaDevices.getDisplayMedia()
  96. .then(s => s.getVideoTracks().forEach(addTrack))
  97. .catch(e => console.error(e))
  98. }
  99. document.querySelectorAll('video').forEach(video => video.srcObject = video.srcObject)
  100. wire({kind: 'peerInfo', value: {type: 'request'}})
  101. }
  102. const onPeerInfo = async ({detail: message}) => {
  103. const localStream = State.streams[State.username]
  104. const rpc = localStream && getOrCreateRpc(message.source)
  105. const resetStreams = () => {
  106. rpc.getSenders().forEach(sender => rpc.removeTrack(sender))
  107. localStream.getTracks().forEach(track => rpc.addTrack(track, localStream))
  108. }
  109. if(rpc && message.value.type === 'request') {
  110. resetStreams()
  111. const localOffer = await rpc.createOffer()
  112. await rpc.setLocalDescription(localOffer)
  113. wire({kind: 'peerInfo', value: localOffer, target: message.source})
  114. }
  115. else if(rpc && message.value.type === 'offer') {
  116. resetStreams()
  117. const remoteOffer = new RTCSessionDescription(message.value)
  118. await rpc.setRemoteDescription(remoteOffer)
  119. const localAnswer = await rpc.createAnswer()
  120. await rpc.setLocalDescription(localAnswer)
  121. wire({kind: 'peerInfo', value: localAnswer, target: message.source})
  122. }
  123. else if(rpc && message.value.type === 'answer') {
  124. const remoteAnswer = new RTCSessionDescription(message.value)
  125. await rpc.setRemoteDescription(remoteAnswer)
  126. }
  127. else if(rpc && message.value.type === 'candidate') {
  128. const candidate = new RTCIceCandidate(message.value.candidate)
  129. rpc.addIceCandidate(candidate)
  130. }
  131. else if(message.value.type === 'stop') {
  132. if(State.streams[message.source]) {
  133. State.streams[message.source].getTracks().map(track => track.stop())
  134. delete State.streams[message.source]
  135. }
  136. if(State.rpcs[message.source]) {
  137. State.rpcs[message.source].close()
  138. delete State.rpcs[message.source]
  139. }
  140. }
  141. else if(rpc) {
  142. console.log('uncaught', message)
  143. }
  144. }
  145. /*
  146. *
  147. * GUI
  148. *
  149. */
  150. const autoFocus = (vnode) => {
  151. vnode.dom.focus()
  152. }
  153. const scrollIntoView = (vnode) => {
  154. vnode.dom.scrollIntoView()
  155. }
  156. const TextBox = {
  157. autoSize: () => {
  158. textbox.rows = textbox.value.split('\n').length
  159. },
  160. sendPost: () => {
  161. if(textbox.value) {
  162. wire({kind: 'post', value: textbox.value})
  163. textbox.value = ''
  164. textbox.focus()
  165. }
  166. },
  167. blockIndent: (text, iStart, iEnd, nLevels) => {
  168. const startLine = text.slice(0, iStart).split('\n').length - 1
  169. const endLine = text.slice(0, iEnd).split('\n').length - 1
  170. const newText = text
  171. .split('\n')
  172. .map((line, i) => {
  173. if(i < startLine || i > endLine || nLevels === 0) {
  174. newLine = line
  175. }
  176. else if(nLevels > 0) {
  177. newLine = line.replace(/^/, ' ')
  178. }
  179. else if(nLevels < 0) {
  180. newLine = line.replace(/^ /, '')
  181. }
  182. if(i === startLine) {
  183. iStart = iStart + newLine.length - line.length
  184. }
  185. iEnd = iEnd + newLine.length - line.length
  186. return newLine
  187. })
  188. .join('\n')
  189. return [newText, Math.max(0, iStart), Math.max(0, iEnd)]
  190. },
  191. hotKey: (e) => {
  192. // if isDesktop, Enter posts, unless Shift+Enter
  193. // use isLandscape as proxy for isDesktop
  194. if(e.key === 'Enter' && isLandscape && !e.shiftKey) {
  195. e.preventDefault()
  196. TextBox.sendPost()
  197. }
  198. // indent and dedent
  199. const modKey = e.ctrlKey || e.metaKey
  200. const {value: text, selectionStart: A, selectionEnd: B} = textbox
  201. if(e.key === 'Tab') {
  202. e.preventDefault()
  203. const regex = new RegExp(`([\\s\\S]{${A}})([\\s\\S]{${B - A}})`)
  204. textbox.value = text.replace(regex, (m, a, b) => a + ' '.repeat(4))
  205. textbox.setSelectionRange(A + 4, A + 4)
  206. }
  207. if(']['.includes(e.key) && modKey) {
  208. e.preventDefault()
  209. const nLevels = {']': 1, '[': -1}[e.key]
  210. const [newText, newA, newB] = TextBox.blockIndent(text, A, B, nLevels)
  211. textbox.value = newText
  212. textbox.setSelectionRange(newA, newB)
  213. }
  214. },
  215. view() {
  216. return m('.actions',
  217. m('textarea#textbox', {
  218. oncreate: (vnode) => {
  219. TextBox.autoSize()
  220. autoFocus(vnode)
  221. },
  222. onkeydown: TextBox.hotKey,
  223. onkeyup: TextBox.autoSize,
  224. }),
  225. m('button', {
  226. onclick: ({target}) => {
  227. TextBox.sendPost()
  228. TextBox.autoSize()
  229. },
  230. },
  231. 'Send'),
  232. )
  233. },
  234. }
  235. const VideoOptions = {
  236. available: ['mirror', 'square', 'full-screen'],
  237. getFor: (username) => {
  238. if(!State.options[username]) {
  239. State.options[username] = new Set(['mirror', 'square'])
  240. }
  241. return State.options[username]
  242. },
  243. getClassListFor: (username) => {
  244. return [...VideoOptions.getFor(username)].join(' ')
  245. },
  246. toggle: (options, string) => () => options.has(string)
  247. ? options.delete(string)
  248. : options.add(string),
  249. view({attrs: {username}}) {
  250. const options = VideoOptions.getFor(username)
  251. return VideoOptions.available.map((string) =>
  252. m('label.video-option',
  253. m('input', {
  254. type: 'checkbox',
  255. checked: options.has(string),
  256. onchange: VideoOptions.toggle(options, string),
  257. }),
  258. string,
  259. )
  260. )
  261. }
  262. }
  263. const Video = {
  264. keepRatio: {observe: () => {}},
  265. appendStream: ({username}) => ({dom}) => {
  266. dom.autoplay = true
  267. dom.muted = (username === State.username)
  268. dom.srcObject = State.streams[username]
  269. },
  270. view({attrs}) {
  271. const classList = VideoOptions.getClassListFor(attrs.username)
  272. const rpc = State.rpcs[attrs.username] || {iceConnectionState: null}
  273. return m('.video-container', {class: classList, oncreate: ({dom}) => Video.keepRatio.observe(dom)},
  274. m('.video-meta',
  275. m('span.video-source', attrs.username),
  276. m('.video-state', rpc.iceConnectionState),
  277. ),
  278. m('video', {playsinline: true, oncreate: Video.appendStream(attrs)}),
  279. )
  280. },
  281. }
  282. if(window.ResizeObserver) {
  283. const doOne = ({target}) => target.style.setProperty('--height', `${target.clientHeight}px`)
  284. const doAll = (entries) => entries.forEach(doOne)
  285. Video.keepRatio = new ResizeObserver(doAll)
  286. }
  287. const Media = {
  288. videoSources: ['camera', 'screen', 'none'],
  289. audioDefaults: {
  290. noiseSuppresion: true,
  291. echoCancellation: true,
  292. },
  293. turnOn: async () => {
  294. State.streams[State.username] = new MediaStream()
  295. await setSelectedMedia()
  296. m.redraw()
  297. },
  298. turnOff: () => {
  299. wire({kind: 'peerInfo', value: {type: 'stop'}})
  300. State.online.forEach(signalPeerStop)
  301. },
  302. view() {
  303. return m('.media',
  304. m('.media-settings',
  305. State.streams[State.username]
  306. ? m('button', {onclick: Media.turnOff}, 'turn off')
  307. : m('button', {onclick: Media.turnOn}, 'turn on')
  308. ,
  309. m('select#media-source', {onchange: setSelectedMedia},
  310. Media.videoSources.map(option => m('option', option))
  311. ),
  312. m('label',
  313. m('input#mute-check', {onchange: setSelectedMedia, type: 'checkbox'}),
  314. 'mute'
  315. ),
  316. ),
  317. m('.videos',
  318. Object.keys(State.streams).map((username) =>
  319. m(Video, {key: username, username})
  320. ),
  321. ),
  322. )
  323. },
  324. }
  325. const Login = {
  326. sendLogin: (e) => {
  327. e.preventDefault()
  328. const username = e.target.username.value
  329. localStorage.username = username
  330. connect(username)
  331. },
  332. sendLogout: (e) => {
  333. Media.turnOff()
  334. wire({kind: 'logout'})
  335. State.posts = []
  336. },
  337. view() {
  338. const attrs = {
  339. oncreate: autoFocus,
  340. name: 'username',
  341. autocomplete: 'off',
  342. value: localStorage.username,
  343. }
  344. return m('.login',
  345. m('form', {onsubmit: Login.sendLogin},
  346. m('input', attrs),
  347. m('button', 'Login'),
  348. ),
  349. m('.error', State.info),
  350. )
  351. },
  352. }
  353. const Chat = {
  354. prettifyTime: (ts) => {
  355. const dt = new Date(ts)
  356. const H = `0${dt.getHours()}`.slice(-2)
  357. const M = `0${dt.getMinutes()}`.slice(-2)
  358. const S = `0${dt.getSeconds()}`.slice(-2)
  359. return `${H}:${M}:${S}`
  360. },
  361. view() {
  362. return m('.chat',
  363. m('.posts',
  364. State.posts.map(post => m('.post', {oncreate: scrollIntoView},
  365. m('.ts', Chat.prettifyTime(post.ts)),
  366. m('.source', post.source || '~'),
  367. m('.text', m.trust(DOMPurify.sanitize(marked(post.value)))),
  368. )),
  369. ),
  370. m(TextBox),
  371. m('.online',
  372. m('button', {onclick: Login.sendLogout}, 'Logout'),
  373. m('.user-list', State.online.map(username =>
  374. m('details',
  375. m('summary', username),
  376. m(VideoOptions, {username}),
  377. ),
  378. )),
  379. ),
  380. m(Media),
  381. )
  382. },
  383. }
  384. const Main = {
  385. view() {
  386. const connected = State.websocket && State.websocket.readyState === 1
  387. return connected ? m(Chat) : m(Login)
  388. },
  389. }
  390. m.mount(document.body, Main)
  391. /*
  392. *
  393. * WEBSOCKETS
  394. *
  395. */
  396. const connect = (username) => {
  397. const wsUrl = location.href.replace('http', 'ws')
  398. State.websocket = new WebSocket(wsUrl)
  399. State.websocket.onopen = (e) => {
  400. wire({kind: 'login', value: username})
  401. }
  402. State.websocket.onmessage = (e) => {
  403. const message = JSON.parse(e.data)
  404. if(message.online) {
  405. const difference = (l1, l2) => l1.filter(u => !l2.includes(u))
  406. difference(message.online, State.online).forEach(username =>
  407. State.posts.push({ts: message.ts, value: `${username} joined`}))
  408. difference(State.online, message.online).forEach(username =>
  409. State.posts.push({ts: message.ts, value: `${username} left`}))
  410. }
  411. if(!doNotLog.has(message.kind)) {
  412. console.log(message)
  413. }
  414. signal(message)
  415. m.redraw()
  416. }
  417. State.websocket.onclose = (e) => {
  418. State.online.forEach(signalPeerStop)
  419. if(!e.wasClean) {
  420. setTimeout(connect, 1000, username)
  421. }
  422. m.redraw()
  423. }
  424. }
  425. if(localStorage.username) {
  426. connect(localStorage.username)
  427. }
  428. addEventListener('pagehide', Media.turnOff)