text
stringlengths
9
39.2M
dir
stringlengths
25
226
lang
stringclasses
163 values
created_date
timestamp[s]
updated_date
timestamp[s]
repo_name
stringclasses
751 values
repo_full_name
stringclasses
752 values
star
int64
1.01k
183k
len_tokens
int64
1
18.5M
```javascript /* @flow strict-local */ import type { ServerEmojiData } from '../../api/modelTypes'; import { displayCharacterForUnicodeEmojiCode, availableUnicodeEmojiCodes } from '../../emoji/data'; const codeToCss = (code, serverEmojiData): string => `.emoji-${code}:before { content: '${displayCharacterForUnicodeEmojiCode( code, serverEmojiData, )}'; }`; const cssEmojis = (serverEmojiData: ServerEmojiData | null): string => { const availableCodes = serverEmojiData?.code_to_names.keys() ?? availableUnicodeEmojiCodes; const chunks = []; for (const code of availableCodes) { chunks.push(codeToCss(code, serverEmojiData)); } return chunks.join('\n'); }; export default cssEmojis; ```
/content/code_sandbox/src/webview/css/cssEmojis.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
167
```javascript /* @flow strict-local */ import { Platform } from 'react-native'; import type { Auth } from '../../types'; import smoothScroll from './smoothScroll.min'; import matchesPolyfill from './matchesPolyfill'; import compiledWebviewJs from './generatedEs3'; /** * An HTML fragment for the main `script` element for our message-list WebView. */ // The bulk of the code in this `script` element comes from // `compiledWebviewJs`, which in turn is derived from `js.js` // and its imports. See module jsdoc on `js.js`. export default ( scrollMessageId: number | null, auth: Auth, doNotMarkMessagesAsRead: boolean, ): string => ` <script> window.__forceSmoothScrollPolyfill__ = true; ${smoothScroll} ${matchesPolyfill} document.addEventListener('DOMContentLoaded', function() { var platformOS = ${JSON.stringify(Platform.OS)}; var isDevelopment = ${JSON.stringify(process.env.NODE_ENV === 'development')}; var doNotMarkMessagesAsRead = ${JSON.stringify(doNotMarkMessagesAsRead)}; ${compiledWebviewJs} compiledWebviewJs.handleInitialLoad( ${JSON.stringify(scrollMessageId)}, ${JSON.stringify(auth)} ); }); </script> `; ```
/content/code_sandbox/src/webview/js/script.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
267
```javascript /* @flow strict-local */ import invariant from 'invariant'; import { ensureUnreachable } from '../../generics'; import type { EditSequence } from '../generateInboundEventEditSequence'; // TODO: Put more of the WebView's event-handling code in here. /** * PRIVATE - don't use until we have more test coverage (coming soon) */ export function applyEditSequence(editSequence: EditSequence) { const msglistElementsDiv = document.querySelector('div#msglist-elements'); invariant(msglistElementsDiv, 'applyEditSequence: expected msglistElementsDiv'); editSequence.forEach(edit => { switch (edit.type) { case 'insert': { // TODO: Performance in the common case of many consecutive inserts: // path_to_url#discussion_r793030286 const newChild = document.createElement('div'); msglistElementsDiv.insertBefore(newChild, msglistElementsDiv.children[edit.index] ?? null); newChild.outerHTML = edit.html; break; } case 'replace': { const fragment = document.createDocumentFragment(); const newChild = document.createElement('div'); fragment.appendChild(newChild); newChild.outerHTML = edit.html; // Use a DocumentFragment so that the old element gets replaced // atomically with the intended new one, without an intermediate // state where it's been replaced by an empty div. // // Why not skip the DocumentFragment and just set `.outerHTML` // before calling `.replaceWith`? Because if an element doesn't // already have a parent, then setting `.outerHTML` on it won't // work: // path_to_url#dom-element-outerhtml msglistElementsDiv.replaceChild(fragment, msglistElementsDiv.children[edit.index]); break; } case 'delete': { msglistElementsDiv.removeChild(msglistElementsDiv.children[edit.index]); break; } default: { ensureUnreachable(edit.type); throw new Error(`unexpected edit type: ${edit.type}`); } } }); } ```
/content/code_sandbox/src/webview/js/handleInboundEvents.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
441
```javascript /* @flow strict-local */ /** * This entire code has been copied near verbatim from the WebApp's `pygments.scss` file. * path_to_url * The main change is in the logic of the `isDarkMode` flag. The reason why we have to do * that is because the WebApp uses SCSS, which can detect this natively, while we use CSS. * * Use this command to get the diff between the WebApp code vs this file for debugging: * `git diff --no-index ../zulip/static/styles/pygments.scss src/webview/css/cssPygments.js` */ export default (isDarkMode: boolean): string => ` .codehilite pre { background-color: hsl(0, 0%, 100%); -webkit-font-smoothing: auto; } .codehilite .hll { background-color: hsl(60, 100%, 90%); } .codehilite .c { color: hsl(180, 33%, 37%); font-style: italic; } /* Comment */ .codehilite .err { border: 1px solid hsl(0, 100%, 50%); } /* Error */ .codehilite .k { color: hsl(332, 70%, 38%); } /* Keyword */ .codehilite .o { color: hsl(332, 70%, 38%); } /* Operator */ .codehilite .cm { color: hsl(180, 33%, 37%); font-style: italic; } /* Comment.Multiline */ .codehilite .cp { color: hsl(38, 100%, 36%); } /* Comment.Preproc */ .codehilite .c1 { color: hsl(0, 0%, 67%); font-style: italic; } /* Comment.Single */ .codehilite .cs { color: hsl(180, 33%, 37%); font-style: italic; } /* Comment.Special */ .codehilite .gd { color: hsl(0, 100%, 31%); } /* Generic.Deleted */ .codehilite .ge { font-style: italic; } /* Generic.Emph */ .codehilite .gr { color: hsl(0, 100%, 50%); } /* Generic.Error */ .codehilite .gh { color: hsl(240, 100%, 25%); font-weight: bold; } /* Generic.Heading */ .codehilite .gi { color: hsl(120, 100%, 31%); } /* Generic.Inserted */ .codehilite .go { color: hsl(0, 0%, 50%); } /* Generic.Output */ .codehilite .gp { color: hsl(240, 100%, 25%); font-weight: bold; } /* Generic.Prompt */ .codehilite .gs { font-weight: bold; } /* Generic.Strong */ .codehilite .gu { color: hsl(300, 100%, 25%); font-weight: bold; } /* Generic.Subheading */ .codehilite .gt { color: hsl(221, 100%, 40%); } /* Generic.Traceback */ .codehilite .kc { color: hsl(332, 70%, 38%); font-weight: bold; } /* Keyword.Constant */ .codehilite .kd { color: hsl(332, 70%, 38%); } /* Keyword.Declaration */ .codehilite .kn { color: hsl(332, 70%, 38%); font-weight: bold; } /* Keyword.Namespace */ .codehilite .kp { color: hsl(332, 70%, 38%); } /* Keyword.Pseudo */ .codehilite .kr { color: hsl(332, 70%, 38%); font-weight: bold; } /* Keyword.Reserved */ .codehilite .kt { color: hsl(332, 70%, 38%); } /* Keyword.Type */ .codehilite .m { color: hsl(0, 0%, 40%); } /* Literal.Number */ .codehilite .s { color: hsl(86, 57%, 40%); } /* Literal.String */ .codehilite .na { color: hsl(71, 55%, 36%); } /* Name.Attribute */ .codehilite .nb { color: hsl(195, 100%, 35%); } /* Name.Builtin */ .codehilite .nc { color: hsl(264, 27%, 50%); font-weight: bold; } /* Name.Class */ .codehilite .no { color: hsl(0, 100%, 26%); } /* Name.Constant */ .codehilite .nd { color: hsl(276, 100%, 56%); } /* Name.Decorator */ .codehilite .ni { color: hsl(0, 0%, 60%); font-weight: bold; } /* Name.Entity */ .codehilite .ne { color: hsl(2, 62%, 52%); font-weight: bold; } /* Name.Exception */ .codehilite .nf { color: hsl(264, 27%, 50%); } /* Name.Function */ .codehilite .nl { color: hsl(60, 100%, 31%); } /* Name.Label */ .codehilite .nn { color: hsl(264, 27%, 50%); font-weight: bold; } /* Name.Namespace */ .codehilite .nt { color: hsl(120, 100%, 25%); font-weight: bold; } /* Name.Tag */ .codehilite .nv { color: hsl(241, 68%, 28%); } /* Name.Variable */ .codehilite .nx { color: hsl(0, 0%, 26%); } /* Not sure? */ .codehilite .ow { color: hsl(276, 100%, 56%); font-weight: bold; } /* Operator.Word */ .codehilite .w { color: hsl(0, 0%, 73%); } /* Text.Whitespace */ .codehilite .mf { color: hsl(195, 100%, 35%); } /* Literal.Number.Float */ .codehilite .mh { color: hsl(195, 100%, 35%); } /* Literal.Number.Hex */ .codehilite .mi { color: hsl(195, 100%, 35%); } /* Literal.Number.Integer */ .codehilite .mo { color: hsl(195, 100%, 35%); } /* Literal.Number.Oct */ .codehilite .sb { color: hsl(86, 57%, 40%); } /* Literal.String.Backtick */ .codehilite .sc { color: hsl(86, 57%, 40%); } /* Literal.String.Char */ .codehilite .sd { color: hsl(86, 57%, 40%); font-style: italic; } /* Literal.String.Doc */ .codehilite .s2 { color: hsl(225, 71%, 33%); } /* Literal.String.Double */ .codehilite .se { color: hsl(26, 69%, 43%); font-weight: bold; } /* Literal.String.Escape */ .codehilite .sh { color: hsl(86, 57%, 40%); } /* Literal.String.Heredoc */ .codehilite .si { color: hsl(336, 38%, 56%); font-weight: bold; } /* Literal.String.Interpol */ .codehilite .sx { color: hsl(120, 100%, 25%); } /* Literal.String.Other */ .codehilite .sr { color: hsl(189, 54%, 49%); } /* Literal.String.Regex */ .codehilite .s1 { color: hsl(86, 57%, 40%); } /* Literal.String.Single */ .codehilite .ss { color: hsl(241, 68%, 28%); } /* Literal.String.Symbol */ .codehilite .bp { color: hsl(120, 100%, 25%); } /* Name.Builtin.Pseudo */ .codehilite .vc { color: hsl(241, 68%, 28%); } /* Name.Variable.Class */ .codehilite .vg { color: hsl(241, 68%, 28%); } /* Name.Variable.Global */ .codehilite .vi { color: hsl(241, 68%, 28%); } /* Name.Variable.Instance */ .codehilite .il { color: hsl(0, 0%, 40%); } /* Literal.Number.Integer.Long */ /* Syntax Highlighting for dark-mode */ ${ isDarkMode ? ` .codehilite code, .codehilite pre { color: hsl(212, 100%, 82%); background-color: hsl(212, 25%, 15%); } .codehilite .hll { background-color: hsl(0, 0%, 13%); } .codehilite .err { color: hsl(1, 67%, 66%); background-color: hsl(0, 7%, 22%); } .codehilite .k { color: hsl(31, 85%, 59%); } .codehilite .p { color: hsl(179, 27%, 35%); } .codehilite .cs { color: hsl(0, 100%, 40%); font-weight: 700; } .codehilite .gd { color: hsl(0, 100%, 40%); } .codehilite .ge { color: hsl(0, 0%, 80%); font-style: italic; } .codehilite .gr { color: hsl(0, 100%, 50%); } .codehilite .go { color: hsl(0, 0%, 50%); } .codehilite .gs { color: hsl(0, 0%, 80%); font-weight: 700; } .codehilite .gu { color: hsl(300, 100%, 25%); font-weight: 700; } .codehilite .gt { color: hsl(222, 100%, 41%); } .codehilite .kc { color: hsl(0, 45%, 75%); } .codehilite .kd { color: hsl(60, 100%, 76%); } .codehilite .kn { color: hsl(24, 56%, 72%); font-weight: 700; } .codehilite .kp { color: hsl(62, 36%, 71%); } .codehilite .kr { color: hsl(359, 58%, 56%); } .codehilite .ni { color: hsl(359, 35%, 63%); } .codehilite .ne { color: hsl(53, 23%, 69%); font-weight: 700; } .codehilite .nn { color: hsl(204, 54%, 72%); } .codehilite .vi { color: hsl(60, 100%, 89%); } .codehilite .c, .codehilite .g, .codehilite .cm, .codehilite .cp, .codehilite .c1 { color: hsl(209, 15%, 55%); } .codehilite .l, .codehilite .x, .codehilite .no, .codehilite .nd, .codehilite .nl, .codehilite .nx, .codehilite .py, .codehilite .w { color: hsl(0, 0%, 80%); } .codehilite .n, .codehilite .nv, .codehilite .vg { color: hsl(60, 19%, 83%); } .codehilite .o, .codehilite .ow { color: hsl(58, 52%, 88%); } .codehilite .gh, .codehilite .gp { color: hsl(60, 19%, 83%); font-weight: 700; } .codehilite .gi, .codehilite .kt { color: hsl(120, 100%, 40%); } .codehilite .ld, .codehilite .s, .codehilite .sb, .codehilite .sc, .codehilite .sd, .codehilite .s2, .codehilite .se, .codehilite .sh, .codehilite .si, .codehilite .sx, .codehilite .sr, .codehilite .s1, .codehilite .ss { color: hsl(0, 36%, 69%); } .codehilite .m, .codehilite .mf, .codehilite .mh, .codehilite .mi, .codehilite .mo, .codehilite .il { color: hsl(183, 45%, 69%); } .codehilite .na, .codehilite .nt { color: hsl(127, 25%, 68%); } .codehilite .nb, .codehilite .nc, .codehilite .nf, .codehilite .bp, .codehilite .vc { color: hsl(60, 75%, 75%); } ` : '' } `; ```
/content/code_sandbox/src/webview/css/cssPygments.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
3,052
```javascript /* @flow strict-local */ // Official MDN polyfill for Element.matches // Source: path_to_url export default ` if (!Element.prototype.matches) { Element.prototype.matches = Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector || function(s) { var matches = (this.document || this.ownerDocument).querySelectorAll(s), i = matches.length; while (--i >= 0 && matches.item(i) !== this) {} return i > -1; }; } `; ```
/content/code_sandbox/src/webview/js/matchesPolyfill.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
128
```javascript /* @flow strict-local */ import type { WebViewInboundEvent, WebViewInboundEventContent, WebViewInboundEventFetching, WebViewInboundEventTyping, WebViewInboundEventReady, WebViewInboundEventSetRead, } from '../generateInboundEvents'; import type { JSONable } from '../../utils/jsonable'; import sendMessage from './sendMessage'; import { ensureUnreachable } from '../../types'; type Scrub<E: WebViewInboundEvent> = {| [key: $Keys<E>]: JSONable |}; type ScrubbedInboundEvent = | Scrub<WebViewInboundEventContent> | Scrub<WebViewInboundEventFetching> | Scrub<WebViewInboundEventTyping> | Scrub<WebViewInboundEventReady> | Scrub<WebViewInboundEventSetRead>; type ScrubbedInboundEventItem = {| timestamp: number, type: 'inbound', scrubbedEvent: ScrubbedInboundEvent, |}; /** * Grab interesting but not privacy-sensitive message-loading state. * * Takes the "content" from an inbound WebView event, an HTML string, * and returns the opening div#message-loading tag, so we know whether * it's visible. */ const placeholdersDivTagFromContent = (content: string): string | null => { const match = /<div id="message-loading" class="(?:hidden)?">/.exec(content); return match !== null ? match[0] : null; }; export default class InboundEventLogger { _captureStartTime: number | void; _captureEndTime: number | void; _isCapturing: boolean; _capturedInboundEventItems: ScrubbedInboundEventItem[]; /** * Minimally transform an inbound event to remove sensitive data. */ static scrubInboundEvent(event: WebViewInboundEvent): ScrubbedInboundEvent { // Don't spread the event (e.g., `...event`); instead, rebuild it. // That way, a new property, when added, won't automatically be // sent to Sentry un-scrubbed. switch (event.type) { case 'content': { return { type: event.type, scrollMessageId: event.scrollMessageId, auth: 'redacted', content: placeholdersDivTagFromContent(event.content), scrollStrategy: event.scrollStrategy, }; } case 'fetching': { return { type: event.type, showMessagePlaceholders: event.showMessagePlaceholders, fetchingOlder: event.fetchingOlder, fetchingNewer: event.fetchingNewer, }; } case 'typing': { return { type: event.type, // Empty if no one is typing; otherwise, has avatar URLs. content: event.content !== '', }; } case 'ready': { return { type: event.type, }; } case 'set-do-not-mark-as-read': { return { type: event.type, value: event.value }; } case 'set-read': { return { type: event.type, value: event.value, messageIds: event.messageIds, }; } default: { ensureUnreachable(event); return { type: event.type, }; } } } constructor() { this._isCapturing = false; this._capturedInboundEventItems = []; } startCapturing() { if (this._isCapturing) { throw new Error('InboundEventLogger: Tried to call startCapturing while already capturing.'); } else if (this._capturedInboundEventItems.length > 0 || this._captureEndTime !== undefined) { throw new Error('InboundEventLogger: Tried to call startCapturing before resetting.'); } this._isCapturing = true; this._captureStartTime = Date.now(); } stopCapturing() { if (!this._isCapturing) { throw new Error('InboundEventLogger: Tried to call stopCapturing while not capturing.'); } this._isCapturing = false; this._captureEndTime = Date.now(); } send() { if (this._isCapturing) { throw new Error('InboundEventLogger: Tried to send captured events while still capturing.'); } sendMessage({ type: 'warn', details: { startTime: this._captureStartTime ?? null, endTime: this._captureEndTime ?? null, inboundEventItems: JSON.stringify(this._capturedInboundEventItems), }, }); } reset() { this._captureStartTime = undefined; this._captureEndTime = undefined; this._capturedInboundEventItems = []; this._isCapturing = false; } maybeCaptureInboundEvent(event: WebViewInboundEvent) { if (this._isCapturing) { const item = { type: 'inbound', timestamp: Date.now(), // Scrubbing up front, rather than just before sending, means // it might be a waste of work -- we may never send. But it's // not a *ton* of work, and it's currently the case that // scrubbed events are much lighter than unscrubbed ones // (unscrubbed events can have very long `content` strings). scrubbedEvent: InboundEventLogger.scrubInboundEvent(event), }; this._capturedInboundEventItems.push(item); } } } ```
/content/code_sandbox/src/webview/js/InboundEventLogger.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,200
```javascript /* @flow strict-local */ /** * Collapse an open spoiler block with animation. * * Does what `collapse_spoiler` in static/js/spoilers.js in the web * does, only departing as appropriate to adapt to mobile. */ const collapseSpoiler = (spoiler: HTMLElement) => { // Translation of zulip/zulip@f3011d3b7 out of jQuery. We need // `spoiler`'s computed content height, which excludes padding. // Things like `clientHeight` and `offsetHeight` include padding. const computedHeight = getComputedStyle(spoiler).height; // Set height to rendered height on next frame, then to zero on following // frame to allow CSS transition animation to work requestAnimationFrame(() => { spoiler.style.height = computedHeight; spoiler.classList.remove('spoiler-content-open'); requestAnimationFrame(() => { spoiler.style.height = '0px'; }); }); }; /** * Expand a closed spoiler block with animation. * * Does what `expand_spoiler` in static/js/spoilers.js in the web app * does, only departing as appropriate to adapt to mobile. */ const expandSpoiler = (spoiler: HTMLElement) => { // Normally, the height of the spoiler block is not defined // absolutely on the `spoiler-content-open` class, but just set to // `auto` (i.e. the height of the content). CSS animations do not // work with properties set to `auto`, so we get the actual height // of the content here and temporarily put it explicitly on the // element styling to allow the transition to work. const spoilerHeight = spoiler.scrollHeight; spoiler.style.height = `${spoilerHeight}px`; // The `spoiler-content-open` class has CSS animations defined on it which // will trigger on the frame after this class change. spoiler.classList.add('spoiler-content-open'); const callback = () => { spoiler.removeEventListener('transitionend', callback); // When the CSS transition is over, reset the height to auto // This keeps things working if, e.g., the viewport is resized spoiler.style.height = ''; }; spoiler.addEventListener('transitionend', callback); }; /** * Toggle the spoiler state - collapsed <-> open. * * Detects the state of the spoiler block and toggles that. */ // The structure we're handling looks like this: // // <div class="spoiler-block"> // <div class="spoiler-header"> // <span class="spoiler-button" aria-expanded="false"> // <span class="spoiler-arrow"></span> // </span> // <p>Always visible heading</p> // </div> // // <div class="spoiler-content"> // <p>This text won't be visible until the user clicks.</p> // </div> // </div> // // The above represents what we get from the server plus some tweaks // that have been made client-side, in `rewriteHtml`. (The web app's // version of the above can be seen in // templates/zerver/app/markdown_help.html, the user-facing Markdown // guide, at c5dc9d386.) export const toggleSpoiler = (spoilerHeader: HTMLElement) => { const spoilerBlock = spoilerHeader.parentElement; if (!spoilerBlock) { return; } const button = spoilerHeader.querySelector('.spoiler-button'); const arrow = spoilerBlock.querySelector('.spoiler-arrow'); const spoilerContent = spoilerBlock.querySelector('.spoiler-content'); if (!arrow || !button || !spoilerContent) { // eslint-disable-next-line no-console console.warn('Malformed spoiler block'); return; } if (spoilerContent.classList.contains('spoiler-content-open')) { // Content was open, we are collapsing arrow.classList.remove('spoiler-button-open'); // Modify ARIA roles for screen readers button.setAttribute('aria-expanded', 'false'); spoilerContent.setAttribute('aria-hidden', 'true'); collapseSpoiler(spoilerContent); } else { // Content was closed, we are expanding arrow.classList.add('spoiler-button-open'); // Modify ARIA roles for screen readers button.setAttribute('aria-expanded', 'true'); spoilerContent.setAttribute('aria-hidden', 'false'); expandSpoiler(spoilerContent); } }; ```
/content/code_sandbox/src/webview/js/spoilers.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
942
```javascript /* @flow strict-local */ import type { Auth } from '../../types'; import { isUrlOnRealm } from '../../utils/url'; /** List of routes which accept the API key appended as a GET parameter. */ const inlineApiRoutes: $ReadOnlyArray<RegExp> = [ '^/user_uploads/', '^/thumbnail$', '^/avatar/', ].map(r => new RegExp(r)); /** * Rewrite the source URLs of <img> elements under the given root, inclusive. * * 1. Make relative URLs absolute, with a path based on the Zulip realm rather * than the document location. * 2. If the source URL names an endpoint known to require authentication, * inject an API key into its query parameters. */ const rewriteImageUrls = (auth: Auth, element: Element | Document) => { const realm = auth.realm; // Find the image elements to act on. const imageTags: $ReadOnlyArray<HTMLImageElement> = [].concat( element instanceof HTMLImageElement ? [element] : [], Array.from(element.getElementsByTagName('img')), ); imageTags.forEach(img => { // Not `img.src`, because that getter absolutizes relative URLs itself. const actualSrc = img.getAttribute('src'); // A missing `src` is invalid per the HTML spec. if (actualSrc == null) { return; } // 1: Absolutize the URL appropriately. let fixedSrc; try { fixedSrc = new URL(actualSrc, realm); } catch { // If the URL doesn't parse, there's nothing we can do for it. // Just in case it doesn't parse as relative to `realm` but *would* // parse as relative to the webview's base URL, though, rewrite it to // something that definitely points nowhere. img.src = 'about:blank'; return; } // 2: Inject the API key where needed. if (isUrlOnRealm(fixedSrc, realm)) { if (inlineApiRoutes.some(regexp => regexp.test(fixedSrc.pathname))) { // Ideally we'd just use `searchParams`, but that was new in Chrome 51 // (and Safari 10). const delimiter = fixedSrc.search ? '&' : ''; fixedSrc.search += `${delimiter}api_key=${auth.apiKey}`; } } // The condition is an optimization, in case setting `src` is slow. if (img.src !== fixedSrc.toString()) { img.src = fixedSrc.toString(); } }); }; /** * Rewrite the 'time' elements under the given root, inclusive, to make them more readable. * * 1. Changes text to localized human readable date-time. * 2. Adds 'original-text' attribrute, to show original text alert dialog on press. */ const rewriteTime = (element: Element | Document) => { // Skip trying to do this if we don't have the necessary browser feature. // The time ends up shown with its literal text, which is an ISO 8601 // string. This happens before Chrome 62 (and Safari 10). if (typeof HTMLTimeElement !== 'function') { return; } // Find the time elements to act on. const timeElements = [].concat( element instanceof HTMLTimeElement ? [element] : [], Array.from(element.getElementsByTagName('time')), ); timeElements.forEach(elem => { // Present only because the Flow DOM libdef does not have a specific definition // for `getElementsByTagName('time')`, so the typedef of `timeElements` is wider // than it actually is. See path_to_url if (!(elem instanceof HTMLTimeElement)) { return; } const timeStamp = elem.dateTime; const text = elem.innerText; const d = new Date(timeStamp); elem.setAttribute('original-text', text); elem.innerText = ` ${d.toLocaleString(undefined, { dateStyle: 'full', timeStyle: 'short', })}`; }); }; /** * Add missing elements to spoiler blocks under the given root, inclusive. * * 1. Adds 'Spoiler' header text if missing. * 2. Adds the spoiler expanded arrow indicator. The arrow is rendered using CSS. * * Does what the web app does, only departing as appropriate to adapt * to mobile. The corresponding code is in * static/js/rendered_markdown.js, at the spot you find searching for * "spoiler-header". That's lines 181-192 in zulip/zulip@c5dc9d386. */ const rewriteSpoilers = (element: Element | Document) => { const spoilerHeaders: NodeList<HTMLElement> = element.querySelectorAll('div.spoiler-header'); spoilerHeaders.forEach(e => { // Add the expand/collapse button to spoiler blocks const toggle_button_html = '<span class="spoiler-button" aria-expanded="false"><span class="spoiler-arrow"></span></span>'; if (e.innerText === '') { // If a spoiler block has no header content, it should have a default header. // We do this client side to allow for i18n by the client. const header_html = '<p>Spoiler</p>'; // TODO: Localize this text. e.innerHTML = toggle_button_html + header_html; } else { e.innerHTML = toggle_button_html + e.innerHTML; } }); }; /** * Modify relevant parts of the rendered DOM tree under the given root, * inclusive, to ensure functionality. * * DEPRECATED: If no root element is specified, the entire document is considered. */ const rewriteHtml = (auth: Auth, element: Element | Document = document) => { rewriteImageUrls(auth, element); rewriteTime(element); rewriteSpoilers(element); // TODO add "(guest)" marker on @-mentions }; export default rewriteHtml; ```
/content/code_sandbox/src/webview/js/rewriteHtml.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,262
```javascript /** * Main entry point for our code running inside the message-list WebView. * * This file, together with the code it imports, does not run in the normal * React Native environment. Instead, it runs in a browser environment * (Chrome when on Android, Safari when on iOS), inside a WebView, where we * present the message list. * * The way this code gets run is: * * The script `tools/generate-webview-js`, using Babel and Rollup, * compiles this file and its imports. The result goes into * `./generatedEs3.js`, as a giant string literal. * * That file `generatedEs3.js` is imported by `./script.js`. There the * compiled code it contains, along with some other code, goes inside a * `<script>` element in an HTML fragment string. * * That string in turn becomes part of the HTML string passed in the * `source` prop of the `WebView` component created in `MessageList`. * * This code does not run at the top level of the `<script>` element. * Rather, it goes inside an event listener for `DOMContentLoaded`. * (See `script.js`.) * * @flow strict-local */ /* eslint-disable no-useless-return */ import type { Auth } from '../../types'; import type { WebViewInboundEvent, WebViewInboundEventContent, WebViewInboundEventFetching, WebViewInboundEventTyping, WebViewInboundEventReady, WebViewInboundEventSetRead, WebViewInboundEventSetDoNotMarkAsRead, } from '../generateInboundEvents'; import { makeUserId } from '../../api/idTypes'; import InboundEventLogger from './InboundEventLogger'; import sendMessage from './sendMessage'; import rewriteHtml from './rewriteHtml'; import { toggleSpoiler } from './spoilers'; import { ensureUnreachable } from '../../generics'; /* * Supported platforms: * * * (When updating these, be sure to update tools/generate-webview-js too.) * * * We support iOS 14. So this code needs to work on Mobile Safari 14. * Graceful degradation is acceptable below iOS 15 / Mobile Safari 15. * * * For Android, core functionality needs to work on Chrome 51. * Graceful degradation is acceptable below Chrome 74. * * * These versions are found in stock images for Android 7 Nougat * and Android 10, respectively, for convenient testing. * * * (Note that Android's Chrome auto-updates independently of the OS, and * the large majority of Android users have a fully-updated Chrome -- * more recent than the Safari on most iOS devices.) * * * See docs/architecture/platform-versions.md for data and discussion * about our version-support strategy. */ /** * A copy of RN's `Platform.OS`. * * Provided by the template in `script.js`. */ declare var platformOS: string; /** * The value of `process.env.NODE_ENV === 'development'` in RN-land. * * Provided by the template in `script.js`. */ declare var isDevelopment: boolean; /** * used to control behavior based on debug settings. * defined in `handleInitialLoad`. * declared globally so as to use across functions. */ declare var doNotMarkMessagesAsRead: boolean; // We pull out document.body in one place, and check it's not null, in order // to provide that assertion to the type-checker. const documentBody = document.body; if (!documentBody) { throw new Error('No document.body element!'); } const msglistElementsDiv = document.querySelector('div#msglist-elements'); if (!msglistElementsDiv) { throw new Error('No div#msglist-elements element!'); } const escapeHtml = (text: string): string => { const element = document.createElement('div'); element.innerText = text; return element.innerHTML; }; window.onerror = (message: string, source: string, line: number, column: number, error: Error) => { if (isDevelopment) { // In development, show a detailed error banner for debugging. const elementJsError = document.getElementById('js-error-detailed'); if (elementJsError) { elementJsError.innerHTML = [ `Message: ${message}`, `Source: ${source}`, `Line: ${line}:${column}`, `Error: ${JSON.stringify(error)}`, '', ] .map(escapeHtml) .join('<br>'); } } else { // In a release build published for normal use, just show a short, // friendly, generic error message. We'll report the error details // via Sentry, below. const elementJsError = document.getElementById('js-error-plain'); const elementSheetGenerated = document.getElementById('generated-styles'); const elementSheetHide = document.getElementById('style-hide-js-error-plain'); if ( elementJsError && elementSheetGenerated && elementSheetHide && elementSheetHide instanceof HTMLStyleElement && elementSheetHide.sheet && elementSheetGenerated instanceof HTMLStyleElement && elementSheetGenerated.sheet ) { elementSheetHide.sheet.disabled = true; const height = elementJsError.offsetHeight; elementSheetGenerated.sheet.insertRule(`.header-wrapper { top: ${height}px; }`, 0); } } const userAgent = window.navigator.userAgent; sendMessage({ type: 'error', details: { message, source, line, column, userAgent, error, }, }); return true; }; const eventLogger = new InboundEventLogger(); eventLogger.startCapturing(); // After 10 seconds, if the loading placeholders are *still* visible, // we want to know all the inbound events that were received in that // time (with sensitive info redacted, of course). setTimeout(() => { const placeholdersDiv = document.getElementById('message-loading'); eventLogger.stopCapturing(); if (placeholdersDiv && !placeholdersDiv.classList.contains('hidden')) { eventLogger.send(); } eventLogger.reset(); }, 10000); const showHideElement = (elementId: string, show: boolean) => { const element = document.getElementById(elementId); if (element) { element.classList.toggle('hidden', !show); } }; /* Cached to avoid re-looking it up all the time. */ let viewportHeight = documentBody.clientHeight; window.addEventListener('resize', event => { const heightChange = documentBody.clientHeight - viewportHeight; viewportHeight = documentBody.clientHeight; // Now we try to scroll to keep the bottom edge of the viewport aligned to // the same content it was before the resize. We assume the browser tried // to keep the top edge aligned instead. // // Mostly, that means if the viewport grew, then the bottom edge moved down, // so we'll scroll back up by the same amount; vice versa if it shrank. // But if we were near the bottom pre-resize, and grew, then there may not // have been room for the bottom edge to move that far down, and we // shouldn't try to compensate -- if we do, we could end up scrolling up // higher than we started. // // If that happened, we'll be at the very bottom now. const maxScrollTop = documentBody.scrollHeight - documentBody.clientHeight; if (documentBody.scrollTop >= maxScrollTop - 1) { // We're at (or within a px of, or beyond) the very bottom of the // content. Don't scroll. // // This does mean if you're near the bottom, and then the viewport grows // by more than that distance, you'll wind up at the very bottom instead // of where you were. That's not our ideal behavior. OTOH it's // mitigated by the fact that in this situation everything that was in // view is still in view. return; } // Scrolling by a positive `top` scrolls down; negative scrolls up. window.scrollBy({ left: 0, top: -heightChange }); }); /* * * Identifying visible messages * */ /** * Returns a "message-list element" visible mid-screen, if any. * * A "message-list element" is a message or one of their siblings that get * laid out among them: e.g. a recipient bar or date separator, but not an * absolutely-positioned overlay. All message-list elements are direct * children of a div#msglist-elements. * * If the middle of the screen is just blank, returns null. */ function midMessageListElement(top: number, bottom: number): ?Element { // The assumption we depend on: any random widgets we draw that aren't // part of a message-list element are drawn *over* the message-list // elements, not under. // // By spec, the elements returned by Document#elementsFromPoint are in // paint order, topmost (and inmost) first. By our assumption, that means // the sequence is: // [ ...(random widgets, if any), // ...(descendants of message-list element), message-list element, // div#msglist-elements, body, html ] const midY = (bottom + top) / 2; const midElements = document.elementsFromPoint(0, midY); if (midElements.length < 4) { // Just [div#msglist-elements, body, html]. return null; } return midElements[midElements.length - 4]; } /** * Find a message element at or near the given element. * * The given element should be a "message-list element"; see * `midMessageListElement` for discussion. * * If the given element is a message, returns that element. Otherwise, * returns the message that comes just after or just before it, depending on * the value of `step`. */ function walkToMessage( start: ?Element, step: 'nextElementSibling' | 'previousElementSibling', ): ?Element { let element: ?Element = start; while (element && !element.classList.contains('message')) { // $FlowFixMe[prop-missing]: doesn't use finite type of `step` element = element[step]; } return element; } /** The first message element in the document. */ function firstMessage(): ?Element { return walkToMessage(msglistElementsDiv.firstElementChild, 'nextElementSibling'); } /** The last message element in the document. */ function lastMessage(): ?Element { return walkToMessage(msglistElementsDiv.lastElementChild, 'previousElementSibling'); } /** The message before the given message, if any. */ function previousMessage(start: Element): ?Element { return walkToMessage(start.previousElementSibling, 'previousElementSibling'); } /** The message after the given message, if any. */ function nextMessage(start: Element): ?Element { return walkToMessage(start.nextElementSibling, 'nextElementSibling'); } /** * An element is visible if any part of it is visible on screen. * * @param top The top of the screen (typically 0) * @param bottom The bottom of the screen (typically body.clientHeight) */ function isVisible(element: Element, top: number, bottom: number): boolean { const rect = element.getBoundingClientRect(); return top < rect.bottom && rect.top < bottom; } /** * The number of pixels of the message that are allowed to be scrolled off * the bottom of the screen when we mark the message as "read". */ // Picked based on the bottom padding of messages in CSS. This doesn't work // so great in cases where messages have the "edited" badge or reaction emojis, // since the user needs to scorll to the bottom of the reaction emoji/edited // badge section for the message to be "read", but it's more important for the // single-line message case to not get inadvertently read than it is for // messages to get marked read exactly when the bottom of the text of the // message comes onto the screen. In the future, we may want more complicated // behaviour here, but this should be fine for now. const messageReadSlop = 16; /** * A visible message is read when its bottom isn't too far down out of view. * * See `messageReadSlop` for specifically how far the bottom might be. The * idea is that a message becomes read when the bottom of its content * scrolls into view, excluding the padding between messages. * * This function doesn't check that the message is visible; it probably * makes sense to call only when `isVisible` is already known to be true. * * @param top The top of the screen (typically 0) * @param bottom The bottom of the screen (typically body.clientHeight) */ function isRead(element: Element, top: number, bottom: number): boolean { return bottom + messageReadSlop >= element.getBoundingClientRect().bottom; } /** Returns some message element which is visible, if any. */ function someVisibleMessage(top: number, bottom: number): ?Element { function checkVisible(candidate: ?Element): ?Element { return candidate && isVisible(candidate, top, bottom) ? candidate : null; } // Algorithm: if some message-list element is visible, then either the // message just before or after it should be visible. If not, we must be // at one end of the message list, meaning either the first or last // message (or both) should be visible. const midElement = midMessageListElement(top, bottom); return ( checkVisible(walkToMessage(midElement, 'previousElementSibling')) || checkVisible(walkToMessage(midElement, 'nextElementSibling')) || checkVisible(firstMessage()) || checkVisible(lastMessage()) ); } /** Returns some message element which is both visible and read, if any. */ function someVisibleReadMessage(top: number, bottom: number): ?Element { function checkReadAndVisible(candidate: ?Element): ?Element { return candidate && isRead(candidate, top, bottom) && isVisible(candidate, top, bottom) ? candidate : null; } // Algorithm: If there's a visible message that isn't read, that means // it's partway off the bottom of the screen. Therefore, either: // * the message above it will be visible and read, or // * there are no visible read messages. const visible = someVisibleMessage(top, bottom); if (!visible) { return visible; } return checkReadAndVisible(visible) || checkReadAndVisible(previousMessage(visible)); } /** * The Zulip message ID of the given message element; throw if not a message. */ function idFromMessage(element: Element): number { const idStr = element.getAttribute('data-msg-id'); if (idStr === null || idStr === undefined) { throw new Error('Bad message element'); } return +idStr; } /** * Returns the IDs of the first and last visible read messages, if any. * * If no messages are both visible and read, the return value has first > last. */ function visibleReadMessageIds(): {| first: number, last: number |} { // Algorithm: We find some message that's both visible and read; then walk // both up and down from there to find all the visible read messages. const top = 0; const bottom = viewportHeight; let first = Number.MAX_SAFE_INTEGER; let last = 0; // Walk through visible-and-read elements, observing message IDs. function walkElements(start: ?Element, step: 'nextElementSibling' | 'previousElementSibling') { let element: ?Element = start; while (element && isVisible(element, top, bottom) && isRead(element, top, bottom)) { if (element.classList.contains('message')) { const id = idFromMessage(element); first = Math.min(first, id); last = Math.max(last, id); } // $FlowFixMe[prop-missing]: doesn't use finite type of `step` element = element[step]; } } const start = someVisibleReadMessage(top, bottom); walkElements(start, 'nextElementSibling'); walkElements(start, 'previousElementSibling'); return { first, last }; } /** DEPRECATED */ const getMessageIdFromElement = (element: Element, defaultValue: number = -1): number => { const msgElement = element.closest('.msglist-element'); return msgElement ? +msgElement.getAttribute('data-msg-id') : defaultValue; }; /** * Set the 'data-read' attribute to a given range of message elements. * This is styled with css to indicate visually what messages are being read. */ const setMessagesReadAttributes = rangeHull => { let element = document.querySelector(`[data-msg-id='${rangeHull.first}']`); while (element) { if (element.classList.contains('message')) { element.setAttribute('data-read', 'true'); if (idFromMessage(element) >= rangeHull.last) { break; } } element = element.nextElementSibling; } }; /* * * Reporting scrolls to outside, to mark messages as read * */ /** * The range of message IDs that were both visible and read whenever we last * checked. */ let prevMessageRange = visibleReadMessageIds(); const sendScrollMessage = () => { const messageRange = visibleReadMessageIds(); // rangeHull is the convex hull of the previous range and the new one. // When the user is actively scrolling, the browser gives us scroll events // only occasionally, so we use this to interpolate scrolling past the // messages in between, as a partial workaround. const rangeHull = { first: Math.min(prevMessageRange.first, messageRange.first), last: Math.max(prevMessageRange.last, messageRange.last), }; sendMessage({ type: 'scroll', // See WebViewOutboundEventScroll for the meanings of these properties. offsetHeight: documentBody.offsetHeight, innerHeight: window.innerHeight, scrollY: window.scrollY, startMessageId: rangeHull.first, endMessageId: rangeHull.last, }); if (!doNotMarkMessagesAsRead) { setMessagesReadAttributes(rangeHull); } // If there are no visible + read messages (for instance, the entire screen // is taken up by a single large message), then we don't want to update // prevMessageRange. This way, if the user scrolled past some messages to // get here, then even though `messageRange` was empty this time and so we // didn't mark any messages as read just now, we'll include those in // `rangeHull` the next time the user scrolls and so we'll mark them as read // then. if (messageRange.first < messageRange.last) { prevMessageRange = messageRange; } }; // If the message list is too short to scroll, fake a scroll event // in order to cause the messages to be marked as read. const sendScrollMessageIfListShort = () => { if (documentBody.scrollHeight === documentBody.clientHeight) { sendScrollMessage(); } }; /** * Disable reporting scrolls to the outside to mark messages as read. * * This is set while we're first setting up after the content loads, and * while we're handling `message` events from the outside and potentially * rewriting the content. */ let scrollEventsDisabled = true; let hasLongPressed = false; let longPressTimeout = undefined; let lastTouchPositionX = -1; let lastTouchPositionY = -1; const handleScrollEvent = () => { clearTimeout(longPressTimeout); if (scrollEventsDisabled) { return; } sendScrollMessage(); const nearEnd = documentBody.offsetHeight - window.scrollY - window.innerHeight > 100; showHideElement('scroll-bottom', nearEnd); }; window.addEventListener('scroll', handleScrollEvent); /* * * Updating message content, and re-scrolling * */ type ScrollTarget = | {| type: 'none' |} | {| type: 'bottom' |} | {| type: 'anchor', messageId: number | null |} | {| type: 'preserve', msgId: number, prevBoundTop: number |}; const scrollToBottom = () => { window.scroll({ left: 0, top: documentBody.scrollHeight, behavior: 'smooth' }); }; const isNearBottom = (): boolean => documentBody.scrollHeight - 100 < documentBody.scrollTop + documentBody.clientHeight; const scrollToBottomIfNearEnd = () => { if (isNearBottom()) { scrollToBottom(); } }; const scrollToMessage = (messageId: number | null) => { const targetNode = messageId !== null ? document.getElementById(`msg-${messageId}`) : null; if (targetNode) { targetNode.scrollIntoView({ block: 'start' }); } else { window.scroll({ left: 0, top: documentBody.scrollHeight + 200 }); } }; // Try to identify a message on screen and its location, so we can // scroll the corresponding message to the same place afterward. const findPreserveTarget = (): ScrollTarget => { const message = someVisibleMessage(0, viewportHeight); if (!message) { // TODO log this -- it's an error which the user will notice. // (We don't attempt this unless there are messages already, // which we really want to keep steady in view.) return { type: 'none' }; } const messageId = idFromMessage(message); const prevBoundRect = message.getBoundingClientRect(); return { type: 'preserve', msgId: messageId, prevBoundTop: prevBoundRect.top }; }; // Scroll the given message to the same height it was at before. const scrollToPreserve = (msgId: number, prevBoundTop: number) => { const newElement = document.getElementById(`msg-${msgId}`); if (!newElement) { // TODO log this -- it's an error which the user will notice. return; } const newBoundRect = newElement.getBoundingClientRect(); window.scrollBy(0, newBoundRect.top - prevBoundTop); }; /** * Run a function after layout properties have updated from DOM changes. * * This is important if we have just set innerHTML and need to read * properties like `scrollHeight` from the DOM, as the re-layout may happen * asynchronously. */ const runAfterLayout = (fn: () => void) => { if (platformOS === 'android') { // On Android/Chrome, empirically the updates happen synchronously, so // there's no need to delay. See discussion: // path_to_url fn(); return; } // On iOS/Safari, we must wait. See: // path_to_url requestAnimationFrame(() => { // this runs immediately before the next repaint fn(); }); }; const handleInboundEventContent = (uevent: WebViewInboundEventContent) => { const { scrollStrategy } = uevent; let target: ScrollTarget; switch (scrollStrategy) { case 'none': target = { type: 'none' }; break; case 'scroll-to-anchor': target = { type: 'anchor', messageId: uevent.scrollMessageId }; break; case 'scroll-to-bottom-if-near-bottom': target = isNearBottom() ? { type: 'bottom' } : findPreserveTarget(); break; case 'preserve-position': target = findPreserveTarget(); break; default: ensureUnreachable(scrollStrategy); target = findPreserveTarget(); break; } msglistElementsDiv.innerHTML = uevent.content; rewriteHtml(uevent.auth); runAfterLayout(() => { if (target.type === 'bottom') { scrollToBottom(); } else if (target.type === 'anchor') { scrollToMessage(target.messageId); } else if (target.type === 'preserve') { scrollToPreserve(target.msgId, target.prevBoundTop); } sendScrollMessageIfListShort(); }); }; /** * Called by the `script.js` template immediately after this module's toplevel. * * (This provides a way for the template to pass arguments for this code to * use at initialization.) */ export const handleInitialLoad = ( scrollMessageId: number | null, // The `realm` part of an `Auth` object is a URL object. It's passed // in its stringified form. rawAuth: {| ...$Diff<Auth, {| realm: mixed |}>, realm: string |}, ) => { const auth: Auth = { ...rawAuth, realm: new URL(rawAuth.realm) }; // Since its version 5.x, the `react-native-webview` library dispatches our // `message` events at `window` on iOS but `document` on Android. if (platformOS === 'ios') { /* eslint-disable-next-line no-use-before-define */ window.addEventListener('message', handleMessageEvent); } else { /* eslint-disable-next-line no-use-before-define */ document.addEventListener('message', handleMessageEvent); } scrollToMessage(scrollMessageId); rewriteHtml(auth); sendScrollMessageIfListShort(); scrollEventsDisabled = false; }; /* * * Handling other message-from-outside events * */ const handleInboundEventFetching = (uevent: WebViewInboundEventFetching) => { showHideElement('message-loading', uevent.showMessagePlaceholders); showHideElement('spinner-older', uevent.fetchingOlder); showHideElement('spinner-newer', uevent.fetchingNewer); }; const handleInboundEventTyping = (uevent: WebViewInboundEventTyping) => { const elementTyping = document.getElementById('typing'); if (elementTyping) { elementTyping.innerHTML = uevent.content; runAfterLayout(() => scrollToBottomIfNearEnd()); } }; let readyRetryInterval: IntervalID | void = undefined; const signalReadyForEvents = () => { sendMessage({ type: 'ready' }); // Keep retrying sending the ready event, in case the first one is sent while // the queue isn't ready. While this isn't something I've observed in testing, // we've previously had bugs that were caused by this (for instance, #3078) readyRetryInterval = setInterval(() => { sendMessage({ type: 'ready' }); }, 100); }; /** * Stop resending the handshake message once we confirm that the channel is * ready. */ const handleInboundEventReady = (uevent: WebViewInboundEventReady) => { clearInterval(readyRetryInterval); }; function setReadFlags(messageIds, value) { const selector = messageIds.map(id => `[data-msg-id="${id}"]`).join(','); const messageElements = document.querySelectorAll(selector); messageElements.forEach(element => { element.setAttribute('data-read', JSON.stringify(value)); }); } const handleInboundEventSetDoNotMarkAsRead = (uevent: WebViewInboundEventSetDoNotMarkAsRead) => { doNotMarkMessagesAsRead = uevent.value; }; /** * Handles messages that have been read outside of the WebView */ const handleInboundEventMessagesSetRead = (uevent: WebViewInboundEventSetRead) => { if (uevent.messageIds.length === 0) { return; } setReadFlags(uevent.messageIds, uevent.value); }; const inboundEventHandlers = { content: handleInboundEventContent, fetching: handleInboundEventFetching, typing: handleInboundEventTyping, ready: handleInboundEventReady, 'set-do-not-mark-as-read': handleInboundEventSetDoNotMarkAsRead, 'set-read': handleInboundEventMessagesSetRead, }; // See `handleInitialLoad` for how this gets subscribed to events. // See `sendInboundEvents` on `MessageList` for where they're sent from. const handleMessageEvent: MessageEventListener = e => { scrollEventsDisabled = true; // This decoding inverts `base64Utf8Encode`. const decodedData = decodeURIComponent(escape(window.atob(e.data))); const rawInboundEvents = JSON.parse(decodedData); const inboundEvents: $ReadOnlyArray<WebViewInboundEvent> = rawInboundEvents.map(inboundEvent => ({ ...inboundEvent, // A URL object doesn't round-trip through JSON; we get the string // representation. So, "revive" it back into a URL object. ...(inboundEvent.auth ? { auth: { ...inboundEvent.auth, realm: new URL(inboundEvent.auth.realm) } } : {}), })); inboundEvents.forEach((uevent: WebViewInboundEvent) => { eventLogger.maybeCaptureInboundEvent(uevent); // $FlowFixMe[incompatible-type] // $FlowFixMe[prop-missing] inboundEventHandlers[uevent.type](uevent); }); scrollEventsDisabled = false; }; /* * * Handling user touches * */ /** * If the given message is muted, reveal it and all consecutive following * messages from the same user. */ const revealMutedMessages = (message: Element) => { let messageNode = message; do { messageNode.setAttribute('data-mute-state', 'shown'); messageNode = nextMessage(messageNode); } while (messageNode && messageNode.classList.contains('message-brief')); }; const requireAttribute = (e: Element, name: string): string => { const value = e.getAttribute(name); if (value === null || value === undefined) { throw new Error(`Missing expected attribute ${name}`); } return value; }; /** * Returns the integer parsed value of a DOM element attribute. * * Throws if parsing fails. */ const requireNumericAttribute = (e: Element, name: string): number => { const value = requireAttribute(e, name); const parsedValue = parseInt(value, 10); if (Number.isNaN(parsedValue)) { throw new Error(`Could not parse attribute ${name} value '${value}' as integer`); } return parsedValue; }; documentBody.addEventListener('click', (e: MouseEvent) => { e.preventDefault(); clearTimeout(longPressTimeout); /* Without a flag `hasLongPressed`, both the short press and the long * press actions get triggered. See PR #3404 for more context. */ if (hasLongPressed) { hasLongPressed = false; return; } const { target } = e; if (!(target instanceof Element)) { return; } if (target.matches('.scroll-bottom')) { scrollToBottom(); return; } if (target.matches('.avatar-img') || target.matches('.name-and-status-emoji')) { sendMessage({ type: 'request-user-profile', fromUserId: makeUserId(requireNumericAttribute(target, 'data-sender-id')), }); return; } if (target.matches('.header')) { sendMessage({ type: 'narrow', narrow: requireAttribute(target, 'data-narrow'), }); return; } if (target.matches('.user-mention')) { sendMessage({ type: 'mention', userId: makeUserId(requireNumericAttribute(target, 'data-user-id')), }); return; } /* Should we pull up the lightbox? For comparison, see the web app's * static/js/lightbox.js , starting at the `#main_div` click handler. */ const inlineImageLink = target.closest('.message_inline_image a'); if ( inlineImageLink /* The web app displays certain videos inline, but on mobile * we'd rather let another app handle them, as links. */ && !inlineImageLink.closest('.message_inline_video, .youtube-video, .vimeo-video') ) { sendMessage({ type: 'image', src: requireAttribute(inlineImageLink, 'href'), // TODO: should be `src` / `data-src-fullsize`. messageId: getMessageIdFromElement(inlineImageLink), }); return; } if (target.matches('.reaction')) { sendMessage({ type: 'reaction', name: requireAttribute(target, 'data-name'), code: requireAttribute(target, 'data-code'), reactionType: requireAttribute(target, 'data-type'), messageId: getMessageIdFromElement(target), voted: target.classList.contains('self-voted'), }); return; } if (target.matches('.poll-vote')) { const messageElement = target.closest('.message'); if (!messageElement) { throw new Error('Message element not found'); } // This duplicates some logic from PollData.handle.vote.outbound in // @zulip/shared/js/poll_data.js, but it's much simpler to just duplicate // it than it is to thread a callback all the way over here. const current_vote = requireAttribute(target, 'data-voted') === 'true'; const vote = current_vote ? -1 : 1; sendMessage({ type: 'vote', messageId: requireNumericAttribute(messageElement, 'data-msg-id'), key: requireAttribute(target, 'data-key'), vote, }); target.setAttribute('data-voted', (!current_vote).toString()); target.innerText = (parseInt(target.innerText, 10) + vote).toString(); return; } if (target.matches('time')) { const originalText = requireAttribute(target, 'original-text'); sendMessage({ type: 'time', originalText, }); } const closestA = target.closest('a'); if (closestA) { sendMessage({ type: 'url', href: requireAttribute(closestA, 'href'), messageId: getMessageIdFromElement(closestA), }); return; } const spoilerHeader = target.closest('.spoiler-header'); if (spoilerHeader instanceof HTMLElement) { toggleSpoiler(spoilerHeader); return; } const messageElement = target.closest('.message-brief'); if (messageElement) { messageElement.getElementsByClassName('msg-timestamp')[0].classList.toggle('show'); return; } }); const handleLongPress = (target: Element) => { // The logic is believed not to cover all the cases it should; for // example, multi-touch events. Better would be to either find a // library we can use which strives to handle all that complexity, or // get long-press events from the platform. hasLongPressed = true; const reactionNode = target.closest('.reaction'); if (reactionNode) { sendMessage({ type: 'reactionDetails', messageId: getMessageIdFromElement(target), reactionName: requireAttribute(reactionNode, 'data-name'), }); return; } // Prettier bug on nested ternary /* prettier-ignore */ const targetType = target.matches('.header') ? 'header' : target.matches('a') ? 'link' : 'message'; const messageNode = target.closest('.message'); if ( targetType === 'message' && messageNode && messageNode.getAttribute('data-mute-state') === 'hidden' ) { revealMutedMessages(messageNode); return; } sendMessage({ type: 'longPress', target: targetType, messageId: getMessageIdFromElement(target), href: target.matches('a') ? requireAttribute(target, 'href') : null, }); }; documentBody.addEventListener('touchstart', (e: TouchEvent) => { const { target } = e; if (e.changedTouches[0].pageX < 20 || !(target instanceof Element)) { return; } lastTouchPositionX = e.changedTouches[0].pageX; lastTouchPositionY = e.changedTouches[0].pageY; hasLongPressed = false; clearTimeout(longPressTimeout); longPressTimeout = setTimeout(() => handleLongPress(target), 500); }); const isNearPositions = (x1: number = 0, y1: number = 0, x2: number = 0, y2: number = 0): boolean => Math.abs(x1 - x2) < 10 && Math.abs(y1 - y2) < 10; documentBody.addEventListener('touchend', (e: TouchEvent) => { if ( isNearPositions( lastTouchPositionX, lastTouchPositionY, e.changedTouches[0].pageX, e.changedTouches[0].pageY, ) ) { clearTimeout(longPressTimeout); } }); documentBody.addEventListener('touchcancel', (e: TouchEvent) => { clearTimeout(longPressTimeout); }); documentBody.addEventListener('touchmove', (e: TouchEvent) => { clearTimeout(longPressTimeout); }); documentBody.addEventListener('drag', (e: DragEvent) => { clearTimeout(longPressTimeout); }); // It's possible we could call this earlier, and would see some performance // benifit from doing so, since js.js takes about 16ms to run on a Pixel 3a. // However, I don't see that as being worth the possible bugs from things // loading too early. signalReadyForEvents(); ```
/content/code_sandbox/src/webview/js/js.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
8,097
```javascript /* @flow strict-local */ export default ` !function(){"use strict";function o(o){var t=["MSIE ","Trident/","Edge/"];return new RegExp(t.join("|")).test(o)}function t(){function t(o,t){this.scrollLeft=o,this.scrollTop=t}function r(o){return.5*(1-Math.cos(Math.PI*o))}function i(o){if(null===o||"object"!=typeof o||void 0===o.behavior||"auto"===o.behavior||"instant"===o.behavior)return!0;if("object"==typeof o&&"smooth"===o.behavior)return!1;throw new TypeError("behavior member of ScrollOptions "+o.behavior+" is not a valid value for enumeration ScrollBehavior.")}function s(o,t){return"Y"===t?o.clientHeight+h<o.scrollHeight:"X"===t?o.clientWidth+h<o.scrollWidth:void 0}function c(o,t){var e=l.getComputedStyle(o,null)["overflow"+t];return"auto"===e||"scroll"===e}function n(o){var t=s(o,"Y")&&c(o,"Y"),l=s(o,"X")&&c(o,"X");return t||l}function f(o){var t;do{t=(o=o.parentNode)===e.body}while(!1===t&&!1===n(o));return t=null,o}function a(o){var t,e,i,s=(y()-o.startTime)/v;t=r(s=s>1?1:s),e=o.startX+(o.x-o.startX)*t,i=o.startY+(o.y-o.startY)*t,o.method.call(o.scrollable,e,i),e===o.x&&i===o.y||l.requestAnimationFrame(a.bind(l,o))}function p(o,r,i){var s,c,n,f,p=y();o===e.body?(s=l,c=l.scrollX||l.pageXOffset,n=l.scrollY||l.pageYOffset,f=u.scroll):(s=o,c=o.scrollLeft,n=o.scrollTop,f=t),a({scrollable:s,method:f,startTime:p,startX:c,startY:n,x:r,y:i})}if(!("scrollBehavior"in e.documentElement.style&&!0!==l.__forceSmoothScrollPolyfill__)){var d=l.HTMLElement||l.Element,v=468,h=o(l.navigator.userAgent)?1:0,u={scroll:l.scroll||l.scrollTo,scrollBy:l.scrollBy,elementScroll:d.prototype.scroll||t,scrollIntoView:d.prototype.scrollIntoView},y=l.performance&&l.performance.now?l.performance.now.bind(l.performance):Date.now;l.scroll=l.scrollTo=function(){void 0!==arguments[0]&&(!0!==i(arguments[0])?p.call(l,e.body,void 0!==arguments[0].left?~~arguments[0].left:l.scrollX||l.pageXOffset,void 0!==arguments[0].top?~~arguments[0].top:l.scrollY||l.pageYOffset):u.scroll.call(l,void 0!==arguments[0].left?arguments[0].left:"object"!=typeof arguments[0]?arguments[0]:l.scrollX||l.pageXOffset,void 0!==arguments[0].top?arguments[0].top:void 0!==arguments[1]?arguments[1]:l.scrollY||l.pageYOffset))},l.scrollBy=function(){void 0!==arguments[0]&&(i(arguments[0])?u.scrollBy.call(l,void 0!==arguments[0].left?arguments[0].left:"object"!=typeof arguments[0]?arguments[0]:0,void 0!==arguments[0].top?arguments[0].top:void 0!==arguments[1]?arguments[1]:0):p.call(l,e.body,~~arguments[0].left+(l.scrollX||l.pageXOffset),~~arguments[0].top+(l.scrollY||l.pageYOffset)))},d.prototype.scroll=d.prototype.scrollTo=function(){if(void 0!==arguments[0])if(!0!==i(arguments[0])){var o=arguments[0].left,t=arguments[0].top;p.call(this,this,void 0===o?this.scrollLeft:~~o,void 0===t?this.scrollTop:~~t)}else{if("number"==typeof arguments[0]&&void 0===arguments[1])throw new SyntaxError("Value couldn't be converted");u.elementScroll.call(this,void 0!==arguments[0].left?~~arguments[0].left:"object"!=typeof arguments[0]?~~arguments[0]:this.scrollLeft,void 0!==arguments[0].top?~~arguments[0].top:void 0!==arguments[1]?~~arguments[1]:this.scrollTop)}},d.prototype.scrollBy=function(){void 0!==arguments[0]&&(!0!==i(arguments[0])?this.scroll({left:~~arguments[0].left+this.scrollLeft,top:~~arguments[0].top+this.scrollTop,behavior:arguments[0].behavior}):u.elementScroll.call(this,void 0!==arguments[0].left?~~arguments[0].left+this.scrollLeft:~~arguments[0]+this.scrollLeft,void 0!==arguments[0].top?~~arguments[0].top+this.scrollTop:~~arguments[1]+this.scrollTop))},d.prototype.scrollIntoView=function(){if(!0!==i(arguments[0])){var o=f(this),t=o.getBoundingClientRect(),r=this.getBoundingClientRect();o!==e.body?(p.call(this,o,o.scrollLeft+r.left-t.left,o.scrollTop+r.top-t.top),"fixed"!==l.getComputedStyle(o).position&&l.scrollBy({left:t.left,top:t.top,behavior:"smooth"})):l.scrollBy({left:r.left,top:r.top,behavior:"smooth"})}else u.scrollIntoView.call(this,void 0===arguments[0]||arguments[0])}}}var l=window,e=document;"object"==typeof exports?module.exports={polyfill:t}:t()}(); `; ```
/content/code_sandbox/src/webview/js/smoothScroll.min.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,247
```javascript /* @flow strict-local */ import type { WebViewOutboundEvent } from '../handleOutboundEvents'; export default (msg: WebViewOutboundEvent) => { window.ReactNativeWebView.postMessage(JSON.stringify(msg)); }; ```
/content/code_sandbox/src/webview/js/sendMessage.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
45
```javascript /* * This is a GENERATED file -- do not edit. * To make changes: * 1. Edit `js.js` or the files it imports, which together make up * the source for this file. * 2. Run `tools/generate-webview-js`. * * @generated * @flow strict */ export default ` 'use strict'; var compiledWebviewJs = (function (exports) { 'use strict'; function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } const makeUserId = id => id; var sendMessage = (msg => { window.ReactNativeWebView.postMessage(JSON.stringify(msg)); }); const placeholdersDivTagFromContent = content => { const match = /<div id="message-loading" class="(?:hidden)?">/.exec(content); return match !== null ? match[0] : null; }; class InboundEventLogger { static scrubInboundEvent(event) { switch (event.type) { case 'content': { return { type: event.type, scrollMessageId: event.scrollMessageId, auth: 'redacted', content: placeholdersDivTagFromContent(event.content), scrollStrategy: event.scrollStrategy }; } case 'fetching': { return { type: event.type, showMessagePlaceholders: event.showMessagePlaceholders, fetchingOlder: event.fetchingOlder, fetchingNewer: event.fetchingNewer }; } case 'typing': { return { type: event.type, content: event.content !== '' }; } case 'ready': { return { type: event.type }; } case 'set-do-not-mark-as-read': { return { type: event.type, value: event.value }; } case 'set-read': { return { type: event.type, value: event.value, messageIds: event.messageIds }; } default: { return { type: event.type }; } } } constructor() { this._isCapturing = false; this._capturedInboundEventItems = []; } startCapturing() { if (this._isCapturing) { throw new Error('InboundEventLogger: Tried to call startCapturing while already capturing.'); } else if (this._capturedInboundEventItems.length > 0 || this._captureEndTime !== undefined) { throw new Error('InboundEventLogger: Tried to call startCapturing before resetting.'); } this._isCapturing = true; this._captureStartTime = Date.now(); } stopCapturing() { if (!this._isCapturing) { throw new Error('InboundEventLogger: Tried to call stopCapturing while not capturing.'); } this._isCapturing = false; this._captureEndTime = Date.now(); } send() { var _this$_captureStartTi, _this$_captureEndTime; if (this._isCapturing) { throw new Error('InboundEventLogger: Tried to send captured events while still capturing.'); } sendMessage({ type: 'warn', details: { startTime: (_this$_captureStartTi = this._captureStartTime) !== null && _this$_captureStartTi !== void 0 ? _this$_captureStartTi : null, endTime: (_this$_captureEndTime = this._captureEndTime) !== null && _this$_captureEndTime !== void 0 ? _this$_captureEndTime : null, inboundEventItems: JSON.stringify(this._capturedInboundEventItems) } }); } reset() { this._captureStartTime = undefined; this._captureEndTime = undefined; this._capturedInboundEventItems = []; this._isCapturing = false; } maybeCaptureInboundEvent(event) { if (this._isCapturing) { const item = { type: 'inbound', timestamp: Date.now(), scrubbedEvent: InboundEventLogger.scrubInboundEvent(event) }; this._capturedInboundEventItems.push(item); } } } const isUrlOnRealm = (url, realm) => url.origin === realm.origin; const inlineApiRoutes = ['^/user_uploads/', '^/thumbnail$', '^/avatar/'].map(r => new RegExp(r)); const rewriteImageUrls = (auth, element) => { const realm = auth.realm; const imageTags = [].concat(element instanceof HTMLImageElement ? [element] : [], Array.from(element.getElementsByTagName('img'))); imageTags.forEach(img => { const actualSrc = img.getAttribute('src'); if (actualSrc == null) { return; } let fixedSrc; try { fixedSrc = new URL(actualSrc, realm); } catch (_unused) { img.src = 'about:blank'; return; } if (isUrlOnRealm(fixedSrc, realm)) { if (inlineApiRoutes.some(regexp => regexp.test(fixedSrc.pathname))) { const delimiter = fixedSrc.search ? '&' : ''; fixedSrc.search += "".concat(delimiter, "api_key=").concat(auth.apiKey); } } if (img.src !== fixedSrc.toString()) { img.src = fixedSrc.toString(); } }); }; const rewriteTime = element => { if (typeof HTMLTimeElement !== 'function') { return; } const timeElements = [].concat(element instanceof HTMLTimeElement ? [element] : [], Array.from(element.getElementsByTagName('time'))); timeElements.forEach(elem => { if (!(elem instanceof HTMLTimeElement)) { return; } const timeStamp = elem.dateTime; const text = elem.innerText; const d = new Date(timeStamp); elem.setAttribute('original-text', text); elem.innerText = "\\uD83D\\uDD52 ".concat(d.toLocaleString(undefined, { dateStyle: 'full', timeStyle: 'short' })); }); }; const rewriteSpoilers = element => { const spoilerHeaders = element.querySelectorAll('div.spoiler-header'); spoilerHeaders.forEach(e => { const toggle_button_html = '<span class="spoiler-button" aria-expanded="false"><span class="spoiler-arrow"></span></span>'; if (e.innerText === '') { const header_html = '<p>Spoiler</p>'; e.innerHTML = toggle_button_html + header_html; } else { e.innerHTML = toggle_button_html + e.innerHTML; } }); }; const rewriteHtml = function (auth) { let element = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document; rewriteImageUrls(auth, element); rewriteTime(element); rewriteSpoilers(element); }; const collapseSpoiler = spoiler => { const computedHeight = getComputedStyle(spoiler).height; requestAnimationFrame(() => { spoiler.style.height = computedHeight; spoiler.classList.remove('spoiler-content-open'); requestAnimationFrame(() => { spoiler.style.height = '0px'; }); }); }; const expandSpoiler = spoiler => { const spoilerHeight = spoiler.scrollHeight; spoiler.style.height = "".concat(spoilerHeight, "px"); spoiler.classList.add('spoiler-content-open'); const callback = () => { spoiler.removeEventListener('transitionend', callback); spoiler.style.height = ''; }; spoiler.addEventListener('transitionend', callback); }; const toggleSpoiler = spoilerHeader => { const spoilerBlock = spoilerHeader.parentElement; if (!spoilerBlock) { return; } const button = spoilerHeader.querySelector('.spoiler-button'); const arrow = spoilerBlock.querySelector('.spoiler-arrow'); const spoilerContent = spoilerBlock.querySelector('.spoiler-content'); if (!arrow || !button || !spoilerContent) { console.warn('Malformed spoiler block'); return; } if (spoilerContent.classList.contains('spoiler-content-open')) { arrow.classList.remove('spoiler-button-open'); button.setAttribute('aria-expanded', 'false'); spoilerContent.setAttribute('aria-hidden', 'true'); collapseSpoiler(spoilerContent); } else { arrow.classList.add('spoiler-button-open'); button.setAttribute('aria-expanded', 'true'); spoilerContent.setAttribute('aria-hidden', 'false'); expandSpoiler(spoilerContent); } }; const documentBody = document.body; if (!documentBody) { throw new Error('No document.body element!'); } const msglistElementsDiv = document.querySelector('div#msglist-elements'); if (!msglistElementsDiv) { throw new Error('No div#msglist-elements element!'); } const escapeHtml = text => { const element = document.createElement('div'); element.innerText = text; return element.innerHTML; }; window.onerror = (message, source, line, column, error) => { if (isDevelopment) { const elementJsError = document.getElementById('js-error-detailed'); if (elementJsError) { elementJsError.innerHTML = ["Message: ".concat(message), "Source: ".concat(source), "Line: ".concat(line, ":").concat(column), "Error: ".concat(JSON.stringify(error)), ''].map(escapeHtml).join('<br>'); } } else { const elementJsError = document.getElementById('js-error-plain'); const elementSheetGenerated = document.getElementById('generated-styles'); const elementSheetHide = document.getElementById('style-hide-js-error-plain'); if (elementJsError && elementSheetGenerated && elementSheetHide && elementSheetHide instanceof HTMLStyleElement && elementSheetHide.sheet && elementSheetGenerated instanceof HTMLStyleElement && elementSheetGenerated.sheet) { elementSheetHide.sheet.disabled = true; const height = elementJsError.offsetHeight; elementSheetGenerated.sheet.insertRule(".header-wrapper { top: ".concat(height, "px; }"), 0); } } const userAgent = window.navigator.userAgent; sendMessage({ type: 'error', details: { message, source, line, column, userAgent, error } }); return true; }; const eventLogger = new InboundEventLogger(); eventLogger.startCapturing(); setTimeout(() => { const placeholdersDiv = document.getElementById('message-loading'); eventLogger.stopCapturing(); if (placeholdersDiv && !placeholdersDiv.classList.contains('hidden')) { eventLogger.send(); } eventLogger.reset(); }, 10000); const showHideElement = (elementId, show) => { const element = document.getElementById(elementId); if (element) { element.classList.toggle('hidden', !show); } }; let viewportHeight = documentBody.clientHeight; window.addEventListener('resize', event => { const heightChange = documentBody.clientHeight - viewportHeight; viewportHeight = documentBody.clientHeight; const maxScrollTop = documentBody.scrollHeight - documentBody.clientHeight; if (documentBody.scrollTop >= maxScrollTop - 1) { return; } window.scrollBy({ left: 0, top: -heightChange }); }); function midMessageListElement(top, bottom) { const midY = (bottom + top) / 2; const midElements = document.elementsFromPoint(0, midY); if (midElements.length < 4) { return null; } return midElements[midElements.length - 4]; } function walkToMessage(start, step) { let element = start; while (element && !element.classList.contains('message')) { element = element[step]; } return element; } function firstMessage() { return walkToMessage(msglistElementsDiv.firstElementChild, 'nextElementSibling'); } function lastMessage() { return walkToMessage(msglistElementsDiv.lastElementChild, 'previousElementSibling'); } function previousMessage(start) { return walkToMessage(start.previousElementSibling, 'previousElementSibling'); } function nextMessage(start) { return walkToMessage(start.nextElementSibling, 'nextElementSibling'); } function isVisible(element, top, bottom) { const rect = element.getBoundingClientRect(); return top < rect.bottom && rect.top < bottom; } const messageReadSlop = 16; function isRead(element, top, bottom) { return bottom + messageReadSlop >= element.getBoundingClientRect().bottom; } function someVisibleMessage(top, bottom) { function checkVisible(candidate) { return candidate && isVisible(candidate, top, bottom) ? candidate : null; } const midElement = midMessageListElement(top, bottom); return checkVisible(walkToMessage(midElement, 'previousElementSibling')) || checkVisible(walkToMessage(midElement, 'nextElementSibling')) || checkVisible(firstMessage()) || checkVisible(lastMessage()); } function someVisibleReadMessage(top, bottom) { function checkReadAndVisible(candidate) { return candidate && isRead(candidate, top, bottom) && isVisible(candidate, top, bottom) ? candidate : null; } const visible = someVisibleMessage(top, bottom); if (!visible) { return visible; } return checkReadAndVisible(visible) || checkReadAndVisible(previousMessage(visible)); } function idFromMessage(element) { const idStr = element.getAttribute('data-msg-id'); if (idStr === null || idStr === undefined) { throw new Error('Bad message element'); } return +idStr; } function visibleReadMessageIds() { const top = 0; const bottom = viewportHeight; let first = Number.MAX_SAFE_INTEGER; let last = 0; function walkElements(start, step) { let element = start; while (element && isVisible(element, top, bottom) && isRead(element, top, bottom)) { if (element.classList.contains('message')) { const id = idFromMessage(element); first = Math.min(first, id); last = Math.max(last, id); } element = element[step]; } } const start = someVisibleReadMessage(top, bottom); walkElements(start, 'nextElementSibling'); walkElements(start, 'previousElementSibling'); return { first, last }; } const getMessageIdFromElement = function (element) { let defaultValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1; const msgElement = element.closest('.msglist-element'); return msgElement ? +msgElement.getAttribute('data-msg-id') : defaultValue; }; const setMessagesReadAttributes = rangeHull => { let element = document.querySelector("[data-msg-id='".concat(rangeHull.first, "']")); while (element) { if (element.classList.contains('message')) { element.setAttribute('data-read', 'true'); if (idFromMessage(element) >= rangeHull.last) { break; } } element = element.nextElementSibling; } }; let prevMessageRange = visibleReadMessageIds(); const sendScrollMessage = () => { const messageRange = visibleReadMessageIds(); const rangeHull = { first: Math.min(prevMessageRange.first, messageRange.first), last: Math.max(prevMessageRange.last, messageRange.last) }; sendMessage({ type: 'scroll', offsetHeight: documentBody.offsetHeight, innerHeight: window.innerHeight, scrollY: window.scrollY, startMessageId: rangeHull.first, endMessageId: rangeHull.last }); if (!doNotMarkMessagesAsRead) { setMessagesReadAttributes(rangeHull); } if (messageRange.first < messageRange.last) { prevMessageRange = messageRange; } }; const sendScrollMessageIfListShort = () => { if (documentBody.scrollHeight === documentBody.clientHeight) { sendScrollMessage(); } }; let scrollEventsDisabled = true; let hasLongPressed = false; let longPressTimeout = undefined; let lastTouchPositionX = -1; let lastTouchPositionY = -1; const handleScrollEvent = () => { clearTimeout(longPressTimeout); if (scrollEventsDisabled) { return; } sendScrollMessage(); const nearEnd = documentBody.offsetHeight - window.scrollY - window.innerHeight > 100; showHideElement('scroll-bottom', nearEnd); }; window.addEventListener('scroll', handleScrollEvent); const scrollToBottom = () => { window.scroll({ left: 0, top: documentBody.scrollHeight, behavior: 'smooth' }); }; const isNearBottom = () => documentBody.scrollHeight - 100 < documentBody.scrollTop + documentBody.clientHeight; const scrollToBottomIfNearEnd = () => { if (isNearBottom()) { scrollToBottom(); } }; const scrollToMessage = messageId => { const targetNode = messageId !== null ? document.getElementById("msg-".concat(messageId)) : null; if (targetNode) { targetNode.scrollIntoView({ block: 'start' }); } else { window.scroll({ left: 0, top: documentBody.scrollHeight + 200 }); } }; const findPreserveTarget = () => { const message = someVisibleMessage(0, viewportHeight); if (!message) { return { type: 'none' }; } const messageId = idFromMessage(message); const prevBoundRect = message.getBoundingClientRect(); return { type: 'preserve', msgId: messageId, prevBoundTop: prevBoundRect.top }; }; const scrollToPreserve = (msgId, prevBoundTop) => { const newElement = document.getElementById("msg-".concat(msgId)); if (!newElement) { return; } const newBoundRect = newElement.getBoundingClientRect(); window.scrollBy(0, newBoundRect.top - prevBoundTop); }; const runAfterLayout = fn => { if (platformOS === 'android') { fn(); return; } requestAnimationFrame(() => { fn(); }); }; const handleInboundEventContent = uevent => { const { scrollStrategy } = uevent; let target; switch (scrollStrategy) { case 'none': target = { type: 'none' }; break; case 'scroll-to-anchor': target = { type: 'anchor', messageId: uevent.scrollMessageId }; break; case 'scroll-to-bottom-if-near-bottom': target = isNearBottom() ? { type: 'bottom' } : findPreserveTarget(); break; case 'preserve-position': target = findPreserveTarget(); break; default: target = findPreserveTarget(); break; } msglistElementsDiv.innerHTML = uevent.content; rewriteHtml(uevent.auth); runAfterLayout(() => { if (target.type === 'bottom') { scrollToBottom(); } else if (target.type === 'anchor') { scrollToMessage(target.messageId); } else if (target.type === 'preserve') { scrollToPreserve(target.msgId, target.prevBoundTop); } sendScrollMessageIfListShort(); }); }; const handleInitialLoad = (scrollMessageId, rawAuth) => { const auth = _objectSpread2(_objectSpread2({}, rawAuth), {}, { realm: new URL(rawAuth.realm) }); if (platformOS === 'ios') { window.addEventListener('message', handleMessageEvent); } else { document.addEventListener('message', handleMessageEvent); } scrollToMessage(scrollMessageId); rewriteHtml(auth); sendScrollMessageIfListShort(); scrollEventsDisabled = false; }; const handleInboundEventFetching = uevent => { showHideElement('message-loading', uevent.showMessagePlaceholders); showHideElement('spinner-older', uevent.fetchingOlder); showHideElement('spinner-newer', uevent.fetchingNewer); }; const handleInboundEventTyping = uevent => { const elementTyping = document.getElementById('typing'); if (elementTyping) { elementTyping.innerHTML = uevent.content; runAfterLayout(() => scrollToBottomIfNearEnd()); } }; let readyRetryInterval = undefined; const signalReadyForEvents = () => { sendMessage({ type: 'ready' }); readyRetryInterval = setInterval(() => { sendMessage({ type: 'ready' }); }, 100); }; const handleInboundEventReady = uevent => { clearInterval(readyRetryInterval); }; function setReadFlags(messageIds, value) { const selector = messageIds.map(id => "[data-msg-id=\\"".concat(id, "\\"]")).join(','); const messageElements = document.querySelectorAll(selector); messageElements.forEach(element => { element.setAttribute('data-read', JSON.stringify(value)); }); } const handleInboundEventSetDoNotMarkAsRead = uevent => { doNotMarkMessagesAsRead = uevent.value; }; const handleInboundEventMessagesSetRead = uevent => { if (uevent.messageIds.length === 0) { return; } setReadFlags(uevent.messageIds, uevent.value); }; const inboundEventHandlers = { content: handleInboundEventContent, fetching: handleInboundEventFetching, typing: handleInboundEventTyping, ready: handleInboundEventReady, 'set-do-not-mark-as-read': handleInboundEventSetDoNotMarkAsRead, 'set-read': handleInboundEventMessagesSetRead }; const handleMessageEvent = e => { scrollEventsDisabled = true; const decodedData = decodeURIComponent(escape(window.atob(e.data))); const rawInboundEvents = JSON.parse(decodedData); const inboundEvents = rawInboundEvents.map(inboundEvent => _objectSpread2(_objectSpread2({}, inboundEvent), inboundEvent.auth ? { auth: _objectSpread2(_objectSpread2({}, inboundEvent.auth), {}, { realm: new URL(inboundEvent.auth.realm) }) } : {})); inboundEvents.forEach(uevent => { eventLogger.maybeCaptureInboundEvent(uevent); inboundEventHandlers[uevent.type](uevent); }); scrollEventsDisabled = false; }; const revealMutedMessages = message => { let messageNode = message; do { messageNode.setAttribute('data-mute-state', 'shown'); messageNode = nextMessage(messageNode); } while (messageNode && messageNode.classList.contains('message-brief')); }; const requireAttribute = (e, name) => { const value = e.getAttribute(name); if (value === null || value === undefined) { throw new Error("Missing expected attribute ".concat(name)); } return value; }; const requireNumericAttribute = (e, name) => { const value = requireAttribute(e, name); const parsedValue = parseInt(value, 10); if (Number.isNaN(parsedValue)) { throw new Error("Could not parse attribute ".concat(name, " value '").concat(value, "' as integer")); } return parsedValue; }; documentBody.addEventListener('click', e => { e.preventDefault(); clearTimeout(longPressTimeout); if (hasLongPressed) { hasLongPressed = false; return; } const { target } = e; if (!(target instanceof Element)) { return; } if (target.matches('.scroll-bottom')) { scrollToBottom(); return; } if (target.matches('.avatar-img') || target.matches('.name-and-status-emoji')) { sendMessage({ type: 'request-user-profile', fromUserId: makeUserId(requireNumericAttribute(target, 'data-sender-id')) }); return; } if (target.matches('.header')) { sendMessage({ type: 'narrow', narrow: requireAttribute(target, 'data-narrow') }); return; } if (target.matches('.user-mention')) { sendMessage({ type: 'mention', userId: makeUserId(requireNumericAttribute(target, 'data-user-id')) }); return; } const inlineImageLink = target.closest('.message_inline_image a'); if (inlineImageLink && !inlineImageLink.closest('.message_inline_video, .youtube-video, .vimeo-video')) { sendMessage({ type: 'image', src: requireAttribute(inlineImageLink, 'href'), messageId: getMessageIdFromElement(inlineImageLink) }); return; } if (target.matches('.reaction')) { sendMessage({ type: 'reaction', name: requireAttribute(target, 'data-name'), code: requireAttribute(target, 'data-code'), reactionType: requireAttribute(target, 'data-type'), messageId: getMessageIdFromElement(target), voted: target.classList.contains('self-voted') }); return; } if (target.matches('.poll-vote')) { const messageElement = target.closest('.message'); if (!messageElement) { throw new Error('Message element not found'); } const current_vote = requireAttribute(target, 'data-voted') === 'true'; const vote = current_vote ? -1 : 1; sendMessage({ type: 'vote', messageId: requireNumericAttribute(messageElement, 'data-msg-id'), key: requireAttribute(target, 'data-key'), vote }); target.setAttribute('data-voted', (!current_vote).toString()); target.innerText = (parseInt(target.innerText, 10) + vote).toString(); return; } if (target.matches('time')) { const originalText = requireAttribute(target, 'original-text'); sendMessage({ type: 'time', originalText }); } const closestA = target.closest('a'); if (closestA) { sendMessage({ type: 'url', href: requireAttribute(closestA, 'href'), messageId: getMessageIdFromElement(closestA) }); return; } const spoilerHeader = target.closest('.spoiler-header'); if (spoilerHeader instanceof HTMLElement) { toggleSpoiler(spoilerHeader); return; } const messageElement = target.closest('.message-brief'); if (messageElement) { messageElement.getElementsByClassName('msg-timestamp')[0].classList.toggle('show'); return; } }); const handleLongPress = target => { hasLongPressed = true; const reactionNode = target.closest('.reaction'); if (reactionNode) { sendMessage({ type: 'reactionDetails', messageId: getMessageIdFromElement(target), reactionName: requireAttribute(reactionNode, 'data-name') }); return; } const targetType = target.matches('.header') ? 'header' : target.matches('a') ? 'link' : 'message'; const messageNode = target.closest('.message'); if (targetType === 'message' && messageNode && messageNode.getAttribute('data-mute-state') === 'hidden') { revealMutedMessages(messageNode); return; } sendMessage({ type: 'longPress', target: targetType, messageId: getMessageIdFromElement(target), href: target.matches('a') ? requireAttribute(target, 'href') : null }); }; documentBody.addEventListener('touchstart', e => { const { target } = e; if (e.changedTouches[0].pageX < 20 || !(target instanceof Element)) { return; } lastTouchPositionX = e.changedTouches[0].pageX; lastTouchPositionY = e.changedTouches[0].pageY; hasLongPressed = false; clearTimeout(longPressTimeout); longPressTimeout = setTimeout(() => handleLongPress(target), 500); }); const isNearPositions = function () { let x1 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; let y1 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; let x2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; let y2 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; return Math.abs(x1 - x2) < 10 && Math.abs(y1 - y2) < 10; }; documentBody.addEventListener('touchend', e => { if (isNearPositions(lastTouchPositionX, lastTouchPositionY, e.changedTouches[0].pageX, e.changedTouches[0].pageY)) { clearTimeout(longPressTimeout); } }); documentBody.addEventListener('touchcancel', e => { clearTimeout(longPressTimeout); }); documentBody.addEventListener('touchmove', e => { clearTimeout(longPressTimeout); }); documentBody.addEventListener('drag', e => { clearTimeout(longPressTimeout); }); signalReadyForEvents(); exports.handleInitialLoad = handleInitialLoad; Object.defineProperty(exports, '__esModule', { value: true }); return exports; })({}); `; ```
/content/code_sandbox/src/webview/js/generatedEs3.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
6,765
```javascript /** @jest-environment jsdom-global */ // @flow strict-local import rewriteHtml from '../rewriteHtml'; import type { Auth } from '../../../types'; describe('rewriteHtml', () => { const realm = new URL('path_to_url global.jsdom.reconfigure({ // This should really be a file:// URL. In particular, it's meant to be // the base URL passed to SinglePageWebView for the message list. But: // path_to_url url: 'path_to_url }); const auth: Auth = { realm, apiKey: 'hMV41eMjVmr6dajvnyOA', // arbitrary random string email: 'rosencrantz+guildenstern@zulip.com', }; const rewrite = (src: string): {| input: string, before: string, after: string |} => { const img = document.createElement('img'); img.setAttribute('src', src); const before = img.src; rewriteHtml(auth, img); const after = img.src; return { input: src, before, after }; }; // URL prefixes. May have a final slash. const prefixes = { relative: '', 'root-relative': '/', 'absolute on-realm': realm.toString(), 'absolute off-realm': 'path_to_url }; // URL suffixes. May have an initial slash. const suffixes = { empty: '', 'known endpoint': 'avatar/example', 'known endpoint plus query': 'avatar/example?size=large', 'known endpoint plus fragment': 'avatar/example#00000042', 'other endpoint': 'placekitten?w=640&w=480', }; Object.keys(prefixes).forEach(pType => { const prefix: string = prefixes[pType]; describe(`${pType} URL`, () => { Object.keys(suffixes).forEach(sType => { const suffix: string = suffixes[sType]; if (!prefix && !suffix) { return; } describe(`+ ${sType} path`, () => { const divider = prefix && !prefix.endsWith('/') && suffix && !suffix.startsWith('/') ? '/' : ''; const url = `${prefix}${divider}${suffix}`; const { before, after } = rewrite(url); if (pType.includes('absolute')) { test('... is not relativized', () => { expect(before).toStartWith(prefix); expect(after).toStartWith(prefix); }); } else { test('... gains a prefix when relativized', () => { expect(before).not.toStartWith(url); expect(after).not.toStartWith(url); }); } /* This tests and confirms the behavior of JSDOM, rather than that of `rewriteImageUrls`. */ if (pType.includes('off-realm')) { test('... yields an off-realm URL', () => { expect(new URL(before).hostname).not.toBe('realm.example.com'); }); } else if (pType.includes('on-realm')) { test('... yields an on-realm URL', () => { expect(new URL(before).hostname).toBe('realm.example.com'); }); } if (sType.includes('known endpoint') && !pType.includes('off-realm')) { test('... has `api_key` added', () => { expect(after).toContain(auth.apiKey); expect(new URL(after).searchParams.getAll('api_key')).toEqual([auth.apiKey]); }); } else { test('... does not have `api_key` added', () => { expect(after).not.toContain(auth.apiKey); expect(new URL(after).searchParams.getAll('api_key')).toEqual([]); }); } }); }); }); }); /* Specific concrete examples. Formally redundant with the preceding tests, but useful for calibrating those against human expectations. */ test('on-realm known endpoint is modified', () => { const { input, before, after } = rewrite('path_to_url expect(before).toBe(input); expect(after).not.toBe(input); }); test('on-realm unknown endpoint is left alone', () => { const { input, before, after } = rewrite('path_to_url expect(before).toBe(input); expect(after).toBe(input); }); test('absolute non-realm url is left alone', () => { const { input, before, after } = rewrite('path_to_url expect(before).toBe(input); expect(after).toBe(input); }); }); ```
/content/code_sandbox/src/webview/js/__tests__/rewriteHtml-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
992
```css /* Top level. */ html { -webkit-user-select: none; /* Safari 3.1+ */ -moz-user-select: none; /* Firefox 2+ */ -ms-user-select: none; /* IE 10+ */ user-select: none; /* Standard syntax */ -khtml-user-select: none; -webkit-touch-callout: none; font: -apple-system-body; } body { font-family: sans-serif; line-height: 1.4; margin: 0; width: 100%; max-width: 100%; } /* TODO: make specific versions of this rule for where we actually use it. That way, no surprises when some contrary rule has higher specificity. (Until then, we avoid using this class for any element where we have another rule specifying a `display:` attribute at all.) */ .hidden { display: none; } #js-error-detailed { position: fixed; width: 100%; background: red; color: white; font-size: 0.7rem; } #js-error-plain, #js-error-plain-dummy { z-index: 1000; width: 100%; background: red; color: white; padding: 4px; text-align: center; } #js-error-plain { position: fixed; } #js-error-plain-dummy { visibility: hidden; } /* Whole messages and their neighbors: timerows, recipient headers, etc. */ /* Timerows. */ .timerow { text-align: center; color: hsl(0, 0%, 60%); display: flex; align-items: center; padding: 8px 0; } .timerow-left, .timerow-right { flex: 1; height: 1px; margin: 8px; } .timerow-left { background: -webkit-linear-gradient(left, transparent 10%, hsl(0, 0%, 60%) 100%); } .timerow-right { background: -webkit-linear-gradient(left, hsl(0, 0%, 60%) 0%, transparent 90%); } /* Recipient headers. */ .header-wrapper { position: -webkit-sticky; position: sticky; top: -1px; z-index: 100; display: flex; justify-content: space-between; } .avatar, .header-wrapper, .message-brief { cursor: pointer; } .stream-header { padding: 0; display: flex; flex-direction: row; } .stream-text, .topic-header, .private-header { line-height: 2; white-space: nowrap; } .private-header { padding: 0 8px; } .private-header { background: hsl(0, 0%, 27%); color: white; } .topic-header { background: hsl(0, 0%, 80%); min-width: 30%; } .stream-text { padding: 0 8px; } .topic-text { flex: 1; padding: 0 8px; display: flex; align-items: center; overflow: hidden; text-overflow: ellipsis; pointer-events: none; } .topic-text[data-followed="true"]::after { content: ""; background-image: url("images/follow.svg"); margin-left: 12px; width: 17px; height: 17px; /* opacity: 0.2 on web, but that's with the pastel stream colors; * 0.3 stands up better to our gray. */ opacity: 0.3; } .topic-date { opacity: 0.5; padding: 0 8px; pointer-events: none; } /* Messages! And "loading" pseudomessages. */ .message, .loading { display: flex; word-wrap: break-word; /* This value is used for messageReadSlop in src/webview/js/js.js, if * updating one, please update the other */ padding: 16px; -webkit-tap-highlight-color: transparent; } .message-brief { /* This value is used for messageReadSlop in src/webview/js/js.js, if * updating one, please update the other */ padding: 0 16px 16px 80px; } .message-brief[data-mute-state="hidden"] { display: none; } .message[data-mute-state="hidden"] > .avatar, .message[data-mute-state="hidden"] > .content { display: none; } .message[data-mute-state="shown"] > .muted-message-explanation { display: none; } #message-loading { position: fixed; width: 100%; opacity: 0.25; } /* Spinners. */ .loading-spinner, .outbox-spinner { width: 32px; height: 32px; border-radius: 50%; margin: 16px auto; font-size: 10px; border: 3px solid hsla(222, 99%, 69%, 0.25); border-left: 3px solid hsla(222, 99%, 69%, 0.75); animation: spin 1s linear infinite; } .outbox-spinner { margin: -16px 0 0 0; border-width: 2px; width: 12px; height: 12px; float: right; } /* Typing-status indicators. */ #typing { display: flex; padding-left: 16px; } #typing .content { padding-top: 8px; padding-bottom: 16px; } #typing span { display: inline-block; background-color: hsl(253, 3%, 72%); width: 0.5rem; height: 0.5rem; border-radius: 100%; margin-right: 5px; animation: bob 2s infinite; } #typing span:nth-child(2) { animation-delay: 0.15s; } #typing span:nth-child(3) { animation-delay: 0.3s; margin-right: 0; } @keyframes bob { 10% { transform: translateY(-10px); background-color: hsl(253, 3%, 63%); } 50% { transform: translateY(0); background-color: hsl(253, 3%, 72%); } } /* The "scroll to bottom" button. */ #scroll-bottom { position: fixed; z-index: 200; right: 5px; bottom: 15px; border-radius: 50%; transition: opacity 0.25s ease-in-out; -webkit-transition: opacity 0.25s ease-in-out; } #scroll-bottom a { display: block; width: 32px; height: 32px; border-radius: 50%; background: hsla(222, 99%, 69%, 0.5); -webkit-tap-highlight-color: transparent; } #scroll-bottom .text { clip: rect(0 0 0 0); overflow: hidden; position: absolute; height: 1px; width: 1px; } #scroll-bottom:active{ background-color: hsl(170, 48%, 54%); } #scroll-bottom svg { width: 32px; height: 32px; fill: hsla(0, 0%, 100%, 0.75); } #scroll-bottom.hidden { display: block; /* Remove this when the generic .hidden rule is removed */ opacity: 0; } /* Inside a "loading" pseudomessage. */ .loading-avatar { border-radius: 3px; background: hsla(0, 0%, 50%, 0.9); } .loading-content { width: 100%; } .loading-subheader { display: flex; justify-content: space-between; } .loading-content .block { background: linear-gradient( to right, hsla(0, 0%, 50%, 0.5) 0%, hsla(0, 0%, 50%, 0.5) 40%, hsla(0, 0%, 50%, 0.25) 51%, hsla(0, 0%, 50%, 0.5) 60%, hsla(0, 0%, 50%, 0.5) 100% ); background-size: 200% 200%; animation: gradient-scroll 1s linear infinite; border-radius: 10px; height: 8px; margin-bottom: 10px; } @keyframes gradient-scroll { 0% { background-position: 100% 50% } 100% { background-position: 0 50% } } .loading-subheader .name { width: 10rem; background-color: hsla(0, 0%, 50%, 0.9); } .loading-subheader .msg-timestamp { width: 5rem; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } /* Inside a message, outside its contents. */ [data-mentioned="true"][data-mute-state="shown"], [data-wildcard_mentioned="true"][data-mute-state="shown"] { background: hsla(0, 100%, 50%, 0.05); } .message:not([data-read="true"]) { box-shadow: inset 4px 0 hsl(222, 99%, 69%); } .message[data-read="true"] { box-shadow: inset 4px 0 transparent; transition-property: box-shadow; transition-duration: 0.3s; transition-delay: 1s; transition-timing-function: ease-out; } /* * The sender's avatar. If changing the size here, be sure to change * the size we request for the avatar image file in the corresponding * HTML-generating code (see messageTypingAsHtml.js and * message.js in src/webview/html/). */ .avatar, .loading-avatar { min-width: 48px; width: 48px; height: 48px; margin-right: 16px; } .avatar img { width: 100%; border-radius: 3px; } /* The "subheader" showing sender, emoji status, and timestamp. */ .subheader { display: flex; flex-direction: row; justify-content: space-between; margin-bottom: 6px; } .name-and-status-emoji { display: flex; align-items: center; font-weight: bold; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; } .status-emoji { height: 1.4rem; /* Different from web, which has 2px. More is mysteriously needed here to get the same effective spacing. */ margin-left: 4px; } .static-timestamp { color: hsl(0, 0%, 60%); font-size: 0.9rem; white-space: nowrap; } /* Timestamp pills. */ .time-container { position: absolute; left: 0; right: 0; height: 2rem; overflow: hidden; pointer-events: none; } .msg-timestamp { position: absolute; right: 4px; transform: translateX(100%); transition-property: right, transform; transition-duration: 0.2s; padding: 2px 4px; font-size: 0.9rem; white-space: nowrap; color: hsl(0, 0%, 60%); background: hsl(0, 0%, 97%); border-radius: 3px; box-shadow: 0px 3px 1px -2px hsla(0, 0%, 0%, 0.2), 0px 2px 2px 0px hsla(0, 0%, 0%, 0.14), 0px 1px 5px 0px hsla(0, 0%, 0%, 0.12); } .msg-timestamp.show { right: 8px; transform: none; } /* The message content! */ .content { width: 100%; max-width: 100%; overflow: hidden; } /* Tags, like "starred" or "edited 2 minutes ago". */ .message-tags { text-align: right; margin: 4px 0; font-size: 0.7rem; } .message-tag { padding: 4px 4px; margin-left: 4px; border-radius: 3px; color: hsla(0, 0%, 50%, 0.75); background: hsla(0, 0%, 0%, 0.1); } /* Emoji reactions. */ .reaction-list { margin: 8px 0; } .reaction { color: hsl(0, 0%, 50%); display: inline-block; padding: 5px 6.5px; border-radius: 3px; border: 1px solid hsla(0, 0%, 50%, 0.75); line-height: 1.2rem; /* No max height. With `displayEmojiReactionUsers: true`, users' names may wrap onto multiple lines. */ min-height: 1rem; margin: 4px 8px 4px 0; } .reaction img { pointer-events: none; cursor: default; max-height: 1rem; max-width: 1rem; vertical-align: top; } .self-voted { color: hsl(222, 99%, 69%); border: 1px solid hsl(222, 99%, 69%); background: hsla(222, 99%, 69%, 0.1); } /* Message contents. For the body of a message, we use nearly the same HTML as the webapp does. The styles therefore have a lot in common. For the webapp's version of these styles, compare static/styles/rendered_markdown.css . */ p { margin: 0; } .message p + p { margin-top: 16px; } .message ul { padding-left: 20px; margin: 4px 0 0 0; } .message ul + p { margin-top: 16px; } blockquote { padding-left: 8px; margin: 8px 0 8px 0; border-left: 3px solid hsla(0, 0%, 50%, 0.5); } table { border-collapse: collapse; max-width: fit-content; display: block; overflow-x: auto; } table, th, td { border: 1px solid hsla(0, 0%, 50%, 0.25); } thead { background: hsla(0, 0%, 50%, 0.1); } th, td { align: center; padding: 4px 8px; } .emoji { display: inline-block; height: 1.25rem; width: 1.25rem; white-space: nowrap; color: transparent; vertical-align: text-top; } .emoji:before { color: white; } /* TODO differentiate these three kinds of mentions */ /* TODO differentiate on .user-mention-me (whether mention includes self-user) */ .topic-mention, .user-group-mention, .user-mention { white-space: nowrap; background-color: hsla(0, 0%, 0%, 0.1); border-radius: 3px; padding: 0 2px; margin: 0 1px; box-shadow: 0 0 0 1px hsla(0, 0%, 0%, 0.2); } .alert-word { background-color: hsla(102, 85%, 57%, 0.3); } time { display: inline-block; padding: 4px 6px; background-color: hsla(0, 0%, 50%, 0.125); border-radius: 8px; } .message_inline_image { text-align: center; } .message_inline_image img, .message_inline_ref img, .twitter-image img { width: 100%; height: 160px; object-fit: scale-down; } .message_inline_image img.image-loading-placeholder { content: url("images/loader-black.svg"); } .message_inline_video { position: relative; } .message_inline_video video { width: 240px; height: 160px; background: black; } .message_inline_video::after { content: ""; background-image: url("images/play_button.svg"); display: block; width: 32px; height: 32px; position: absolute; top: calc(50% - 16px); left: calc(50% - 16px); border-radius: 100%; transform: scale(0.8); } .twitter-tweet { border: 2px solid hsla(203, 89%, 53%, 0.5); background: hsla(203, 89%, 53%, 0.1); border-radius: 6px; padding: 8px 16px; margin: 8px 0; } .twitter-avatar { border-radius: 3px; margin: 8px 8px 4px 0; float: left; width: 2.2rem; height: 2.2rem; } .twitter-image { text-align: center; margin: 8px auto; } code { font-size: .857rem; white-space: pre-wrap; padding: 0 4px; } pre { padding: 8px; margin: 8px 0; font-size: 0.75rem; white-space: pre; overflow-x: auto; word-wrap: normal; } code, pre { border-radius: 3px; border: 1px solid hsla(0, 0%, 50%, 0.25); background-color: hsla(0, 0%, 50%, 0.125); font-family: Monaco, Menlo, Consolas, "Courier New", monospace; } pre code { /* Starting with Zulip Server 3.0, code blocks have `pre > code`. Undo the stuff we have for `code` that isn't meant to apply there. TODO(server-3.0): Simplify this. */ font-size: inherit; white-space: inherit; padding: 0; border: none; background: none; } .highlight { background-color: hsl(51, 94%, 74%); } /* `a`, which the webapp styles with Bootstrap. */ a { color: hsl(200, 100%, 40%); } /* `hr`, not found in the webapp's rendered_markdown.css. */ hr { margin: 16px 0; border: 0; border-top: 1px solid hsla(0, 0%, 50%, 0.5); } h1, h2, h3, h4, h5, h6 { font-size: 100%; font-weight: 600; /* line-height doesn't seem to be needed on mobile, but it's here just for * the sake of being consistent with the webapp */ line-height: 1.4; margin-top: 0; margin-bottom: 5px; text-decoration: underline; } /* Our own "sorry, unsupported" message for widgets. Also used for showing that a message was sent by a muted user. */ .special-message { display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 1rem; background: hsla(0, 0%, 50%, 0.1); border: 1px dashed hsla(0, 0%, 50%, 0.5); border-radius: 0.5rem; } /* LaTeX styling */ .katex-display { /* KaTeX sometimes overdraws its bounding box by a little, so we enlarge its scrolling area by stealing 3px from the margin of the enclosing <p>. */ margin: -3px 0; padding: 3px 0; overflow: auto hidden; } /* Taken from the `.spoiler-block` section of the webapp's styles, as of zulip/zulip@1cb040647, translated from SCSS to plain CSS. */ .spoiler-block { border: hsl(0, 0%, 50%) 1px solid; padding: 2px 8px 2px 10px; border-radius: 10px; position: relative; top: 1px; display: block; margin: 5px 0 15px 0; } .spoiler-block .spoiler-header { padding: 5px; font-weight: bold; } .spoiler-block .spoiler-content { overflow: hidden; border-top: hsla(0, 0%, 50%,1) 0px solid; transition: height 0.4s ease-in-out, border-top 0.4s step-end, padding 0.4s step-end; padding: 0px; height: 0px; } .spoiler-block .spoiler-content.spoiler-content-open { border-top: hsla(0, 0%, 50%,1) 1px solid; transition: height 0.4s ease-in-out, border-top 0.4s step-start, padding 0.4s step-start; padding: 5px; height: auto; } .spoiler-block .spoiler-button { float: right; width: 25px; height: 25px; } .spoiler-block .spoiler-button:hover .spoiler-arrow::before, .spoiler-block .spoiler-button:hover .spoiler-arrow::after { background-color: hsl(0, 0%, 50%); } .spoiler-block .spoiler-arrow { float: right; width: 13px; height: 13px; position: relative; bottom: -5px; left: -10px; cursor: pointer; transition: 0.4s ease; margin-top: 2px; text-align: left; transform: rotate(45deg); } .spoiler-block .spoiler-arrow::before, .spoiler-block .spoiler-arrow::after { position: absolute; content: ''; display: inline-block; width: 12px; height: 3px; background-color: hsl(0, 0%, 83%); transition: 0.4s ease; } .spoiler-block .spoiler-arrow::after { position: absolute; transform: rotate(90deg); top: -5px; left: 5px; } .spoiler-block .spoiler-arrow.spoiler-button-open { transform: rotate(45deg) translate(-5px, -5px); } .spoiler-block .spoiler-arrow.spoiler-button-open::before { transform: translate(10px, 0); } .spoiler-block .spoiler-arrow.spoiler-button-open::after { transform: rotate(90deg) translate(10px, 0); } /* Poll styling */ .poll-widget { border: hsl(0, 0%, 50%) 1px solid; padding: 2px 8px 2px 10px; border-radius: 10px; } .poll-question { font-size: 1.2rem; margin-bottom: 8px; border-bottom: 1px solid hsla(0, 0%, 60%, 0.2); } .poll-widget > ul { padding: 0px; } .poll-widget > ul > li { list-style: none; margin-bottom: 4px; display: flex; align-items: center; } .poll-vote { background-color: hsla(0, 0%, 0%, 0); border: 1.5px solid hsl(0, 0%, 50%); border-radius: 8px; height: 36px; min-width: 36px; padding: 1px 8px; font-weight: bold; font-size: 18px; flex-shrink: 0; } .poll-vote[data-voted="true"] { border: 1.5px solid hsl(222, 99%, 69%); background-color: hsla(222, 99%, 69%, 25%); } .poll-option { margin-left: 8px; width: 100%; } ```
/content/code_sandbox/src/webview/static/base.css
css
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
5,566
```javascript /* @flow strict-local */ import deepFreeze from 'deep-freeze'; import generateInboundEvents from '../generateInboundEvents'; import { flagsStateToStringList } from '../html/message'; import { HOME_NARROW } from '../../utils/narrow'; import * as eg from '../../__tests__/lib/exampleData'; import type { Props } from '../MessageList'; import { mock_ } from '../../__tests__/lib/intl'; describe('generateInboundEvents', () => { const baseSelectorProps = deepFreeze({ backgroundData: eg.baseBackgroundData, initialScrollMessageId: null, fetching: { older: false, newer: false }, messages: [], messageListElementsForShownMessages: [], typingUsers: [], doNotMarkMessagesAsRead: false, }); const baseProps: Props = deepFreeze({ narrow: HOME_NARROW, showMessagePlaceholders: false, startEditMessage: jest.fn(), composeBoxRef: { current: null }, dispatch: jest.fn(), ...baseSelectorProps, showActionSheetWithOptions: jest.fn(), fetchOlder: jest.fn(), fetchNewer: jest.fn(), _: mock_, setDoNotMarkMessagesAsRead: jest.fn(), }); test('missing prev and next props returns no messages', () => { const prevProps = baseProps; const nextProps = baseProps; const messages = generateInboundEvents(prevProps, nextProps); expect(messages).toEqual([]); }); test('if fetching message differs send a message for fetching', () => { const prevProps = { ...baseProps, fetching: { older: false, newer: false }, }; const nextProps = { ...baseProps, fetching: { older: false, newer: true }, }; const messages = generateInboundEvents(prevProps, nextProps); expect(messages).toEqual([ { type: 'fetching', showMessagePlaceholders: nextProps.showMessagePlaceholders, fetchingNewer: true, fetchingOlder: false, }, ]); }); test('if fetching key is the same no message is sent', () => { const prevProps = { ...baseProps, fetching: { older: false, newer: false }, }; const nextProps = { ...baseProps, fetching: { older: false, newer: false }, }; const messages = generateInboundEvents(prevProps, nextProps); expect(messages).toEqual([]); }); test('if typing users differ send a "typing" message', () => { const prevProps = { ...baseProps, typingUsers: [], }; const nextProps = { ...baseProps, typingUsers: [eg.makeUser()], }; const messages = generateInboundEvents(prevProps, nextProps); expect(messages).toHaveLength(1); expect(messages[0].type).toEqual('typing'); }); test('when rendered messages are the same return empty result', () => { const prevProps = { ...baseProps, messageListElementsForShownMessages: [], }; const nextProps = { ...baseProps, messageListElementsForShownMessages: [], }; const messages = generateInboundEvents(prevProps, nextProps); expect(messages).toEqual([]); }); test('when the rendered messages differ (even deeply) a "content" message is returned', () => { const message = eg.streamMessage({ sender: eg.selfUser }); const prevProps = { ...baseProps, messageListElementsForShownMessages: [], }; const nextProps = { ...baseProps, messageListElementsForShownMessages: [ { key: [message.id, 2], type: 'message', isBrief: false, message }, ], }; const messages = generateInboundEvents(prevProps, nextProps); expect(messages).toHaveLength(1); expect(messages[0].type).toEqual('content'); }); test('WUUT there are several diffs return several messages', () => { const prevProps = { ...baseProps, narrow: HOME_NARROW, fetching: { older: false, newer: false }, typingUsers: [], }; const nextProps = { ...baseProps, narrow: HOME_NARROW, fetching: { older: false, newer: true }, typingUsers: [eg.makeUser()], }; const messages = generateInboundEvents(prevProps, nextProps); expect(messages).toHaveLength(2); expect(messages[0].type).toEqual('fetching'); expect(messages[1].type).toEqual('typing'); }); test('if a new message is read send a "read" update', () => { const message1 = eg.streamMessage({ id: 1 }); const message2 = eg.streamMessage({ id: 2 }); const message3 = eg.streamMessage({ id: 3 }); const prevProps = { ...baseProps, backgroundData: { ...eg.baseBackgroundData, flags: { ...eg.baseBackgroundData.flags, read: { [message2.id]: true }, }, }, }; const nextProps = { ...baseProps, backgroundData: { ...eg.baseBackgroundData, flags: { ...eg.baseBackgroundData.flags, read: { [message1.id]: true, [message2.id]: true, [message3.id]: true }, }, }, }; const messages = generateInboundEvents(prevProps, nextProps); expect(messages[0]).toEqual({ type: 'set-read', value: true, messageIds: [1, 3], }); }); }); describe('flagsStateToStringList', () => { const message1 = eg.streamMessage({ id: 1 }); const message2 = eg.streamMessage({ id: 2 }); const message3 = eg.streamMessage({ id: 3 }); const flags = { ...eg.baseReduxState.flags, read: { [message1.id]: true, [message2.id]: true, }, starred: { [message1.id]: true, [message3.id]: true, }, mentioned: {}, // ... // the actual state keeps track of many more flags }; test("returns a string list of flags for some message, given some FlagsState and the message's id", () => { expect(flagsStateToStringList(flags, 1)).toEqual(['read', 'starred']); expect(flagsStateToStringList(flags, 2)).toEqual(['read']); expect(flagsStateToStringList(flags, 3)).toEqual(['starred']); }); }); ```
/content/code_sandbox/src/webview/__tests__/generateInboundEvents-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,420
```javascript /** * @jest-environment jsdom * @flow strict-local */ import Immutable from 'immutable'; import invariant from 'invariant'; import * as eg from '../../__tests__/lib/exampleData'; import { HOME_NARROW, streamNarrow, topicNarrow, pmNarrowFromUsersUnsafe, keyFromNarrow, ALL_PRIVATE_NARROW, } from '../../utils/narrow'; import type { PerAccountState, GlobalSettingsState, Narrow, Message, Outbox, FlagsState, } from '../../types'; import type { ReadWrite } from '../../generics'; import { getEditSequence } from '../generateInboundEventEditSequence'; import { applyEditSequence } from '../js/handleInboundEvents'; import getMessageListElements from '../../message/getMessageListElements'; import { getGlobalSettings } from '../../selectors'; import { getBackgroundData } from '../backgroundData'; import { randString } from '../../utils/misc'; import { makeMuteState } from '../../mute/__tests__/mute-testlib'; import { UserTopicVisibilityPolicy } from '../../api/modelTypes'; import { mock_ } from '../../__tests__/lib/intl'; import { Role } from '../../api/permissionsTypes'; // Tell ESLint to recognize `check` as a helper function that runs // assertions. /* eslint jest/expect-expect: ["error", { "assertFunctionNames": ["expect", "check"] }] */ const user1 = eg.makeUser({ user_id: 1, full_name: 'Nonrandom name one User' }); const user2 = eg.makeUser({ user_id: 2, full_name: 'Nonrandom name two User' }); const user3 = eg.makeUser({ user_id: 3, full_name: 'Nonrandom name three User' }); const stream1 = eg.makeStream({ stream_id: 1, name: 'stream 1' }); const stream2 = eg.makeStream({ stream_id: 2, name: 'stream 2' }); const topic1 = 'topic 1'; const topic2 = 'topic 2'; // Same sender, stream, topic, day const streamMessages1 = [ eg.streamMessage({ id: 1024, timestamp: 791985600, sender: user1, stream: stream1, subject: topic1, }), eg.streamMessage({ id: 1598, timestamp: 791985601, sender: user1, stream: stream1, subject: topic1, }), ]; // Different senders; same stream, topic, day const streamMessages2 = [ eg.streamMessage({ id: 7938, timestamp: 794404812, sender: user1, stream: stream1, subject: topic1, }), eg.streamMessage({ id: 8060, timestamp: 794404813, sender: user2, stream: stream1, subject: topic1, }), ]; // Same sender, stream, day; different topics const streamMessages3 = [ eg.streamMessage({ id: 4948, timestamp: 793195202, sender: user1, stream: stream1, subject: topic1, }), eg.streamMessage({ id: 5083, timestamp: 793195203, sender: user1, stream: stream1, subject: topic2, }), ]; // Same sender, day; different streams, topics const streamMessages4 = [ eg.streamMessage({ id: 6789, timestamp: 794404810, sender: user1, stream: stream1, subject: topic1, }), eg.streamMessage({ id: 7727, timestamp: 794404811, sender: user1, stream: stream2, subject: topic2, }), ]; // Same sender, stream, topic; different days const streamMessages5 = [ eg.streamMessage({ id: 9181, timestamp: 794404816, sender: user1, stream: stream1, subject: topic1, }), eg.streamMessage({ id: 9815, timestamp: 795009616, sender: user1, stream: stream1, subject: topic1, }), ]; // 1:1 PM, same sender, day const pmMessages1 = [ eg.pmMessage({ id: 8849, timestamp: 794404814, sender: user1, recipients: [user1, user2] }), eg.pmMessage({ id: 8917, timestamp: 794404815, sender: user1, recipients: [user1, user2] }), ]; // 1:1 PM, different senders; same day const pmMessages2 = [ eg.pmMessage({ id: 5287, timestamp: 793195204, sender: user1, recipients: [user1, user2] }), eg.pmMessage({ id: 5309, timestamp: 793195205, sender: user2, recipients: [user1, user2] }), ]; // 1:1 PM, same sender; different day const pmMessages3 = [ eg.pmMessage({ id: 5829, timestamp: 793195210, sender: user1, recipients: [user1, user2] }), eg.pmMessage({ id: 5963, timestamp: 793800010, sender: user1, recipients: [user1, user2] }), ]; // Group PM, same sender, day const pmMessages4 = [ eg.pmMessage({ id: 5377, timestamp: 793195206, sender: user1, recipients: [user1, user2, user3], }), eg.pmMessage({ id: 5620, timestamp: 793195207, sender: user1, recipients: [user1, user2, user3], }), ]; // Group PM, different senders; same day const pmMessages5 = [ eg.pmMessage({ id: 5637, timestamp: 793195208, sender: user1, recipients: [user1, user2, user3], }), eg.pmMessage({ id: 5727, timestamp: 793195209, sender: user2, recipients: [user1, user2, user3], }), ]; // Group PM, same sender; different day const pmMessages6 = [ eg.pmMessage({ id: 2794, timestamp: 791985602, sender: user1, recipients: [user1, user2, user3], }), eg.pmMessage({ id: 4581, timestamp: 792590402, sender: user1, recipients: [user1, user2, user3], }), ]; const baseState = eg.reduxStatePlus({ streams: [...eg.plusReduxState.streams, stream1, stream2], subscriptions: [ ...eg.plusReduxState.subscriptions, eg.makeSubscription({ stream: stream1 }), eg.makeSubscription({ stream: stream2 }), ], }); /** * Highlight changes in content-HTML generation. * * Test failures here (which we expect to happen often) will have two * major flavors: * * - Your changes caused different content HTML to be generated from * the same input (list of messages, backgroundData, etc.). You * should examine the changes and see if we want them. * - If they look correct, please follow Jest's instructions to * update the snapshots, and commit the result. * - If they don't look correct, look for bugs that were caused or * revealed by your changes. Please fix them and run the tests * again. * * - Different input was given on this run of the tests, and naturally * our code produced different output. * - This will be the case when extending these tests to increase * coverage. Thanks for doing that! :) * - But one big "gotcha!" is that we can't vary the input * programmatically with every run of the tests. That's why the * data objects in the input have hard-coded IDs, names, etc., * instead of random ones (even as `exampleData` is happy to give * us random data, which is often what we want!). If we allow * something in the input to randomly change between test runs, * we're inviting the output to change randomly too, and if that * happens, the snapshots won't match, and the tests will fail. We * should avoid meaningless failures like that; strong tests have * meaningful results. * * This is our first attempt at testing UI logic with snapshot tests, * done in part to help check a refactor of `getMessageListElements` * and `messageListElementHtml`. */ describe('messages -> piece descriptors -> content HTML is stable/sensible', () => { const check = ({ state = baseState, globalSettings = getGlobalSettings(eg.plusReduxState), narrow, messages, }: {| state?: PerAccountState, globalSettings?: GlobalSettingsState, narrow: Narrow, messages: $ReadOnlyArray<Message>, |}) => { invariant( messages.every((message, i, allMessages) => { const prevMessage: Message | void = allMessages[i - 1]; return ( prevMessage === undefined || (prevMessage.id < message.id && prevMessage.timestamp < message.timestamp) ); }), 'Problem with test data: `messages` should increase monotonically in both `id` and `timestamp`.', ); invariant(document.body, 'expected jsdom environment'); document.body.innerHTML = '<div id="msglist-elements" />'; const msglistElementsDiv = document.querySelector('div#msglist-elements'); invariant(msglistElementsDiv, 'expected msglistElementsDiv'); // Simulate applying an edit-sequence event to the DOM. applyEditSequence( getEditSequence( { backgroundData: getBackgroundData(state, globalSettings), elements: [], _: mock_, }, { backgroundData: getBackgroundData(state, globalSettings), elements: getMessageListElements(messages, narrow), _: mock_, }, ), ); expect(msglistElementsDiv.innerHTML).toMatchSnapshot(); }; test('HOME_NARROW', () => { [ { narrow: HOME_NARROW, messages: streamMessages1 }, { narrow: HOME_NARROW, messages: streamMessages2 }, { narrow: HOME_NARROW, messages: streamMessages3 }, { narrow: HOME_NARROW, messages: streamMessages4 }, { narrow: HOME_NARROW, messages: streamMessages5 }, { narrow: HOME_NARROW, messages: pmMessages1 }, { narrow: HOME_NARROW, messages: pmMessages2 }, { narrow: HOME_NARROW, messages: pmMessages3 }, { narrow: HOME_NARROW, messages: pmMessages4 }, { narrow: HOME_NARROW, messages: pmMessages5 }, { narrow: HOME_NARROW, messages: pmMessages6 }, { narrow: HOME_NARROW, // All together, sorted by ID. (Which basically means jumbled; // the IDs in each sub-list are only internally sorted.) messages: [ ...streamMessages1, ...streamMessages2, ...streamMessages3, ...streamMessages4, ...streamMessages5, ...pmMessages1, ...pmMessages2, ...pmMessages3, ...pmMessages4, ...pmMessages5, ...pmMessages6, ].sort((a, b) => a.id - b.id), }, ].forEach(testCase => check(testCase)); }); const streamNarrow1 = streamNarrow(stream1.stream_id); test(`${keyFromNarrow(streamNarrow1)}`, () => { [ { narrow: streamNarrow1, messages: streamMessages1 }, { narrow: streamNarrow1, messages: streamMessages2 }, { narrow: streamNarrow1, messages: streamMessages3 }, { narrow: streamNarrow1, messages: streamMessages5 }, { narrow: streamNarrow1, // All together, sorted by ID. (Which basically means jumbled; // the IDs in each sub-list are only internally sorted.) messages: [ ...streamMessages1, ...streamMessages2, ...streamMessages3, ...streamMessages5, ].sort((a, b) => a.id - b.id), }, ].forEach(testCase => check(testCase)); }); const topicNarrow1 = topicNarrow(stream1.stream_id, topic1); test(`${keyFromNarrow(topicNarrow1)}`, () => { [ { narrow: topicNarrow1, messages: streamMessages1 }, { narrow: topicNarrow1, messages: streamMessages2 }, { narrow: topicNarrow1, messages: streamMessages5 }, { narrow: topicNarrow1, // All together, sorted by ID. (Which basically means jumbled; // the IDs in each sub-list are only internally sorted.) messages: [...streamMessages1, ...streamMessages2, ...streamMessages5].sort( (a, b) => a.id - b.id, ), }, ].forEach(testCase => check(testCase)); }); const pmNarrow1to1 = pmNarrowFromUsersUnsafe([user1, user2]); test(`${keyFromNarrow(pmNarrow1to1)}`, () => { [ { narrow: pmNarrow1to1, messages: pmMessages1 }, { narrow: pmNarrow1to1, messages: pmMessages2 }, { narrow: pmNarrow1to1, messages: pmMessages3 }, { narrow: pmNarrow1to1, // All together, sorted by ID. (Which basically means jumbled; // the IDs in each sub-list are only internally sorted.) messages: [...pmMessages1, ...pmMessages2, ...pmMessages3].sort((a, b) => a.id - b.id), }, ].forEach(testCase => check(testCase)); }); const pmNarrowGroup = pmNarrowFromUsersUnsafe([user1, user2, user3]); test(`${keyFromNarrow(pmNarrowGroup)}`, () => { [ { narrow: pmNarrowGroup, messages: pmMessages4 }, { narrow: pmNarrowGroup, messages: pmMessages5 }, { narrow: pmNarrowGroup, messages: pmMessages6 }, { narrow: pmNarrowGroup, // All together, sorted by ID. (Which basically means jumbled; // the IDs in each sub-list are only internally sorted.) messages: [...pmMessages4, ...pmMessages5, ...pmMessages6].sort((a, b) => a.id - b.id), }, ].forEach(testCase => check(testCase)); }); test(`${keyFromNarrow(ALL_PRIVATE_NARROW)}`, () => { [ { narrow: ALL_PRIVATE_NARROW, messages: pmMessages1 }, { narrow: ALL_PRIVATE_NARROW, messages: pmMessages2 }, { narrow: ALL_PRIVATE_NARROW, messages: pmMessages3 }, { narrow: ALL_PRIVATE_NARROW, messages: pmMessages4 }, { narrow: ALL_PRIVATE_NARROW, messages: pmMessages5 }, { narrow: ALL_PRIVATE_NARROW, messages: pmMessages6 }, { narrow: ALL_PRIVATE_NARROW, // All together, sorted by ID. (Which basically means jumbled; // the IDs in each sub-list are only internally sorted.) messages: [ ...pmMessages1, ...pmMessages2, ...pmMessages3, ...pmMessages4, ...pmMessages5, ...pmMessages6, ].sort((a, b) => a.id - b.id), }, ].forEach(testCase => check(testCase)); }); describe('other interesting cases (single messages)', () => { const stableSelfUser = eg.makeUser({ user_id: 1, full_name: 'Nonrandom name self User' }); const stableOtherUser = eg.makeUser({ user_id: 2, full_name: 'Nonrandom name other User' }); const stableThirdUser = eg.makeUser({ user_id: 3, full_name: 'Nonrandom name third User' }); const stableFourthUser = eg.makeUser({ user_id: 4, full_name: 'Nonrandom name fourth User' }); const singleMessageSender = eg.makeUser({ user_id: 10, full_name: 'Nonrandom name sender User', }); const baseSingleMessage = eg.streamMessage({ id: 1, timestamp: -1, stream: stream1, sender: singleMessageSender, }); test('message in unsubscribed stream', () => { check({ narrow: HOME_NARROW, messages: [baseSingleMessage], state: eg.reduxStatePlus({ streams: [...eg.plusReduxState.streams, stream1, stream2], subscriptions: [ ...eg.plusReduxState.subscriptions, // no subscription for stream1 eg.makeSubscription({ stream: stream2 }), ], }), }); }); test('message in followed topic', () => { check({ narrow: HOME_NARROW, messages: [baseSingleMessage], state: eg.reduxStatePlus({ streams: [...eg.plusReduxState.streams, stream1], subscriptions: [ ...eg.plusReduxState.subscriptions, eg.makeSubscription({ stream: stream1 }), ], mute: makeMuteState([ [stream1, baseSingleMessage.subject, UserTopicVisibilityPolicy.Followed], ]), }), }); }); describe('message with reactions', () => { describe('displayEmojiReactionUsers: false', () => { const state = eg.reduxStatePlus({ settings: { ...eg.plusReduxState.settings, displayEmojiReactionUsers: false }, users: [stableSelfUser, stableOtherUser, stableThirdUser], realm: { ...eg.plusReduxState.realm, user_id: stableSelfUser.user_id }, }); test('few reactions', () => { check({ narrow: HOME_NARROW, messages: [ { ...baseSingleMessage, reactions: [{ ...eg.unicodeEmojiReaction, user_id: stableSelfUser.user_id }], }, ], state, }); }); test('many reactions', () => { check({ narrow: HOME_NARROW, messages: [ { ...baseSingleMessage, reactions: [ { ...eg.unicodeEmojiReaction, user_id: stableSelfUser.user_id }, { ...eg.zulipExtraEmojiReaction, user_id: stableSelfUser.user_id }, { ...eg.realmEmojiReaction, user_id: stableOtherUser.user_id }, { ...eg.realmEmojiReaction, user_id: stableThirdUser.user_id }, ], }, ], state, }); }); }); describe('displayEmojiReactionUsers: true', () => { const state = eg.reduxStatePlus({ settings: { ...eg.plusReduxState.settings, displayEmojiReactionUsers: true }, users: [stableSelfUser, stableOtherUser, stableThirdUser, stableFourthUser], realm: { ...eg.plusReduxState.realm, user_id: stableSelfUser.user_id }, }); test('3 votes on same emoji', () => { check({ narrow: HOME_NARROW, messages: [ { ...baseSingleMessage, reactions: [ { ...eg.unicodeEmojiReaction, user_id: stableSelfUser.user_id }, { ...eg.unicodeEmojiReaction, user_id: stableOtherUser.user_id }, { ...eg.unicodeEmojiReaction, user_id: stableThirdUser.user_id }, ], }, ], state, }); }); test('3 votes on multiple emoji', () => { check({ narrow: HOME_NARROW, messages: [ { ...baseSingleMessage, reactions: [ { ...eg.unicodeEmojiReaction, user_id: stableSelfUser.user_id }, { ...eg.zulipExtraEmojiReaction, user_id: stableSelfUser.user_id }, { ...eg.realmEmojiReaction, user_id: stableOtherUser.user_id }, ], }, ], state, }); }); test('4 votes on same emoji', () => { check({ narrow: HOME_NARROW, messages: [ { ...baseSingleMessage, reactions: [ { ...eg.unicodeEmojiReaction, user_id: stableSelfUser.user_id }, { ...eg.unicodeEmojiReaction, user_id: stableOtherUser.user_id }, { ...eg.unicodeEmojiReaction, user_id: stableThirdUser.user_id }, { ...eg.unicodeEmojiReaction, user_id: stableFourthUser.user_id }, ], }, ], state, }); }); test('4 votes on multiple emoji', () => { check({ narrow: HOME_NARROW, messages: [ { ...baseSingleMessage, reactions: [ { ...eg.unicodeEmojiReaction, user_id: stableSelfUser.user_id }, { ...eg.zulipExtraEmojiReaction, user_id: stableSelfUser.user_id }, { ...eg.realmEmojiReaction, user_id: stableOtherUser.user_id }, { ...eg.realmEmojiReaction, user_id: stableThirdUser.user_id }, ], }, ], state, }); }); test('guest user reacts', () => { check({ narrow: HOME_NARROW, messages: [ { ...baseSingleMessage, reactions: [{ ...eg.realmEmojiReaction, user_id: stableOtherUser.user_id }], }, ], state: eg.reduxStatePlus({ settings: { ...eg.plusReduxState.settings, displayEmojiReactionUsers: true }, realm: { ...eg.plusReduxState.realm, user_id: stableSelfUser.user_id, enableGuestUserIndicator: true, }, users: [ stableSelfUser, stableOtherUser, { ...stableOtherUser, role: Role.Guest }, stableFourthUser, ], }), }); }); }); }); test('message with a poll', () => { const baseSubmessage = { message_id: baseSingleMessage.id, msg_type: 'widget', }; check({ narrow: HOME_NARROW, state: eg.reduxStatePlus({ realm: { ...eg.plusReduxState.realm, user_id: stableSelfUser.user_id }, users: [singleMessageSender, stableSelfUser, stableOtherUser], }), messages: [ { ...baseSingleMessage, submessages: [ { // poll ...baseSubmessage, content: '{"widget_type": "poll", "extra_data": {"question": "Choose a choice:", "options": []}}', sender_id: baseSingleMessage.sender_id, id: 1, }, { // "Choice A" added ...baseSubmessage, content: '{"type":"new_option","idx":1,"option":"Choice A"}', sender_id: baseSingleMessage.sender_id, id: 2, }, { // Vote for "Choice A" by self ...baseSubmessage, content: `{"type":"vote","key":"${baseSingleMessage.sender_id},1","vote":1}`, sender_id: stableSelfUser.user_id, id: 3, }, { // Vote for "Choice A" by other ...baseSubmessage, content: `{"type":"vote","key":"${baseSingleMessage.sender_id},1","vote":1}`, sender_id: stableOtherUser.user_id, id: 4, }, { // Vote for "Choice A" by sender ...baseSubmessage, content: `{"type":"vote","key":"${baseSingleMessage.sender_id},1","vote":1}`, sender_id: baseSingleMessage.sender_id, id: 5, }, { // "Choice B" added ...baseSubmessage, content: '{"type":"new_option","idx":2,"option":"Choice B"}', sender_id: baseSingleMessage.sender_id, id: 6, }, { // Vote for "Choice B" by other ...baseSubmessage, content: `{"type":"vote","key":"${baseSingleMessage.sender_id},2","vote":1}`, sender_id: stableOtherUser.user_id, id: 7, }, ], }, ], }); }); Object.keys(eg.plusReduxState.flags).forEach(flag => { test(`message with flag: ${flag}`, () => { const flags: ReadWrite<FlagsState> = { ...eg.plusBackgroundData.flags }; flags[flag] = { [baseSingleMessage.id]: true }; check({ narrow: HOME_NARROW, messages: [baseSingleMessage], state: eg.reduxStatePlus({ flags }), }); }); }); test('muted sender', () => { check({ narrow: HOME_NARROW, messages: [baseSingleMessage], state: eg.reduxStatePlus({ mutedUsers: Immutable.Map([[baseSingleMessage.sender_id, 1644366787]]), }), }); }); test('guest sender, with enableGuestUserIndicator', () => { check({ narrow: HOME_NARROW, messages: [baseSingleMessage], state: eg.reduxStatePlus({ realm: { ...eg.plusReduxState.realm, enableGuestUserIndicator: true }, users: [...eg.plusReduxState.users, { ...singleMessageSender, role: Role.Guest }], }), }); }); [ ['none', null], ['unicode', eg.userStatusEmojiUnicode], ['realm', eg.userStatusEmojiRealm], ['zulip extra', eg.userStatusEmojiZulipExtra], ].forEach(([description, statusEmoji]) => { test(`sender status emoji: ${description}`, () => { check({ narrow: HOME_NARROW, messages: [baseSingleMessage], state: eg.reduxStatePlus({ userStatuses: Immutable.Map([ [ baseSingleMessage.sender_id, { away: false, status_text: null, status_emoji: statusEmoji }, ], ]), }), }); }); }); }); }); describe('getEditSequence correct for interesting changes', () => { const resetMsglist = () => { invariant(document.body, 'expected jsdom environment'); document.body.innerHTML = '<div id="msglist-elements" />'; }; const getClonedMsglistElementsDiv = () => { const msglistElementsDiv = document.querySelector('div#msglist-elements'); invariant(msglistElementsDiv, 'getClonedMsglistElementsDiv: expected msglistElementsDiv'); return msglistElementsDiv.cloneNode(true); }; type CheckArg = {| state?: PerAccountState, globalSettings?: GlobalSettingsState, narrow?: Narrow, messages: $ReadOnlyArray<Message>, |}; const check = ( // TODO: Test with a variety of different things in state/globalState { state: oldState = baseState, globalSettings: oldGlobalSettings = getGlobalSettings(eg.plusReduxState), narrow: oldNarrow = HOME_NARROW, messages: oldMessages, }: CheckArg, { state: newState = baseState, globalSettings: newGlobalSettings = getGlobalSettings(eg.plusReduxState), narrow: newNarrow = HOME_NARROW, messages: newMessages, }: CheckArg, ) => { const oldBackgroundData = getBackgroundData(oldState, oldGlobalSettings); const newBackgroundData = getBackgroundData(newState, newGlobalSettings); const oldElements = getMessageListElements(oldMessages, oldNarrow); const newElements = getMessageListElements(newMessages, newNarrow); resetMsglist(); applyEditSequence( getEditSequence( { backgroundData: newBackgroundData, elements: [], _: mock_ }, { backgroundData: newBackgroundData, elements: newElements, _: mock_ }, ), ); const expectedMsglistElementsDiv = getClonedMsglistElementsDiv(); resetMsglist(); applyEditSequence( getEditSequence( { backgroundData: oldBackgroundData, elements: [], _: mock_ }, { backgroundData: oldBackgroundData, elements: oldElements, _: mock_ }, ), ); const realEditSequence = getEditSequence( { backgroundData: oldBackgroundData, elements: oldElements, _: mock_ }, { backgroundData: newBackgroundData, elements: newElements, _: mock_ }, ); expect(realEditSequence.length).toMatchSnapshot(); applyEditSequence(realEditSequence); expect(getClonedMsglistElementsDiv().isEqualNode(expectedMsglistElementsDiv)).toBeTrue(); }; // All together, sorted by ID. (Which basically means jumbled; // the IDs in each sub-list are only internally sorted.) const allMessages = [ ...streamMessages1, ...streamMessages2, ...streamMessages3, ...streamMessages4, ...streamMessages5, ...pmMessages1, ...pmMessages2, ...pmMessages3, ...pmMessages4, ...pmMessages5, ...pmMessages6, ].sort((a, b) => a.id - b.id); const withContentReplaced = <M: Message | Outbox>(m: M): M => ({ ...(m: M), content: randString(), }); describe('from empty', () => { test('to empty', () => { check({ messages: [] }, { messages: [] }); }); test('to one message', () => { check({ messages: [] }, { messages: [allMessages[0]] }); }); test('to many messages', () => { check({ messages: [] }, { messages: allMessages }); }); }); describe('from many messages', () => { test('to empty', () => { check({ messages: allMessages }, { messages: [] }); }); test('to disjoint set of many later messages', () => { check( { messages: allMessages.slice(0, allMessages.length / 2) }, { messages: allMessages.slice(allMessages.length / 2, allMessages.length) }, ); }); test('to disjoint set of many earlier messages', () => { check( { messages: allMessages.slice(allMessages.length / 2, allMessages.length) }, { messages: allMessages.slice(0, allMessages.length / 2) }, ); }); test('insert one message at end', () => { check({ messages: allMessages.slice(0, allMessages.length - 1) }, { messages: allMessages }); }); test('delete one message at end', () => { check({ messages: allMessages }, { messages: allMessages.slice(0, allMessages.length - 1) }); }); test('replace one message at end with new content', () => { check( { messages: allMessages }, { messages: [ ...allMessages.slice(0, allMessages.length - 1), withContentReplaced(allMessages[allMessages.length - 1]), ], }, ); }); test('insert one message at start', () => { check({ messages: allMessages.slice(1, allMessages.length) }, { messages: allMessages }); }); test('delete one message at start', () => { check({ messages: allMessages }, { messages: allMessages.slice(1, allMessages.length) }); }); test('replace one message at start with new content', () => { const [firstMessage, ...rest] = allMessages; check({ messages: allMessages }, { messages: [withContentReplaced(firstMessage), ...rest] }); }); test('insert many messages at end', () => { check({ messages: allMessages.slice(0, allMessages.length / 2) }, { messages: allMessages }); }); test('insert many messages at start', () => { check( { messages: allMessages.slice(allMessages.length / 2, allMessages.length - 1) }, { messages: allMessages }, ); }); test('insert many messages at start and end', () => { const firstThirdIndex = Math.floor(allMessages.length / 3); const secondThirdIndex = Math.floor(allMessages.length * (2 / 3)); check( { messages: allMessages.slice(firstThirdIndex, secondThirdIndex) }, { messages: allMessages }, ); }); test('delete many messages in middle', () => { const firstThirdIndex = Math.floor(allMessages.length / 3); const secondThirdIndex = Math.floor(allMessages.length * (2 / 3)); check( { messages: allMessages }, { messages: [ ...allMessages.slice(0, firstThirdIndex), ...allMessages.slice(secondThirdIndex, allMessages.length - 1), ], }, ); }); test('replace one message in middle with new content', () => { const midIndex = Math.floor(allMessages.length / 2); check( { messages: allMessages }, { messages: [ ...allMessages.slice(0, midIndex), withContentReplaced(allMessages[midIndex]), ...allMessages.slice(midIndex + 1, allMessages.length - 1), ], }, ); }); }); describe('DM recipient headers', () => { test("recipient user's name changed", () => { const sender = eg.selfUser; const message = eg.pmMessage({ sender, recipients: [eg.selfUser, eg.otherUser] }); check( { messages: [message], state: eg.reduxStatePlus({ users: [eg.selfUser, eg.otherUser] }), }, { messages: [message], state: eg.reduxStatePlus({ users: [eg.selfUser, { ...eg.otherUser, full_name: `${sender.full_name}, Jr.` }], }), }, ); }); test('enableGuestUserIndicator turns on, affecting a recipient user', () => { const user = { ...eg.otherUser, role: Role.Guest }; const users = [eg.selfUser, user]; const message = eg.pmMessage({ sender: eg.selfUser, recipients: [eg.otherUser, user] }); check( { messages: [message], state: eg.reduxStatePlus({ realm: { ...eg.plusReduxState.realm, enableGuestUserIndicator: false }, users, }), }, { messages: [message], state: eg.reduxStatePlus({ realm: { ...eg.plusReduxState.realm, enableGuestUserIndicator: true }, users, }), }, ); }); test('recipient user became guest', () => { const user = { ...eg.otherUser, role: Role.Member }; const message = eg.pmMessage({ sender: eg.selfUser, recipients: [eg.otherUser, user], }); check( { messages: [message], state: eg.reduxStatePlus({ users: [eg.selfUser, user] }), }, { messages: [message], state: eg.reduxStatePlus({ users: [eg.selfUser, { ...user, role: Role.Guest }] }), }, ); }); }); describe('within a given message', () => { test('add reactions to a message', () => { const message = eg.streamMessage(); check( { messages: [message] }, { messages: [{ ...message, reactions: [eg.unicodeEmojiReaction] }] }, ); }); test('remove reactions from a message', () => { const message = eg.streamMessage({ reactions: [eg.unicodeEmojiReaction] }); check({ messages: [message] }, { messages: [{ ...message, reactions: [] }] }); }); describe('polls', () => { const baseMessage = eg.streamMessage(); const baseSubmessage = { message_id: baseMessage.id, msg_type: 'widget', sender_id: baseMessage.sender_id, }; const msgWithPoll = { ...baseMessage, submessages: [ { ...baseSubmessage, content: '{"widget_type": "poll", "extra_data": {"question": "Choose a choice:", "options": []}}', id: 1, }, ], }; const msgWithChoice = { ...baseMessage, submessages: [ ...msgWithPoll.submessages, { ...baseSubmessage, content: '{"type":"new_option","idx":1,"option":"Choice A"}', id: 2, }, ], }; test('choice added', () => { check({ messages: [msgWithPoll] }, { messages: [msgWithChoice] }); }); const msgWithVote = { ...baseMessage, submessages: [ // TODO(server-1.9): No invariant needed when `.submessages` is // required. ...(() => { invariant(msgWithChoice.submessages, 'msgWithChoice has submessages'); return msgWithChoice.submessages; })(), { ...baseSubmessage, content: `{"type":"vote","key":"${baseMessage.sender_id},1","vote":1}`, id: 3, }, ], }; test('vote added', () => { check({ messages: [msgWithChoice] }, { messages: [msgWithVote] }); }); }); test('star a message', () => { const message = eg.streamMessage(); check( { messages: [message], state: eg.reduxStatePlus({ flags: { ...eg.plusReduxState.flags, starred: {} }, }), }, { messages: [message], state: eg.reduxStatePlus({ flags: { ...eg.plusReduxState.flags, starred: { [message.id]: true } }, }), }, ); }); test('unstar a message', () => { const message = eg.streamMessage(); check( { messages: [message], state: eg.reduxStatePlus({ flags: { ...eg.plusReduxState.flags, starred: { [message.id]: true } }, }), }, { messages: [message], state: eg.reduxStatePlus({ flags: { ...eg.plusReduxState.flags, starred: {} }, }), }, ); }); test('follow a topic', () => { const message = eg.streamMessage(); check( { messages: [message], state: eg.reduxStatePlus({ mute: makeMuteState([]), }), }, { messages: [message], state: eg.reduxStatePlus({ mute: makeMuteState([[eg.stream, message.subject, UserTopicVisibilityPolicy.Followed]]), }), }, ); }); test('unfollow a topic', () => { const message = eg.streamMessage(); check( { messages: [message], state: eg.reduxStatePlus({ mute: makeMuteState([[eg.stream, message.subject, UserTopicVisibilityPolicy.Followed]]), }), }, { messages: [message], state: eg.reduxStatePlus({ mute: makeMuteState([]), }), }, ); }); test("sender's name changed", () => { const baseUsers = eg.plusReduxState.users; const sender = eg.makeUser(); const message = eg.streamMessage({ sender }); check( { messages: [message], state: eg.reduxStatePlus({ users: [...baseUsers, sender] }), }, { messages: [message], state: eg.reduxStatePlus({ users: [...baseUsers, { ...sender, full_name: `${sender.full_name}, Jr.` }], }), }, ); }); test('sender becomes guest', () => { const baseUsers = eg.plusReduxState.users; const sender = eg.makeUser({ role: Role.Member }); const message = eg.streamMessage({ sender }); check( { messages: [message], state: eg.reduxStatePlus({ realm: { ...eg.plusReduxState.realm, enableGuestUserIndicator: true }, users: [...baseUsers, sender], }), }, { messages: [message], state: eg.reduxStatePlus({ realm: { ...eg.plusReduxState.realm, enableGuestUserIndicator: true }, users: [...baseUsers, { ...sender, role: Role.Guest }], }), }, ); }); test('enableGuestUserIndicator turns on, and sender is guest', () => { const sender = eg.makeUser({ role: Role.Guest }); const users = [...eg.plusReduxState.users, sender]; const message = eg.streamMessage({ sender }); check( { messages: [message], state: eg.reduxStatePlus({ realm: { ...eg.plusReduxState.realm, enableGuestUserIndicator: false }, users, }), }, { messages: [message], state: eg.reduxStatePlus({ realm: { ...eg.plusReduxState.realm, enableGuestUserIndicator: true }, users, }), }, ); }); // TODO(#5208) test.todo("sender's avatar changed"); test('mute a sender', () => { const message = eg.streamMessage(); check( { messages: [message], state: eg.reduxStatePlus({ mutedUsers: Immutable.Map() }), }, { messages: [message], state: eg.reduxStatePlus({ mutedUsers: Immutable.Map([[message.sender_id, 1644366787]]), }), }, ); }); test('unmute a sender', () => { const message = eg.streamMessage(); check( { messages: [message], state: eg.reduxStatePlus({ mutedUsers: Immutable.Map([[message.sender_id, 1644366787]]), }), }, { messages: [message], state: eg.reduxStatePlus({ mutedUsers: Immutable.Map() }), }, ); }); describe('add/remove/change emoji status', () => { const message = eg.streamMessage(); const emojiStatuses = [ ['none', null], ['unicode', eg.userStatusEmojiUnicode], ['realm', eg.userStatusEmojiRealm], ['zulip extra', eg.userStatusEmojiZulipExtra], ]; emojiStatuses.forEach(([statusALabel, emojiStatusA]) => { emojiStatuses.forEach(([statusBLabel, emojiStatusB]) => { let description = `status emoji: ${statusALabel} -> ${statusBLabel}`; if (emojiStatusA === emojiStatusB) { description += ' (no change)'; } test(description, () => { check( ...[emojiStatusA, emojiStatusB].map(emojiStatus => ({ messages: [message], state: eg.reduxStatePlus({ userStatuses: Immutable.Map([ [ message.sender_id, { away: false, status_text: null, status_emoji: emojiStatus, }, ], ]), }), })), ); }); }); }); }); }); }); ```
/content/code_sandbox/src/webview/__tests__/generateInboundEventEditSequence-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
9,529
```unknown // Jest Snapshot v1, path_to_url exports[`getEditSequence correct for interesting changes DM recipient headers enableGuestUserIndicator turns on, affecting a recipient user 1`] = `3`; exports[`getEditSequence correct for interesting changes DM recipient headers recipient user became guest 1`] = `1`; exports[`getEditSequence correct for interesting changes DM recipient headers recipient user's name changed 1`] = `1`; exports[`getEditSequence correct for interesting changes from empty to empty 1`] = `0`; exports[`getEditSequence correct for interesting changes from empty to many messages 1`] = `40`; exports[`getEditSequence correct for interesting changes from empty to one message 1`] = `3`; exports[`getEditSequence correct for interesting changes from many messages delete many messages in middle 1`] = `12`; exports[`getEditSequence correct for interesting changes from many messages delete one message at end 1`] = `2`; exports[`getEditSequence correct for interesting changes from many messages delete one message at start 1`] = `6`; exports[`getEditSequence correct for interesting changes from many messages insert many messages at end 1`] = `20`; exports[`getEditSequence correct for interesting changes from many messages insert many messages at start 1`] = `24`; exports[`getEditSequence correct for interesting changes from many messages insert many messages at start and end 1`] = `32`; exports[`getEditSequence correct for interesting changes from many messages insert one message at end 1`] = `2`; exports[`getEditSequence correct for interesting changes from many messages insert one message at start 1`] = `6`; exports[`getEditSequence correct for interesting changes from many messages replace one message at end with new content 1`] = `2`; exports[`getEditSequence correct for interesting changes from many messages replace one message at start with new content 1`] = `3`; exports[`getEditSequence correct for interesting changes from many messages replace one message in middle with new content 1`] = `3`; exports[`getEditSequence correct for interesting changes from many messages to disjoint set of many earlier messages 1`] = `42`; exports[`getEditSequence correct for interesting changes from many messages to disjoint set of many later messages 1`] = `42`; exports[`getEditSequence correct for interesting changes from many messages to empty 1`] = `40`; exports[`getEditSequence correct for interesting changes within a given message add reactions to a message 1`] = `3`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: none -> none (no change) 1`] = `0`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: none -> realm 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: none -> unicode 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: none -> zulip extra 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: realm -> none 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: realm -> realm (no change) 1`] = `0`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: realm -> unicode 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: realm -> zulip extra 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: unicode -> none 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: unicode -> realm 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: unicode -> unicode (no change) 1`] = `0`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: unicode -> zulip extra 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: zulip extra -> none 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: zulip extra -> realm 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: zulip extra -> unicode 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: zulip extra -> zulip extra (no change) 1`] = `0`; exports[`getEditSequence correct for interesting changes within a given message enableGuestUserIndicator turns on, and sender is guest 1`] = `3`; exports[`getEditSequence correct for interesting changes within a given message follow a topic 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message mute a sender 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message polls choice added 1`] = `3`; exports[`getEditSequence correct for interesting changes within a given message polls vote added 1`] = `3`; exports[`getEditSequence correct for interesting changes within a given message remove reactions from a message 1`] = `3`; exports[`getEditSequence correct for interesting changes within a given message sender becomes guest 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message sender's name changed 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message star a message 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message unfollow a topic 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message unmute a sender 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message unstar a message 1`] = `1`; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1024\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1024\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Feb 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1024\\" data-msg-id=\\"1024\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-1598\\" data-msg-id=\\"1598\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 2`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"7938\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"7938\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-7938\\" data-msg-id=\\"7938\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8060\\" data-msg-id=\\"8060\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 3`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"4948\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"4948\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Feb 19, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-4948\\" data-msg-id=\\"4948\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"5083\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAy\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 2</div> <div class=\\"topic-date\\">Feb 19, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5083\\" data-msg-id=\\"5083\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 4`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"6789\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"6789\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-6789\\" data-msg-id=\\"6789\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"7727\\" data-narrow=\\"dG9waWM6Mjp0b3BpYyAy\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjI=\\"> # stream 2 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 2</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-7727\\" data-msg-id=\\"7727\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 5`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"9181\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"9181\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9181\\" data-msg-id=\\"9181\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"9815\\"> <div class=\\"timerow-left\\"></div> Mar 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9815\\" data-msg-id=\\"9815\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 6`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"8849\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"8849\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8849\\" data-msg-id=\\"8849\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-8917\\" data-msg-id=\\"8917\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 7`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5287\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"5287\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5287\\" data-msg-id=\\"5287\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5309\\" data-msg-id=\\"5309\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 8`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5829\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"5829\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5829\\" data-msg-id=\\"5829\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"5963\\"> <div class=\\"timerow-left\\"></div> Feb 26, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5963\\" data-msg-id=\\"5963\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 9`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5377\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwyLDM=\\" data-msg-id=\\"5377\\"> Nonrandom name one User, Nonrandom name three User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5377\\" data-msg-id=\\"5377\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-5620\\" data-msg-id=\\"5620\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 10`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5637\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwyLDM=\\" data-msg-id=\\"5637\\"> Nonrandom name one User, Nonrandom name three User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5637\\" data-msg-id=\\"5637\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5727\\" data-msg-id=\\"5727\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 11`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"2794\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwyLDM=\\" data-msg-id=\\"2794\\"> Nonrandom name one User, Nonrandom name three User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-2794\\" data-msg-id=\\"2794\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"4581\\"> <div class=\\"timerow-left\\"></div> Feb 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-4581\\" data-msg-id=\\"4581\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 12`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1024\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1024\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Feb 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1024\\" data-msg-id=\\"1024\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-1598\\" data-msg-id=\\"1598\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwyLDM=\\" data-msg-id=\\"2794\\"> Nonrandom name one User, Nonrandom name three User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-2794\\" data-msg-id=\\"2794\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"4581\\"> <div class=\\"timerow-left\\"></div> Feb 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-4581\\" data-msg-id=\\"4581\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"4948\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"4948\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Feb 19, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-4948\\" data-msg-id=\\"4948\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"5083\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAy\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 2</div> <div class=\\"topic-date\\">Feb 19, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5083\\" data-msg-id=\\"5083\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"5287\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5287\\" data-msg-id=\\"5287\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5309\\" data-msg-id=\\"5309\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwyLDM=\\" data-msg-id=\\"5377\\"> Nonrandom name one User, Nonrandom name three User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5377\\" data-msg-id=\\"5377\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-5620\\" data-msg-id=\\"5620\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-5637\\" data-msg-id=\\"5637\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5727\\" data-msg-id=\\"5727\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"5829\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5829\\" data-msg-id=\\"5829\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"5963\\"> <div class=\\"timerow-left\\"></div> Feb 26, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5963\\" data-msg-id=\\"5963\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"6789\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"6789\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-6789\\" data-msg-id=\\"6789\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"7727\\" data-narrow=\\"dG9waWM6Mjp0b3BpYyAy\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjI=\\"> # stream 2 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 2</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-7727\\" data-msg-id=\\"7727\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"7938\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-7938\\" data-msg-id=\\"7938\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8060\\" data-msg-id=\\"8060\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"8849\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8849\\" data-msg-id=\\"8849\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-8917\\" data-msg-id=\\"8917\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"9181\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9181\\" data-msg-id=\\"9181\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"9815\\"> <div class=\\"timerow-left\\"></div> Mar 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9815\\" data-msg-id=\\"9815\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible all-pm 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"8849\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"8849\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8849\\" data-msg-id=\\"8849\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-8917\\" data-msg-id=\\"8917\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible all-pm 2`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5287\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"5287\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5287\\" data-msg-id=\\"5287\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5309\\" data-msg-id=\\"5309\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible all-pm 3`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5829\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"5829\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5829\\" data-msg-id=\\"5829\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"5963\\"> <div class=\\"timerow-left\\"></div> Feb 26, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5963\\" data-msg-id=\\"5963\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible all-pm 4`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5377\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwyLDM=\\" data-msg-id=\\"5377\\"> Nonrandom name one User, Nonrandom name three User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5377\\" data-msg-id=\\"5377\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-5620\\" data-msg-id=\\"5620\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible all-pm 5`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5637\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwyLDM=\\" data-msg-id=\\"5637\\"> Nonrandom name one User, Nonrandom name three User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5637\\" data-msg-id=\\"5637\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5727\\" data-msg-id=\\"5727\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible all-pm 6`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"2794\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwyLDM=\\" data-msg-id=\\"2794\\"> Nonrandom name one User, Nonrandom name three User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-2794\\" data-msg-id=\\"2794\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"4581\\"> <div class=\\"timerow-left\\"></div> Feb 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-4581\\" data-msg-id=\\"4581\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible all-pm 7`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"2794\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwyLDM=\\" data-msg-id=\\"2794\\"> Nonrandom name one User, Nonrandom name three User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-2794\\" data-msg-id=\\"2794\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"4581\\"> <div class=\\"timerow-left\\"></div> Feb 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-4581\\" data-msg-id=\\"4581\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"5287\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"5287\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5287\\" data-msg-id=\\"5287\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5309\\" data-msg-id=\\"5309\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwyLDM=\\" data-msg-id=\\"5377\\"> Nonrandom name one User, Nonrandom name three User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5377\\" data-msg-id=\\"5377\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-5620\\" data-msg-id=\\"5620\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-5637\\" data-msg-id=\\"5637\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5727\\" data-msg-id=\\"5727\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"5829\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5829\\" data-msg-id=\\"5829\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"5963\\"> <div class=\\"timerow-left\\"></div> Feb 26, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5963\\" data-msg-id=\\"5963\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"8849\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8849\\" data-msg-id=\\"8849\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-8917\\" data-msg-id=\\"8917\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) guest sender, with enableGuestUserIndicator 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"{userFullName} (guest)\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> {userFullName} (guest) </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message in followed topic 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"true\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message in unsubscribed stream 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with a poll 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <div class=\\"poll-widget\\"> <p class=\\"poll-question\\">Choose a choice:</p> <ul> <li> <button class=\\"poll-vote\\" data-voted=\\"true\\" data-key=\\"10,1\\">3</button> <span class=\\"poll-option\\">Choice A</span> </li> <li> <button class=\\"poll-vote\\" data-voted=\\"false\\" data-key=\\"10,2\\">1</button> <span class=\\"poll-option\\">Choice B</span> </li> </ul> </div> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with flag: collapsed 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\" data-collapsed=\\"true\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with flag: has_alert_word 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\" data-has_alert_word=\\"true\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with flag: historical 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\" data-historical=\\"true\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with flag: mentioned 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\" data-mentioned=\\"true\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with flag: read 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\" data-read=\\"true\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with flag: starred 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\" data-starred=\\"true\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> <div class=\\"message-tags\\"><span class=\\"message-tag\\">starred</span></div> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with flag: wildcard_mentioned 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\" data-wildcard_mentioned=\\"true\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with reactions displayEmojiReactionUsers: false few reactions 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> <div class=\\"reaction-list\\"><span onclick=\\"\\" class=\\"reaction self-voted\\" data-name=\\"thumbs_up\\" data-code=\\"1f44d\\" data-type=\\"unicode_emoji\\">&nbsp;1</span></div> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with reactions displayEmojiReactionUsers: false many reactions 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> <div class=\\"reaction-list\\"><span onclick=\\"\\" class=\\"reaction\\" data-name=\\"github_parrot\\" data-code=\\"80\\" data-type=\\"realm_emoji\\"><img src=\\"path_to_url">&nbsp;2</span><span onclick=\\"\\" class=\\"reaction self-voted\\" data-name=\\"thumbs_up\\" data-code=\\"1f44d\\" data-type=\\"unicode_emoji\\">&nbsp;1</span><span onclick=\\"\\" class=\\"reaction self-voted\\" data-name=\\"zulip\\" data-code=\\"zulip\\" data-type=\\"zulip_extra_emoji\\"><img src=\\"path_to_url">&nbsp;1</span></div> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with reactions displayEmojiReactionUsers: true 3 votes on multiple emoji 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> <div class=\\"reaction-list\\"><span onclick=\\"\\" class=\\"reaction self-voted\\" data-name=\\"thumbs_up\\" data-code=\\"1f44d\\" data-type=\\"unicode_emoji\\">&nbsp;You</span><span onclick=\\"\\" class=\\"reaction self-voted\\" data-name=\\"zulip\\" data-code=\\"zulip\\" data-type=\\"zulip_extra_emoji\\"><img src=\\"path_to_url">&nbsp;You</span><span onclick=\\"\\" class=\\"reaction\\" data-name=\\"github_parrot\\" data-code=\\"80\\" data-type=\\"realm_emoji\\"><img src=\\"path_to_url">&nbsp;Nonrandom name other User</span></div> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with reactions displayEmojiReactionUsers: true 3 votes on same emoji 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> <div class=\\"reaction-list\\"><span onclick=\\"\\" class=\\"reaction self-voted\\" data-name=\\"thumbs_up\\" data-code=\\"1f44d\\" data-type=\\"unicode_emoji\\">&nbsp;You, Nonrandom name other User, Nonrandom name third User</span></div> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with reactions displayEmojiReactionUsers: true 4 votes on multiple emoji 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> <div class=\\"reaction-list\\"><span onclick=\\"\\" class=\\"reaction\\" data-name=\\"github_parrot\\" data-code=\\"80\\" data-type=\\"realm_emoji\\"><img src=\\"path_to_url">&nbsp;2</span><span onclick=\\"\\" class=\\"reaction self-voted\\" data-name=\\"thumbs_up\\" data-code=\\"1f44d\\" data-type=\\"unicode_emoji\\">&nbsp;1</span><span onclick=\\"\\" class=\\"reaction self-voted\\" data-name=\\"zulip\\" data-code=\\"zulip\\" data-type=\\"zulip_extra_emoji\\"><img src=\\"path_to_url">&nbsp;1</span></div> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with reactions displayEmojiReactionUsers: true 4 votes on same emoji 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> <div class=\\"reaction-list\\"><span onclick=\\"\\" class=\\"reaction self-voted\\" data-name=\\"thumbs_up\\" data-code=\\"1f44d\\" data-type=\\"unicode_emoji\\">&nbsp;4</span></div> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with reactions displayEmojiReactionUsers: true guest user reacts 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> <div class=\\"reaction-list\\"><span onclick=\\"\\" class=\\"reaction\\" data-name=\\"github_parrot\\" data-code=\\"80\\" data-type=\\"realm_emoji\\"><img src=\\"path_to_url">&nbsp;{userFullName} (guest)</span></div> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) muted sender 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"hidden\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> <div class=\\"special-message muted-message-explanation\\"> This message was hidden because it is from a user you have muted. Long-press to view. </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) sender status emoji: none 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) sender status emoji: realm 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User<img class=\\"status-emoji\\" src=\\"path_to_url"> </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) sender status emoji: unicode 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User<span class=\\"status-emoji\\"></span> </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) sender status emoji: zulip extra 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User<img class=\\"status-emoji\\" src=\\"path_to_url"> </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible pm:1,2 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"8849\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8849\\" data-msg-id=\\"8849\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-8917\\" data-msg-id=\\"8917\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible pm:1,2 2`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5287\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5287\\" data-msg-id=\\"5287\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5309\\" data-msg-id=\\"5309\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible pm:1,2 3`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5829\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5829\\" data-msg-id=\\"5829\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"5963\\"> <div class=\\"timerow-left\\"></div> Feb 26, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5963\\" data-msg-id=\\"5963\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible pm:1,2 4`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5287\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5287\\" data-msg-id=\\"5287\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5309\\" data-msg-id=\\"5309\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5829\\" data-msg-id=\\"5829\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"5963\\"> <div class=\\"timerow-left\\"></div> Feb 26, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5963\\" data-msg-id=\\"5963\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"8849\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8849\\" data-msg-id=\\"8849\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-8917\\" data-msg-id=\\"8917\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible pm:1,2,3 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5377\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5377\\" data-msg-id=\\"5377\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-5620\\" data-msg-id=\\"5620\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible pm:1,2,3 2`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5637\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5637\\" data-msg-id=\\"5637\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5727\\" data-msg-id=\\"5727\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible pm:1,2,3 3`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"2794\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-2794\\" data-msg-id=\\"2794\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"4581\\"> <div class=\\"timerow-left\\"></div> Feb 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-4581\\" data-msg-id=\\"4581\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible pm:1,2,3 4`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"2794\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-2794\\" data-msg-id=\\"2794\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"4581\\"> <div class=\\"timerow-left\\"></div> Feb 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-4581\\" data-msg-id=\\"4581\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"5377\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5377\\" data-msg-id=\\"5377\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-5620\\" data-msg-id=\\"5620\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-5637\\" data-msg-id=\\"5637\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5727\\" data-msg-id=\\"5727\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible stream:1 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1024\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header topic-header\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\" data-msg-id=\\"1024\\"> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Feb 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1024\\" data-msg-id=\\"1024\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-1598\\" data-msg-id=\\"1598\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible stream:1 2`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"7938\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header topic-header\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\" data-msg-id=\\"7938\\"> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-7938\\" data-msg-id=\\"7938\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8060\\" data-msg-id=\\"8060\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible stream:1 3`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"4948\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header topic-header\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\" data-msg-id=\\"4948\\"> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Feb 19, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-4948\\" data-msg-id=\\"4948\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element header-wrapper header topic-header\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAy\\" data-msg-id=\\"5083\\"> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 2</div> <div class=\\"topic-date\\">Feb 19, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5083\\" data-msg-id=\\"5083\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible stream:1 4`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"9181\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header topic-header\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\" data-msg-id=\\"9181\\"> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9181\\" data-msg-id=\\"9181\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"9815\\"> <div class=\\"timerow-left\\"></div> Mar 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9815\\" data-msg-id=\\"9815\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible stream:1 5`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1024\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header topic-header\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\" data-msg-id=\\"1024\\"> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Feb 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1024\\" data-msg-id=\\"1024\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-1598\\" data-msg-id=\\"1598\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"4948\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-4948\\" data-msg-id=\\"4948\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element header-wrapper header topic-header\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAy\\" data-msg-id=\\"5083\\"> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 2</div> <div class=\\"topic-date\\">Feb 19, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5083\\" data-msg-id=\\"5083\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"7938\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header topic-header\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\" data-msg-id=\\"7938\\"> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-7938\\" data-msg-id=\\"7938\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8060\\" data-msg-id=\\"8060\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9181\\" data-msg-id=\\"9181\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"9815\\"> <div class=\\"timerow-left\\"></div> Mar 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9815\\" data-msg-id=\\"9815\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible topic:1:topic 1 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1024\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1024\\" data-msg-id=\\"1024\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-1598\\" data-msg-id=\\"1598\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible topic:1:topic 1 2`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"7938\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-7938\\" data-msg-id=\\"7938\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8060\\" data-msg-id=\\"8060\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible topic:1:topic 1 3`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"9181\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9181\\" data-msg-id=\\"9181\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"9815\\"> <div class=\\"timerow-left\\"></div> Mar 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9815\\" data-msg-id=\\"9815\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible topic:1:topic 1 4`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1024\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1024\\" data-msg-id=\\"1024\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-1598\\" data-msg-id=\\"1598\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"7938\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-7938\\" data-msg-id=\\"7938\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8060\\" data-msg-id=\\"8060\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9181\\" data-msg-id=\\"9181\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"9815\\"> <div class=\\"timerow-left\\"></div> Mar 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9815\\" data-msg-id=\\"9815\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; ```
/content/code_sandbox/src/webview/__tests__/__snapshots__/generateInboundEventEditSequence-test.js.snap.ios
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
39,602
```javascript // @flow strict-local /** * Heartbeat: Perform callbacks at regular intervals. * * While active, calls `callback` every `milliseconds` milliseconds. * While inactive, does nothing. * * On becoming active, the first call to `callback` comes immediately, * or one full period after the last call made when previously active, * whichever is later. * * (Despite the generic-looking definition, this class is closely tailored to * user-presence reporting.) */ class Heartbeat { // There are three possible states -- off, on, and zombie: // // "off" "zombie" "on" // _active false false true // _intervalId null non-null non-null // // The state machine is (omitting no-op transitions): // // --init---> off ----start()---------\ // ^ \ // | | // doCallback() | // | | // | /---start()--\ | // | / v / // zombie <--stop()--- on <--/ // // The "zombie" state has a visible difference from "off" if we end // up calling start() again before the interval next fires: it's how // we make sure to call the callback on the original regular schedule, // rather than another full interval after the new start() call. _callback: () => void; _milliseconds: number; _active: boolean = false; _intervalId: IntervalID | null = null; constructor(callback: () => void, milliseconds: number) { this._callback = callback; this._milliseconds = milliseconds; } doCallback: () => void = () => { if (!this._active) { clearInterval(this._intervalId); this._intervalId = null; return; } this._callback(); }; /** PRIVATE. Exposed only for tests. */ isActive(): boolean { return this._active; } /** Start the heartbeat. Idempotent. */ start() { if (this._active) { return; } this._active = true; if (this._intervalId === null) { this.doCallback(); this._intervalId = setInterval(this.doCallback, this._milliseconds); } } /** Stop the heartbeat. Idempotent. */ stop() { this._active = false; } /** Set the current heartbeat state. Idempotent. */ toState(active: boolean) { if (active) { this.start(); } else { this.stop(); } } } export default Heartbeat; ```
/content/code_sandbox/src/presence/heartbeat.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
594
```javascript // @flow strict-local import * as React from 'react'; import { AppState } from 'react-native'; import { useGlobalSelector, useSelector, useDispatch } from '../react-redux'; import { getHasAuth } from '../account/accountsSelectors'; import { reportPresence } from '../actions'; import Heartbeat from './heartbeat'; import { getPresence } from './presenceModel'; type Props = $ReadOnly<{||}>; /** * Component providing a recurrent `presence` signal. */ // TODO(#5005): either make one of these per account, or make it act on all accounts export default function PresenceHeartbeat(props: Props): React.Node { const dispatch = useDispatch(); const hasAuth = useGlobalSelector(getHasAuth); // a job for withHaveServerDataGate? const pingIntervalSeconds = useSelector(state => getPresence(state).pingIntervalSeconds); React.useEffect(() => { if (!hasAuth) { return; } const onHeartbeat = () => { // TODO(#5005): should ensure this gets the intended account dispatch(reportPresence(true)); }; const heartbeat = new Heartbeat(onHeartbeat, pingIntervalSeconds * 1000); // React to any state change. const updateHeartbeatState = () => { // heartbeat.toState is idempotent heartbeat.toState(AppState.currentState === 'active'); }; const sub = AppState.addEventListener('change', updateHeartbeatState); updateHeartbeatState(); // conditional start return () => { sub.remove(); heartbeat.stop(); // unconditional stop }; }, [dispatch, hasAuth, pingIntervalSeconds]); return null; } ```
/content/code_sandbox/src/presence/PresenceHeartbeat.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
349
```javascript /* @flow strict-local */ import Immutable from 'immutable'; import differenceInSeconds from 'date-fns/differenceInSeconds'; import differenceInDays from 'date-fns/differenceInDays'; import formatDistanceToNow from 'date-fns/formatDistanceToNow'; import type { ClientPresence, UserPresence, PresenceStatus, PresenceState, PerAccountApplicableAction, } from '../types'; import { ensureUnreachable } from '../types'; import { objectEntries } from '../flowPonyfill'; import type { PerAccountState } from '../reduxTypes'; import type { UserId } from '../api/idTypes'; import { tryGetUserForId } from '../users/userSelectors'; import { getUserStatus } from '../user-statuses/userStatusesModel'; import { getZulipFeatureLevel } from '../account/accountsSelectors'; import { EVENT_PRESENCE, PRESENCE_RESPONSE, REGISTER_COMPLETE, RESET_ACCOUNT_DATA, } from '../actionConstants'; import type { UserOrBot } from '../api/modelTypes'; // // // Simple selectors and getters. // export const getPresence = (state: PerAccountState): PresenceState => state.presence; function getUserPresenceByEmail(state: PresenceState, email: string): UserPresence | void { return state.byEmail.get(email); } // // // More-complex selectors, getters, and friends. // /** The relation `>=`, where `active` > `idle` > `offline`. */ const presenceStatusGeq = (a: PresenceStatus, b: PresenceStatus): boolean => { /* prettier-ignore */ switch (a) { case 'active': return true; case 'idle': return b !== 'active'; case 'offline': return b !== 'active' && b !== 'idle'; default: ensureUnreachable(a); return false; } }; /** * Aggregate our information on a user's presence across their clients. * * For an explanation of the Zulip presence model this helps implement, see * the subsystem doc: * path_to_url * * This logic should match `status_from_timestamp` in the web app's * `static/js/presence.js` at 1ae07b93d^. */ export const getAggregatedPresence = ( presence: UserPresence, offlineThresholdSeconds: number, ): ClientPresence => { /* Gives an artificial ClientPresence object where * - `timestamp` is the latest `timestamp` of all ClientPresence * objects in the input, and * - `status` is the greatest `status` of all *recent* ClientPresence * objects, where `active` > `idle` > `offline`. If there are no * recent ClientPresence objects (i.e., they are all at least as * old as offlineThresholdSeconds), `status` is 'offline'. If there * are several ClientPresence objects with the greatest * PresenceStatus, an arbitrary one is chosen. * - `client` is the `client` of the ClientPresence object from the * calculation of `status` (see previous), or empty string if * there wasn't one. * * It may not be entirely correct, but the `timestamp`'s * ClientPresence object may be a different one than what `status` * and `client` were drawn from. */ let status = 'offline'; let client = ''; let timestamp = 0; const dateNow = Date.now(); for (const [device, devicePresence] of objectEntries(presence)) { if (device === 'aggregated') { continue; } const age = dateNow / 1000 - devicePresence.timestamp; if (timestamp < devicePresence.timestamp) { timestamp = devicePresence.timestamp; } if (age < offlineThresholdSeconds) { if (presenceStatusGeq(devicePresence.status, status)) { client = device; status = devicePresence.status; } } } return { client, status, timestamp }; }; export function getUserLastActiveAsRelativeTimeString( state: PerAccountState, user: UserOrBot, dateNow: number, ): string | null { const presenceState = getPresence(state); const presence = getUserPresenceByEmail(presenceState, user.email); if (!presence) { return null; } if (!presence.aggregated) { return 'never'; } const lastTimeActive = new Date(presence.aggregated.timestamp * 1000); // "Invisible mode", new in FL 148, doesn't involve UserStatus['away']: // path_to_url#narrow/stream/2-general/topic/.22unavailable.22.20status/near/1454779 // TODO(server-6.0): Simplify this away. if ( getZulipFeatureLevel(state) < 148 && getUserStatus(state, user.user_id).away && differenceInDays(dateNow, lastTimeActive) < 1 ) { // Be vague when an unavailable user is recently online. // TODO: This phrasing doesn't really match the logic and can be misleading. return 'today'; } return differenceInSeconds(dateNow, lastTimeActive) < presenceState.offlineThresholdSeconds ? 'now' : `${formatDistanceToNow(lastTimeActive)} ago`; } export function getPresenceOnlyStatusForUser( state: PresenceState, user: UserOrBot, ): PresenceStatus | null { const userPresence = getUserPresenceByEmail(state, user.email); if (!userPresence || !userPresence.aggregated) { return null; } const { status, timestamp } = userPresence.aggregated; if (status === 'offline') { return 'offline'; } const timestampDate = new Date(timestamp * 1000); const diffToNowInSeconds = differenceInSeconds(Date.now(), timestampDate); if (diffToNowInSeconds > state.offlineThresholdSeconds) { return 'offline'; } return status; } /** * Get a user's overall presence status, aggregated from all their devices. * * Gives null when we're missing data to determine this, such as when the * user doesn't exist. */ export const getPresenceStatusForUserId = ( state: PerAccountState, userId: UserId, ): PresenceStatus | 'unavailable' | null => { // TODO(server-6.0): Cut this; UserStatus['away'] was replaced by "invisible mode". // path_to_url#narrow/stream/2-general/topic/.22unavailable.22.20status/near/1454779 if (getZulipFeatureLevel(state) < 148 && getUserStatus(state, userId).away) { return 'unavailable'; } const presence = getPresence(state); const user = tryGetUserForId(state, userId); if (!user) { return null; } return getPresenceOnlyStatusForUser(presence, user); }; // // // Reducer. // const initialState: PresenceState = { pingIntervalSeconds: 60, offlineThresholdSeconds: 140, byEmail: Immutable.Map(), }; export function reducer( state: PresenceState = initialState, // eslint-disable-line default-param-last action: PerAccountApplicableAction, ): PresenceState { switch (action.type) { case RESET_ACCOUNT_DATA: return initialState; case REGISTER_COMPLETE: return { pingIntervalSeconds: action.data.server_presence_ping_interval_seconds ?? 60, offlineThresholdSeconds: action.data.server_presence_offline_threshold_seconds ?? 140, byEmail: Immutable.Map(action.data.presences), }; case PRESENCE_RESPONSE: return { ...state, byEmail: state.byEmail.merge(action.presence), }; case EVENT_PRESENCE: { // A presence event should have either "active" or "idle" status const isPresenceEventValid = !!objectEntries(action.presence).find( ([device, devicePresence]) => ['active', 'idle'].includes(devicePresence.status), ); if (!isPresenceEventValid) { return state; } return { ...state, byEmail: state.byEmail.update(action.email, (userPresence: UserPresence): UserPresence => // $FlowIssue[cannot-spread-indexer] path_to_url ({ ...userPresence, ...action.presence, aggregated: getAggregatedPresence( // $FlowIssue[cannot-spread-indexer] path_to_url { ...userPresence, ...action.presence, }, state.offlineThresholdSeconds, ), }), ), }; } default: return state; } } ```
/content/code_sandbox/src/presence/presenceModel.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,884
```javascript /* @flow strict-local */ import deepFreeze from 'deep-freeze'; import Immutable from 'immutable'; import * as eg from '../../__tests__/lib/exampleData'; import { PRESENCE_RESPONSE, EVENT_PRESENCE } from '../../actionConstants'; import { reducer as presenceReducer, getAggregatedPresence, getUserLastActiveAsRelativeTimeString, getPresenceStatusForUserId, getPresenceOnlyStatusForUser, } from '../presenceModel'; import { makePresenceState } from './presence-testlib'; import type { UserPresence, UserStatus } from '../../api/modelTypes'; import type { PerAccountState } from '../../reduxTypes'; const currentTimestamp = Date.now() / 1000; // TODO test offlineThresholdSeconds varying const offlineThresholdSeconds = 140; describe('getAggregatedPresence', () => { const oldAggregatedClientPresence = { client: 'website', timestamp: currentTimestamp - 10000, status: 'active', }; test('aggregated status is active if any of the client has status active with age less than threshold', () => { expect( getAggregatedPresence( { website: { client: 'website', timestamp: currentTimestamp - 100, status: 'idle' }, zulipMobile: { client: 'zulipMobile', timestamp: currentTimestamp - 120, status: 'active', }, aggregated: oldAggregatedClientPresence, }, offlineThresholdSeconds, ), ).toEqual({ client: 'zulipMobile', status: 'active', timestamp: currentTimestamp - 100, }); }); test('aggregated status is idle if any of the client has status idle with age less than threshold and no client has status active with age has than threshold', () => { expect( getAggregatedPresence( { website: { client: 'website', timestamp: currentTimestamp - 100, status: 'idle' }, zulipMobile: { client: 'zulipMobile', timestamp: currentTimestamp - 220, status: 'active', }, aggregated: oldAggregatedClientPresence, }, offlineThresholdSeconds, ), ).toEqual({ client: 'website', status: 'idle', timestamp: currentTimestamp - 100 }); }); test('aggregated status is offline if no client has status active or idle with age less than threshold', () => { expect( getAggregatedPresence( { zulipMobile: { client: 'zulipMobile', timestamp: currentTimestamp - 400, status: 'active', }, website: { client: 'website', timestamp: currentTimestamp - 200, status: 'idle' }, zulipAndroid: { client: 'zulipAndroid', timestamp: currentTimestamp - 500, status: 'active', }, aggregated: oldAggregatedClientPresence, }, offlineThresholdSeconds, ), ).toEqual({ client: '', timestamp: currentTimestamp - 200, status: 'offline' }); }); test('do not consider presence if its age is greater than offline threshold', () => { expect( getAggregatedPresence( { website: { client: 'website', timestamp: currentTimestamp - 300, status: 'active' }, zulipMobile: { client: 'zulipMobile', timestamp: currentTimestamp - 10, status: 'idle' }, aggregated: oldAggregatedClientPresence, }, offlineThresholdSeconds, ), ).toEqual({ client: 'zulipMobile', status: 'idle', timestamp: currentTimestamp - 10, }); }); test('Use specified offline threshold', () => { expect( getAggregatedPresence( { website: { client: 'website', timestamp: currentTimestamp - 300, status: 'active' }, zulipMobile: { client: 'zulipMobile', timestamp: currentTimestamp - 10, status: 'idle' }, aggregated: oldAggregatedClientPresence, }, 360, ), ).toEqual({ client: 'website', status: 'active', timestamp: currentTimestamp - 10, }); }); test('Do not consider old aggregated', () => { expect( getAggregatedPresence( { aggregated: { client: 'website', status: 'active', timestamp: currentTimestamp - 100 }, website: { client: 'website', status: 'idle', timestamp: currentTimestamp - 10 }, }, offlineThresholdSeconds, ), ).toEqual({ client: 'website', status: 'idle', timestamp: currentTimestamp - 10 }); }); }); describe('getUserLastActiveAsRelativeTimeString', () => { function lastActiveString(args: { userPresence: UserPresence, userStatus: UserStatus, zulipFeatureLevel?: number, offlineThresholdSeconds?: number, }): string | null { const { userPresence, userStatus, zulipFeatureLevel = eg.recentZulipFeatureLevel, offlineThresholdSeconds, // eslint-disable-line no-shadow } = args; return getUserLastActiveAsRelativeTimeString( eg.reduxStatePlus({ presence: makePresenceState([[eg.otherUser, userPresence]], { offlineThresholdSeconds }), userStatuses: Immutable.Map([[eg.otherUser.user_id, userStatus]]), accounts: [{ ...eg.plusReduxState.accounts[0], zulipFeatureLevel }], }), eg.otherUser, currentTimestamp * 1000, ); } test('a recent time', () => { const userPresence = { aggregated: { client: 'website', status: 'active', timestamp: currentTimestamp - 240 }, }; const userStatus = { away: false, status_text: null, status_emoji: null }; expect(lastActiveString({ userPresence, userStatus })).toBe('4 minutes ago'); }); test('if less than a threshold, the user is currently active', () => { const userPresence = { aggregated: { client: 'website', status: 'active', timestamp: currentTimestamp - 100 }, }; const userStatus = { away: false, status_text: null, status_emoji: null }; expect(lastActiveString({ userPresence, userStatus })).toBe('now'); }); test('Use specified offline threshold', () => { const userPresence = { aggregated: { client: 'website', status: 'active', timestamp: currentTimestamp - 100 }, }; const userStatus = { away: false, status_text: null, status_emoji: null }; expect(lastActiveString({ userPresence, userStatus, offlineThresholdSeconds: 80 })).toBe( '2 minutes ago', ); }); // TODO(server-6.0): Remove test('Pre-FL 148: if less than a day and user is "away", use imprecise "today"', () => { const userPresence = { aggregated: { client: 'website', status: 'active', timestamp: currentTimestamp - 100 }, }; const userStatus = { away: true, status_text: null, status_emoji: null }; const zulipFeatureLevel = 147; expect(lastActiveString({ userPresence, userStatus, zulipFeatureLevel })).toBe('today'); }); // TODO(server-6.0): Remove, once this test case is redundant with those // above after the status parameter is gone. test('FL 148: if less than a day and user is "away", *don\'t* use imprecise "today"', () => { const userPresence = { aggregated: { client: 'website', status: 'active', timestamp: currentTimestamp - 100 }, }; const userStatus = { away: true, status_text: null, status_emoji: null }; const zulipFeatureLevel = 148; expect(lastActiveString({ userPresence, userStatus, zulipFeatureLevel })).not.toBe('today'); }); }); describe('getPresenceOnlyStatusForUser', () => { test('if aggregate status is "offline" the result is always "offline"', () => { const userPresence = { aggregated: { client: 'website', status: 'offline', timestamp: currentTimestamp - 100 }, }; expect( getPresenceOnlyStatusForUser(makePresenceState([[eg.otherUser, userPresence]]), eg.otherUser), ).toBe('offline'); }); test('if status is not "offline" but last activity was more than 1hr ago result is still "offline"', () => { const userPresence = { aggregated: { client: 'website', status: 'active', timestamp: Math.trunc(Date.now() / 1000 - 2 * 60 * 60), // two hours }, }; expect( getPresenceOnlyStatusForUser(makePresenceState([[eg.otherUser, userPresence]]), eg.otherUser), ).toBe('offline'); }); test('if status is "idle" and last activity is less than 140 seconds then result remain "idle"', () => { const userPresence = { aggregated: { client: 'website', status: 'idle', timestamp: Math.trunc(Date.now() / 1000 - 60), // 1 minute }, }; expect( getPresenceOnlyStatusForUser(makePresenceState([[eg.otherUser, userPresence]]), eg.otherUser), ).toBe('idle'); }); test('Use specified offline threshold', () => { const userPresence = { aggregated: { client: 'website', status: 'idle', timestamp: Math.trunc(Date.now() / 1000 - 60), // 1 minute }, }; expect( getPresenceOnlyStatusForUser( makePresenceState([[eg.otherUser, userPresence]], { offlineThresholdSeconds: 40 }), eg.otherUser, ), ).toBe('offline'); }); test('if status is not "offline" and last activity was less than 5min ago result is "active"', () => { const userPresence = { aggregated: { client: 'website', status: 'active', timestamp: Math.trunc(Date.now() / 1000 - 60), // 1 minute }, }; expect( getPresenceOnlyStatusForUser(makePresenceState([[eg.otherUser, userPresence]]), eg.otherUser), ).toBe('active'); }); }); describe('getPresenceStatusForUserId, server < FL 148', () => { function makeState(args: { userPresence: UserPresence, userStatus: UserStatus, zulipFeatureLevel?: number, }): PerAccountState { const { userPresence, userStatus, zulipFeatureLevel = eg.recentZulipFeatureLevel } = args; return eg.reduxStatePlus({ presence: makePresenceState([[eg.otherUser, userPresence]]), userStatuses: Immutable.Map([[eg.otherUser.user_id, userStatus]]), accounts: [{ ...eg.plusReduxState.accounts[0], zulipFeatureLevel }], }); } test('if `userPresence` is provided but `away` is false do not change', () => { const state = makeState({ userPresence: { aggregated: { client: 'website', status: 'active', timestamp: currentTimestamp - 100 }, }, userStatus: { away: false, status_text: 'Hello, world!', status_emoji: null }, zulipFeatureLevel: 147, }); expect(getPresenceStatusForUserId(state, eg.otherUser.user_id)).toBe('active'); }); test('if `userPresence` is provided and `away` is `true` override status with "unavailable"', () => { const state = makeState({ userPresence: { aggregated: { client: 'website', status: 'active', timestamp: currentTimestamp - 100 }, }, userStatus: { away: true, status_text: null, status_emoji: null }, zulipFeatureLevel: 147, }); expect(getPresenceStatusForUserId(state, eg.otherUser.user_id)).toBe('unavailable'); }); }); describe('presenceReducer', () => { describe('REGISTER_COMPLETE', () => { test('when `presence` data is provided init state with it', () => { const user = eg.otherUser; const userPresence = { aggregated: { client: 'website', status: 'active', timestamp: 123 }, website: { client: 'website', status: 'active', timestamp: 123 }, }; const prevState = deepFreeze(eg.baseReduxState.presence); const action = eg.mkActionRegisterComplete({ presences: { [user.email]: userPresence }, }); const expectedState = makePresenceState([[user, userPresence]]); expect(presenceReducer(prevState, action)).toEqual(expectedState); }); }); describe('PRESENCE_RESPONSE', () => { test('merges a single user in presence response', () => { const user = eg.otherUser; const userPresence1 = { aggregated: { status: 'active', timestamp: 8, client: 'zulipMobile' }, zulipMobile: { status: 'active', timestamp: 8, client: 'zulipMobile' }, }; const userPresence2 = { aggregated: { status: 'active', timestamp: 123, client: 'website' }, website: { status: 'active', timestamp: 123, client: 'website' }, }; const prevState = makePresenceState([[user, userPresence1]]); const action = deepFreeze({ type: PRESENCE_RESPONSE, presence: { [user.email]: userPresence2 }, serverTimestamp: 1474527537, }); const expectedState = makePresenceState([[user, userPresence2]]); expect(presenceReducer(prevState, action)).toEqual(expectedState); }); test('merges multiple users in presence response', () => { const [user1, user2, user3] = [eg.makeUser(), eg.otherUser, eg.thirdUser]; const presence1a = { aggregated: { status: 'active', timestamp: 8, client: 'zulipMobile' }, zulipMobile: { status: 'active', timestamp: 8, client: 'zulipMobile' }, }; const presence2 = { aggregated: { status: 'active', timestamp: 8, client: 'zulipMobile' }, zulipMobile: { status: 'active', timestamp: 8, client: 'zulipMobile' }, }; const presence1b = { aggregated: { client: 'website', status: 'active', timestamp: 123 }, website: { client: 'website', status: 'active', timestamp: 123 }, }; const presence3 = { aggregated: { status: 'active', timestamp: 345, client: 'website' }, website: { status: 'active', timestamp: 345, client: 'website' }, }; const prevState = makePresenceState([ [user1, presence1a], [user2, presence2], ]); const action = deepFreeze({ type: PRESENCE_RESPONSE, presence: { [user1.email]: presence1b, [user3.email]: presence3 }, serverTimestamp: 12345, }); const expectedState = makePresenceState([ [user1, presence1b], [user2, presence2], [user3, presence3], ]); expect(presenceReducer(prevState, action)).toEqual(expectedState); }); }); describe('EVENT_PRESENCE', () => { test('merges a single user presence', () => { const user = eg.otherUser; const clientPresence1 = { client: 'website', status: 'idle', timestamp: currentTimestamp - 20, }; const clientPresence2 = { client: 'zulipMobile', status: 'active', timestamp: currentTimestamp - 10, }; const prevState = makePresenceState([ [user, { aggregated: clientPresence1, website: clientPresence1 }], ]); const action = deepFreeze({ id: 1, type: EVENT_PRESENCE, email: user.email, server_timestamp: 200, presence: { zulipMobile: clientPresence2 }, }); const expectedState = makePresenceState([ [ user, { aggregated: clientPresence2, website: clientPresence1, zulipMobile: clientPresence2 }, ], ]); expect(presenceReducer(prevState, action)).toEqual(expectedState); }); }); describe('RESET_ACCOUNT_DATA', () => { test('resets state to initial state', () => { const user = eg.otherUser; const userPresence = { aggregated: { status: 'active', timestamp: 8, client: 'zulipMobile' }, zulipMobile: { status: 'active', timestamp: 8, client: 'zulipMobile' }, }; const prevState = makePresenceState([[user, userPresence]]); const action = eg.action.reset_account_data; const expectedState = makePresenceState([]); expect(presenceReducer(prevState, action)).toEqual(expectedState); }); }); }); ```
/content/code_sandbox/src/presence/__tests__/presenceModel-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
3,799
```javascript // @flow strict-local import Heartbeat from '../heartbeat'; // (hopefully) restrictive type alias for Jest's mock callback functions type CallbackType = JestMockFn<$ReadOnlyArray<void>, void>; describe('Heartbeat', () => { // =================================================================== // Constants and conveniences // arbitrarily, one full hour between heartbeats const HEARTBEAT_TIME = 60 * 60 * 1000; /** * Wrapper class for Heartbeat. * * Since Heartbeat erases its callback type (and `callback` should be private * anyway!), it's inconvenient to access the Jest mock functionality of * Heartbeat's callback. This wrapper provides fully-typed access to the * callback. * * As a convenience, we also keep track of the current set of Heartbeats used * by test cases. */ class JestHeartbeatHelper { callback: CallbackType; heartbeat: Heartbeat; // eslint-disable-next-line no-use-before-define static _currentHeartbeats: Array<JestHeartbeatHelper> = []; constructor() { this.callback = jest.fn(); this.heartbeat = new Heartbeat(this.callback, HEARTBEAT_TIME); // eslint-disable-next-line no-underscore-dangle JestHeartbeatHelper._currentHeartbeats.push(this); } start() { this.heartbeat.start(); } stop() { this.heartbeat.stop(); } isActive(): boolean { return this.heartbeat.isActive(); } static getExtant(): $ReadOnlyArray<JestHeartbeatHelper> { return this._currentHeartbeats; } static clearExtant() { this._currentHeartbeats = []; } } // convenience function: create a new Heartbeat with its associated callback const setup = (): {| callback: CallbackType, heartbeat: JestHeartbeatHelper, |} => { const heartbeat = new JestHeartbeatHelper(); const { callback } = heartbeat; return { heartbeat, callback }; }; /** * Check that the supplied heartbeat is running, and confirm that it continues * to run for at least `count` cycles. */ const expectRunning = (heartbeat: JestHeartbeatHelper, count: number = 10) => { const { callback } = heartbeat; for (let i = 0; i < count; ++i) { callback.mockClear(); jest.runOnlyPendingTimers(); expect(callback).toHaveBeenCalled(); } callback.mockClear(); }; /** Check that the supplied heartbeat is not running. */ const expectNotRunning = (heartbeat: JestHeartbeatHelper) => { const { callback } = heartbeat; callback.mockClear(); jest.runOnlyPendingTimers(); expect(callback).not.toHaveBeenCalled(); jest.advanceTimersByTime(HEARTBEAT_TIME * 10); expect(callback).not.toHaveBeenCalled(); }; // =================================================================== // Jest hooks afterAll(() => { JestHeartbeatHelper.clearExtant(); }); // before each test: reset common state beforeEach(() => { jest.clearAllTimers(); JestHeartbeatHelper.clearExtant(); }); // after each test: confirm common properties afterEach(() => { const heartbeats = JestHeartbeatHelper.getExtant(); for (const heartbeat of heartbeats) { // Tests should stop all their Heartbeats. expect(heartbeat.isActive()).toBeFalse(); heartbeat.callback.mockClear(); } // Stopped heartbeats may have timers running, but those timers should not // persist beyond their next firing... jest.runOnlyPendingTimers(); expect(jest.getTimerCount()).toBe(0); // ... and none of those _timer_ firings should result in a _callback_ // firing. for (const heartbeat of heartbeats) { expect(heartbeat.callback).not.toHaveBeenCalled(); } }); // =================================================================== // Test cases test('starts inactive', () => { const { heartbeat, callback } = setup(); expect(heartbeat.isActive()).toBeFalse(); expect(callback).not.toHaveBeenCalled(); expectNotRunning(heartbeat); }); test('can be turned on and off', () => { const { heartbeat, callback } = setup(); expect(callback).not.toHaveBeenCalled(); heartbeat.start(); expect(callback).toHaveBeenCalled(); expectRunning(heartbeat); heartbeat.stop(); expect(callback).not.toHaveBeenCalled(); expectNotRunning(heartbeat); }); test('can be turned on and off repeatedly without signal', () => { const { heartbeat, callback } = setup(); heartbeat.start(); for (let i = 0; i < 10; ++i) { callback.mockClear(); heartbeat.stop(); expect(callback).not.toHaveBeenCalled(); callback.mockClear(); heartbeat.start(); expect(callback).not.toHaveBeenCalled(); } heartbeat.stop(); }); test('can be turned on and off repeatedly _with_ signal', () => { const { heartbeat, callback } = setup(); heartbeat.start(); for (let i = 0; i < 10; ++i) { callback.mockClear(); heartbeat.stop(); expect(callback).not.toHaveBeenCalled(); // delay past HEARTBEAT_TIME callback.mockClear(); jest.advanceTimersByTime(HEARTBEAT_TIME * 1.1); expect(callback).not.toHaveBeenCalled(); callback.mockClear(); heartbeat.start(); expect(callback).toHaveBeenCalled(); expect(callback).toHaveBeenCalledTimes(1); } heartbeat.stop(); }); test('can be turned off and on without delaying the signal', () => { const { heartbeat, callback } = setup(); heartbeat.start(); callback.mockClear(); // Late in interval, stop and start again. jest.advanceTimersByTime(HEARTBEAT_TIME * 0.8); heartbeat.stop(); jest.advanceTimersByTime(HEARTBEAT_TIME * 0.1); heartbeat.start(); // No signal yet... expect(callback).not.toHaveBeenCalled(); // ... but signal promptly at end of original interval. jest.advanceTimersByTime(HEARTBEAT_TIME * 0.101); expect(callback).toHaveBeenCalled(); heartbeat.stop(); }); test('takes about the right amount of time', () => { const { heartbeat, callback } = setup(); expect(callback).not.toHaveBeenCalled(); heartbeat.start(); expect(callback).toHaveBeenCalled(); callback.mockClear(); for (let i = 0; i < 10; ++i) { jest.advanceTimersByTime(HEARTBEAT_TIME * 1.001); expect(callback).toHaveBeenCalled(); expect(callback).toHaveBeenCalledTimes(1); callback.mockClear(); } heartbeat.stop(); expect(callback).not.toHaveBeenCalled(); }); test('has idempotent stop()', () => { const { heartbeat, callback } = setup(); expect(callback).not.toHaveBeenCalled(); heartbeat.stop(); expect(callback).not.toHaveBeenCalled(); expectNotRunning(heartbeat); heartbeat.stop(); expect(callback).not.toHaveBeenCalled(); expectNotRunning(heartbeat); }); test('has idempotent start()', () => { const { heartbeat, callback } = setup(); expect(callback).not.toHaveBeenCalled(); heartbeat.start(); expect(callback).toHaveBeenCalled(); expectRunning(heartbeat, 3); jest.advanceTimersByTime(HEARTBEAT_TIME * 0.25); expect(callback).not.toHaveBeenCalled(); heartbeat.start(); expect(callback).not.toHaveBeenCalled(); // sic! jest.advanceTimersByTime(HEARTBEAT_TIME * 0.76); expect(callback).toHaveBeenCalled(); heartbeat.stop(); }); }); ```
/content/code_sandbox/src/presence/__tests__/heartbeat-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,689
```javascript // @flow strict-local import type { User, UserPresence } from '../../api/modelTypes'; import { type PresenceState } from '../../reduxTypes'; import { reducer } from '../presenceModel'; import * as eg from '../../__tests__/lib/exampleData'; import { objectFromEntries } from '../../jsBackport'; export function makePresenceState( data: $ReadOnlyArray<[User, UserPresence]>, args?: {| +offlineThresholdSeconds?: number, +pingIntervalSeconds?: number, |}, ): PresenceState { const { offlineThresholdSeconds, pingIntervalSeconds } = args ?? {}; return reducer( undefined, eg.mkActionRegisterComplete({ presences: objectFromEntries(data.map(([user, presence]) => [user.email, presence])), server_presence_offline_threshold_seconds: offlineThresholdSeconds ?? 140, server_presence_ping_interval_seconds: pingIntervalSeconds ?? 60, }), ); } ```
/content/code_sandbox/src/presence/__tests__/presence-testlib.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
197
```javascript /* @flow strict-local */ import invariant from 'invariant'; import type { PerAccountApplicableAction, PerAccountState } from '../types'; import type { UnreadPmsState } from './unreadModelTypes'; import { REGISTER_COMPLETE, EVENT_NEW_MESSAGE, EVENT_MESSAGE_DELETE, EVENT_UPDATE_MESSAGE_FLAGS, RESET_ACCOUNT_DATA, } from '../actionConstants'; import { addItemsToPmArray, removeItemsDeeply } from './unreadHelpers'; import { NULL_ARRAY } from '../nullObjects'; import { recipientsOfPrivateMessage } from '../utils/recipient'; import * as logging from '../utils/logging'; import { getOwnUserId } from '../users/userSelectors'; const initialState: UnreadPmsState = NULL_ARRAY; const eventNewMessage = (state, action) => { if (action.message.type !== 'private') { return state; } if (recipientsOfPrivateMessage(action.message).length > 2) { return state; } invariant(action.message.flags, 'message in EVENT_NEW_MESSAGE must have flags'); if (action.message.flags.includes('read')) { return state; } return addItemsToPmArray(state, [action.message.id], action.message.sender_id); }; const eventUpdateMessageFlags = (state, action, ownUserId) => { if (action.flag !== 'read') { return state; } if (action.all) { return initialState; } if (action.op === 'add') { return removeItemsDeeply(state, action.messages); } else if (action.op === 'remove') { const { message_details } = action; if (message_details === undefined) { logging.warn('Got update_message_flags/remove/read event without message_details.'); return state; } let newState = state; for (const id of action.messages) { const message = message_details.get(id); if (message && message.type === 'private') { // This logic corresponds to pmUnreadsKeyFromOtherUsers, except that // the latter returns a string (for the sake of group PMs) and our // data structure here wants a UserId. if (message.user_ids.length === 1) { newState = addItemsToPmArray(newState, [id], message.user_ids[0]); } else if (message.user_ids.length === 0) { newState = addItemsToPmArray(newState, [id], ownUserId); } } } // TODO This re-sorting/deduping is pretty overkill; only the // conversations we actually touched need it. But rather than add // complications to the `addItemsTo` system to support that, let's // spend that effort instead to finally rip that system out in favor // of Immutable.js. return newState.map(({ sender_id, unread_message_ids }) => ({ sender_id, unread_message_ids: [...new Set(unread_message_ids)].sort((a, b) => a - b), })); } return state; }; export default ( state: UnreadPmsState = initialState, // eslint-disable-line default-param-last action: PerAccountApplicableAction, globalState: PerAccountState, ): UnreadPmsState => { switch (action.type) { case RESET_ACCOUNT_DATA: return initialState; case REGISTER_COMPLETE: return action.data.unread_msgs.pms; case EVENT_NEW_MESSAGE: return eventNewMessage(state, action); case EVENT_MESSAGE_DELETE: return removeItemsDeeply(state, action.messageIds); case EVENT_UPDATE_MESSAGE_FLAGS: return eventUpdateMessageFlags(state, action, getOwnUserId(globalState)); default: return state; } }; ```
/content/code_sandbox/src/unread/unreadPmsReducer.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
801
```javascript /* @flow strict-local */ import Immutable from 'immutable'; import invariant from 'invariant'; import type { Narrow, UserId } from '../types'; import { userIdsOfPmNarrow } from '../utils/narrow'; import { pmUnreadsKeyFromPmKeyIds } from '../utils/recipient'; import type { PerAccountApplicableAction } from '../actionTypes'; import type { UnreadState, UnreadStreamsState, UnreadPmsState, UnreadHuddlesState, UnreadMentionsState, } from './unreadModelTypes'; import type { PerAccountState } from '../reduxTypes'; import unreadPmsReducer from './unreadPmsReducer'; import unreadHuddlesReducer from './unreadHuddlesReducer'; import unreadMentionsReducer from './unreadMentionsReducer'; import { EVENT_MESSAGE_DELETE, EVENT_NEW_MESSAGE, EVENT_UPDATE_MESSAGE, EVENT_UPDATE_MESSAGE_FLAGS, MESSAGE_FETCH_COMPLETE, REGISTER_COMPLETE, RESET_ACCOUNT_DATA, } from '../actionConstants'; import DefaultMap from '../utils/DefaultMap'; import * as logging from '../utils/logging'; import { updateAllAndPrune, updateAndPrune, setUnion } from '../immutableUtils'; // // // Selectors. // // These take the global state as their input. // /** The unread-messages state as a whole. */ export const getUnread = (state: PerAccountState): UnreadState => state.unread; export const getUnreadStreams = (state: PerAccountState): UnreadStreamsState => state.unread.streams; export const getUnreadPms = (state: PerAccountState): UnreadPmsState => state.unread.pms; export const getUnreadHuddles = (state: PerAccountState): UnreadHuddlesState => state.unread.huddles; export const getUnreadMentions = (state: PerAccountState): UnreadMentionsState => state.unread.mentions; // // // Getters. // // These operate directly on this particular model's state, as part of this // model's own interface. // /** The total number of unreads in the given topic. */ export const getUnreadCountForTopic = ( unread: UnreadState, streamId: number, topic: string, ): number => unread.streams.get(streamId)?.get(topic)?.size ?? 0; /** All the unread message IDs for a given PM narrow. */ export const getUnreadIdsForPmNarrow = ( unread: UnreadState, narrow: Narrow, ownUserId: UserId, ): $ReadOnlyArray<number> => { const userIds = userIdsOfPmNarrow(narrow); if (userIds.length > 1) { const unreadsKey = pmUnreadsKeyFromPmKeyIds(userIds, ownUserId); const unreadItem = unread.huddles.find(x => x.user_ids_string === unreadsKey); return unreadItem?.unread_message_ids ?? []; } else { const senderId = userIds[0]; const unreadItem = unread.pms.find(x => x.sender_id === senderId); return unreadItem?.unread_message_ids ?? []; } }; // // // Reducer. // const initialStreamsState: UnreadStreamsState = Immutable.Map(); function deleteMessagesIn( state: UnreadStreamsState, streamId: number, topic: string, ids: Set<number>, ): UnreadStreamsState { return updateAndPrune(state, Immutable.Map(), streamId, (perStream = Immutable.Map()) => updateAndPrune(perStream, Immutable.List(), topic, (perTopic = Immutable.List()) => perTopic.filter(id => !ids.has(id)), ), ); } function deleteMessages( state: UnreadStreamsState, ids: $ReadOnlyArray<number>, ): UnreadStreamsState { const idSet = new Set(ids); const toDelete = id => idSet.has(id); const emptyList: Immutable.List<number> = Immutable.List(); return updateAllAndPrune(state, Immutable.Map(), perStream => updateAllAndPrune(perStream, emptyList, (perTopic: Immutable.List<number>) => perTopic.find(toDelete) ? perTopic.filterNot(toDelete) : perTopic, ), ); } function streamsReducer( state: UnreadStreamsState = initialStreamsState, // eslint-disable-line default-param-last action: PerAccountApplicableAction, globalState: PerAccountState, ): UnreadStreamsState { switch (action.type) { case RESET_ACCOUNT_DATA: return initialStreamsState; case REGISTER_COMPLETE: { const data = action.data.unread_msgs.streams; // First, collect together all the data for a given stream, just in a // plain old Array. const byStream = new DefaultMap(() => []); for (const { stream_id, topic, unread_message_ids } of data) { // unread_message_ids is already sorted; see comment at its // definition in src/api/initialDataTypes.js. byStream.getOrCreate(stream_id).push([topic, Immutable.List(unread_message_ids)]); } // Then, for each of those plain Arrays build an Immutable.Map from it // all in one shot. This is quite a bit faster than building the Maps // incrementally. For a user with lots of unreads in a busy org, we // can be handling 50k message IDs here, across perhaps 2-5k threads // in dozens of streams, so the effect is significant. return Immutable.Map(Immutable.Seq.Keyed(byStream.map.entries()).map(Immutable.Map)); } case MESSAGE_FETCH_COMPLETE: // TODO handle MESSAGE_FETCH_COMPLETE here. This rarely matters, but // could in principle: we could be fetching some messages from // before the (long) window included in the initial unreads data. // For comparison, the webapp does handle this case; see the call to // message_util.do_unread_count_updates in message_fetch.js. return state; case EVENT_NEW_MESSAGE: { const { message } = action; if (message.type !== 'stream') { return state; } invariant(message.flags, 'message in EVENT_NEW_MESSAGE must have flags'); if (message.flags.includes('read')) { return state; } // prettier-ignore return state.updateIn([message.stream_id, message.subject], (perTopic = Immutable.List()) => perTopic.push(message.id)); } case EVENT_MESSAGE_DELETE: // TODO optimize by looking up directly; see #4684 return deleteMessages(state, action.messageIds); case EVENT_UPDATE_MESSAGE_FLAGS: { if (action.flag !== 'read') { return state; } if (action.all) { return initialStreamsState; } if (action.op === 'remove') { const { message_details } = action; if (message_details === undefined) { logging.warn('Got update_message_flags/remove/read event without message_details.'); return state; } let newlyUnreadState: Immutable.Map< number, Immutable.Map<string, Immutable.List<number>>, > = Immutable.Map(); for (const id of action.messages) { const message = message_details.get(id); // The server should ensure that all messages sent are in // message_details, so the first `message` here is defensive. if (message && message.type === 'stream') { newlyUnreadState = newlyUnreadState.updateIn( [message.stream_id, message.topic], Immutable.List(), messages => messages.push(id), ); } } // We rely in `setUnion` below on these being sorted. Even if we // didn't, and sorted there, it wouldn't catch topics that are in // newlyUnreadState but not the existing state (because `mergeWith` // would use those verbatim). So sort here. newlyUnreadState = newlyUnreadState.map(e => e.map(messages => messages.sort())); return state.mergeWith( (oldTopicsMap, newTopicsMap) => oldTopicsMap.mergeWith( (oldUnreadMessages, newUnreadMessages) => setUnion(oldUnreadMessages, newUnreadMessages), newTopicsMap, ), newlyUnreadState, ); } // TODO optimize by looking up directly; see #4684. // Then when do, also optimize so deleting the oldest items is fast, // as that should be the common case here. return deleteMessages(state, action.messages); } case EVENT_UPDATE_MESSAGE: { const { event, move } = action; if (!move) { return state; } const eventIds = new Set(event.message_ids); const matchingIds = state .getIn([move.orig_stream_id, move.orig_topic], Immutable.List()) .filter(id => eventIds.has(id)); if (matchingIds.size === 0) { // None of the updated messages were unread. return state; } return deleteMessagesIn(state, move.orig_stream_id, move.orig_topic, eventIds).updateIn( [move.new_stream_id, move.new_topic], (messages = Immutable.List()) => messages.push(...matchingIds).sort(), ); } default: return state; } } export const reducer = ( state: void | UnreadState, action: PerAccountApplicableAction, globalState: PerAccountState, ): UnreadState => { const nextState = { streams: streamsReducer(state?.streams, action, globalState), // Note for converting these other sub-reducers to the new design: // Probably first push this four-part data structure down through the // `switch` statement, and the other logic that's duplicated between them. pms: unreadPmsReducer(state?.pms, action, globalState), huddles: unreadHuddlesReducer(state?.huddles, action, globalState), mentions: unreadMentionsReducer(state?.mentions, action), }; if (state && Object.keys(nextState).every(key => nextState[key] === state[key])) { return state; } return nextState; }; ```
/content/code_sandbox/src/unread/unreadModel.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
2,207
```unknown // Jest Snapshot v1, path_to_url exports[`getEditSequence correct for interesting changes DM recipient headers enableGuestUserIndicator turns on, affecting a recipient user 1`] = `3`; exports[`getEditSequence correct for interesting changes DM recipient headers recipient user became guest 1`] = `1`; exports[`getEditSequence correct for interesting changes DM recipient headers recipient user's name changed 1`] = `1`; exports[`getEditSequence correct for interesting changes from empty to empty 1`] = `0`; exports[`getEditSequence correct for interesting changes from empty to many messages 1`] = `40`; exports[`getEditSequence correct for interesting changes from empty to one message 1`] = `3`; exports[`getEditSequence correct for interesting changes from many messages delete many messages in middle 1`] = `12`; exports[`getEditSequence correct for interesting changes from many messages delete one message at end 1`] = `2`; exports[`getEditSequence correct for interesting changes from many messages delete one message at start 1`] = `6`; exports[`getEditSequence correct for interesting changes from many messages insert many messages at end 1`] = `20`; exports[`getEditSequence correct for interesting changes from many messages insert many messages at start 1`] = `24`; exports[`getEditSequence correct for interesting changes from many messages insert many messages at start and end 1`] = `32`; exports[`getEditSequence correct for interesting changes from many messages insert one message at end 1`] = `2`; exports[`getEditSequence correct for interesting changes from many messages insert one message at start 1`] = `6`; exports[`getEditSequence correct for interesting changes from many messages replace one message at end with new content 1`] = `2`; exports[`getEditSequence correct for interesting changes from many messages replace one message at start with new content 1`] = `3`; exports[`getEditSequence correct for interesting changes from many messages replace one message in middle with new content 1`] = `3`; exports[`getEditSequence correct for interesting changes from many messages to disjoint set of many earlier messages 1`] = `42`; exports[`getEditSequence correct for interesting changes from many messages to disjoint set of many later messages 1`] = `42`; exports[`getEditSequence correct for interesting changes from many messages to empty 1`] = `40`; exports[`getEditSequence correct for interesting changes within a given message add reactions to a message 1`] = `3`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: none -> none (no change) 1`] = `0`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: none -> realm 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: none -> unicode 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: none -> zulip extra 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: realm -> none 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: realm -> realm (no change) 1`] = `0`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: realm -> unicode 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: realm -> zulip extra 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: unicode -> none 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: unicode -> realm 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: unicode -> unicode (no change) 1`] = `0`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: unicode -> zulip extra 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: zulip extra -> none 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: zulip extra -> realm 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: zulip extra -> unicode 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message add/remove/change emoji status status emoji: zulip extra -> zulip extra (no change) 1`] = `0`; exports[`getEditSequence correct for interesting changes within a given message enableGuestUserIndicator turns on, and sender is guest 1`] = `3`; exports[`getEditSequence correct for interesting changes within a given message follow a topic 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message mute a sender 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message polls choice added 1`] = `3`; exports[`getEditSequence correct for interesting changes within a given message polls vote added 1`] = `3`; exports[`getEditSequence correct for interesting changes within a given message remove reactions from a message 1`] = `3`; exports[`getEditSequence correct for interesting changes within a given message sender becomes guest 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message sender's name changed 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message star a message 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message unfollow a topic 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message unmute a sender 1`] = `1`; exports[`getEditSequence correct for interesting changes within a given message unstar a message 1`] = `1`; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1024\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1024\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Feb 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1024\\" data-msg-id=\\"1024\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-1598\\" data-msg-id=\\"1598\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 2`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"7938\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"7938\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-7938\\" data-msg-id=\\"7938\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8060\\" data-msg-id=\\"8060\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 3`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"4948\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"4948\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Feb 19, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-4948\\" data-msg-id=\\"4948\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"5083\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAy\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 2</div> <div class=\\"topic-date\\">Feb 19, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5083\\" data-msg-id=\\"5083\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 4`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"6789\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"6789\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-6789\\" data-msg-id=\\"6789\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"7727\\" data-narrow=\\"dG9waWM6Mjp0b3BpYyAy\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjI=\\"> # stream 2 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 2</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-7727\\" data-msg-id=\\"7727\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 5`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"9181\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"9181\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9181\\" data-msg-id=\\"9181\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"9815\\"> <div class=\\"timerow-left\\"></div> Mar 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9815\\" data-msg-id=\\"9815\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 6`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"8849\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"8849\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8849\\" data-msg-id=\\"8849\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-8917\\" data-msg-id=\\"8917\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 7`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5287\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"5287\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5287\\" data-msg-id=\\"5287\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5309\\" data-msg-id=\\"5309\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 8`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5829\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"5829\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5829\\" data-msg-id=\\"5829\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"5963\\"> <div class=\\"timerow-left\\"></div> Feb 26, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5963\\" data-msg-id=\\"5963\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 9`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5377\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwyLDM=\\" data-msg-id=\\"5377\\"> Nonrandom name one User, Nonrandom name three User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5377\\" data-msg-id=\\"5377\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-5620\\" data-msg-id=\\"5620\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 10`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5637\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwyLDM=\\" data-msg-id=\\"5637\\"> Nonrandom name one User, Nonrandom name three User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5637\\" data-msg-id=\\"5637\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5727\\" data-msg-id=\\"5727\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 11`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"2794\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwyLDM=\\" data-msg-id=\\"2794\\"> Nonrandom name one User, Nonrandom name three User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-2794\\" data-msg-id=\\"2794\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"4581\\"> <div class=\\"timerow-left\\"></div> Feb 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-4581\\" data-msg-id=\\"4581\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible HOME_NARROW 12`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1024\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1024\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Feb 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1024\\" data-msg-id=\\"1024\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-1598\\" data-msg-id=\\"1598\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwyLDM=\\" data-msg-id=\\"2794\\"> Nonrandom name one User, Nonrandom name three User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-2794\\" data-msg-id=\\"2794\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"4581\\"> <div class=\\"timerow-left\\"></div> Feb 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-4581\\" data-msg-id=\\"4581\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"4948\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"4948\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Feb 19, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-4948\\" data-msg-id=\\"4948\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"5083\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAy\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 2</div> <div class=\\"topic-date\\">Feb 19, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5083\\" data-msg-id=\\"5083\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"5287\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5287\\" data-msg-id=\\"5287\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5309\\" data-msg-id=\\"5309\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwyLDM=\\" data-msg-id=\\"5377\\"> Nonrandom name one User, Nonrandom name three User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5377\\" data-msg-id=\\"5377\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-5620\\" data-msg-id=\\"5620\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-5637\\" data-msg-id=\\"5637\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5727\\" data-msg-id=\\"5727\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"5829\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5829\\" data-msg-id=\\"5829\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"5963\\"> <div class=\\"timerow-left\\"></div> Feb 26, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5963\\" data-msg-id=\\"5963\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"6789\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"6789\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-6789\\" data-msg-id=\\"6789\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"7727\\" data-narrow=\\"dG9waWM6Mjp0b3BpYyAy\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjI=\\"> # stream 2 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 2</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-7727\\" data-msg-id=\\"7727\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"7938\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-7938\\" data-msg-id=\\"7938\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8060\\" data-msg-id=\\"8060\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"8849\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8849\\" data-msg-id=\\"8849\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-8917\\" data-msg-id=\\"8917\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"9181\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9181\\" data-msg-id=\\"9181\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"9815\\"> <div class=\\"timerow-left\\"></div> Mar 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9815\\" data-msg-id=\\"9815\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible all-pm 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"8849\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"8849\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8849\\" data-msg-id=\\"8849\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-8917\\" data-msg-id=\\"8917\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible all-pm 2`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5287\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"5287\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5287\\" data-msg-id=\\"5287\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5309\\" data-msg-id=\\"5309\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible all-pm 3`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5829\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"5829\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5829\\" data-msg-id=\\"5829\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"5963\\"> <div class=\\"timerow-left\\"></div> Feb 26, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5963\\" data-msg-id=\\"5963\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible all-pm 4`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5377\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwyLDM=\\" data-msg-id=\\"5377\\"> Nonrandom name one User, Nonrandom name three User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5377\\" data-msg-id=\\"5377\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-5620\\" data-msg-id=\\"5620\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible all-pm 5`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5637\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwyLDM=\\" data-msg-id=\\"5637\\"> Nonrandom name one User, Nonrandom name three User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5637\\" data-msg-id=\\"5637\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5727\\" data-msg-id=\\"5727\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible all-pm 6`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"2794\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwyLDM=\\" data-msg-id=\\"2794\\"> Nonrandom name one User, Nonrandom name three User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-2794\\" data-msg-id=\\"2794\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"4581\\"> <div class=\\"timerow-left\\"></div> Feb 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-4581\\" data-msg-id=\\"4581\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible all-pm 7`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"2794\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwyLDM=\\" data-msg-id=\\"2794\\"> Nonrandom name one User, Nonrandom name three User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-2794\\" data-msg-id=\\"2794\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"4581\\"> <div class=\\"timerow-left\\"></div> Feb 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-4581\\" data-msg-id=\\"4581\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"5287\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"5287\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5287\\" data-msg-id=\\"5287\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5309\\" data-msg-id=\\"5309\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwyLDM=\\" data-msg-id=\\"5377\\"> Nonrandom name one User, Nonrandom name three User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5377\\" data-msg-id=\\"5377\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-5620\\" data-msg-id=\\"5620\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-5637\\" data-msg-id=\\"5637\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5727\\" data-msg-id=\\"5727\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element header-wrapper private-header header\\" data-narrow=\\"cG06MSwy\\" data-msg-id=\\"5829\\"> Nonrandom name one User, Nonrandom name two User </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5829\\" data-msg-id=\\"5829\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"5963\\"> <div class=\\"timerow-left\\"></div> Feb 26, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5963\\" data-msg-id=\\"5963\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"8849\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8849\\" data-msg-id=\\"8849\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-8917\\" data-msg-id=\\"8917\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) guest sender, with enableGuestUserIndicator 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"{userFullName} (guest)\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> {userFullName} (guest) </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message in followed topic 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: white; background: #123456\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"true\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message in unsubscribed stream 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with a poll 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <div class=\\"poll-widget\\"> <p class=\\"poll-question\\">Choose a choice:</p> <ul> <li> <button class=\\"poll-vote\\" data-voted=\\"true\\" data-key=\\"10,1\\">3</button> <span class=\\"poll-option\\">Choice A</span> </li> <li> <button class=\\"poll-vote\\" data-voted=\\"false\\" data-key=\\"10,2\\">1</button> <span class=\\"poll-option\\">Choice B</span> </li> </ul> </div> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with flag: collapsed 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\" data-collapsed=\\"true\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with flag: has_alert_word 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\" data-has_alert_word=\\"true\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with flag: historical 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\" data-historical=\\"true\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with flag: mentioned 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\" data-mentioned=\\"true\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with flag: read 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\" data-read=\\"true\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with flag: starred 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\" data-starred=\\"true\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> <div class=\\"message-tags\\"><span class=\\"message-tag\\">starred</span></div> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with flag: wildcard_mentioned 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\" data-wildcard_mentioned=\\"true\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with reactions displayEmojiReactionUsers: false few reactions 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> <div class=\\"reaction-list\\"><span onclick=\\"\\" class=\\"reaction self-voted\\" data-name=\\"thumbs_up\\" data-code=\\"1f44d\\" data-type=\\"unicode_emoji\\">&nbsp;1</span></div> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with reactions displayEmojiReactionUsers: false many reactions 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> <div class=\\"reaction-list\\"><span onclick=\\"\\" class=\\"reaction\\" data-name=\\"github_parrot\\" data-code=\\"80\\" data-type=\\"realm_emoji\\"><img src=\\"path_to_url">&nbsp;2</span><span onclick=\\"\\" class=\\"reaction self-voted\\" data-name=\\"thumbs_up\\" data-code=\\"1f44d\\" data-type=\\"unicode_emoji\\">&nbsp;1</span><span onclick=\\"\\" class=\\"reaction self-voted\\" data-name=\\"zulip\\" data-code=\\"zulip\\" data-type=\\"zulip_extra_emoji\\"><img src=\\"path_to_url">&nbsp;1</span></div> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with reactions displayEmojiReactionUsers: true 3 votes on multiple emoji 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> <div class=\\"reaction-list\\"><span onclick=\\"\\" class=\\"reaction self-voted\\" data-name=\\"thumbs_up\\" data-code=\\"1f44d\\" data-type=\\"unicode_emoji\\">&nbsp;You</span><span onclick=\\"\\" class=\\"reaction self-voted\\" data-name=\\"zulip\\" data-code=\\"zulip\\" data-type=\\"zulip_extra_emoji\\"><img src=\\"path_to_url">&nbsp;You</span><span onclick=\\"\\" class=\\"reaction\\" data-name=\\"github_parrot\\" data-code=\\"80\\" data-type=\\"realm_emoji\\"><img src=\\"path_to_url">&nbsp;Nonrandom name other User</span></div> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with reactions displayEmojiReactionUsers: true 3 votes on same emoji 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> <div class=\\"reaction-list\\"><span onclick=\\"\\" class=\\"reaction self-voted\\" data-name=\\"thumbs_up\\" data-code=\\"1f44d\\" data-type=\\"unicode_emoji\\">&nbsp;You, Nonrandom name other User, Nonrandom name third User</span></div> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with reactions displayEmojiReactionUsers: true 4 votes on multiple emoji 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> <div class=\\"reaction-list\\"><span onclick=\\"\\" class=\\"reaction\\" data-name=\\"github_parrot\\" data-code=\\"80\\" data-type=\\"realm_emoji\\"><img src=\\"path_to_url">&nbsp;2</span><span onclick=\\"\\" class=\\"reaction self-voted\\" data-name=\\"thumbs_up\\" data-code=\\"1f44d\\" data-type=\\"unicode_emoji\\">&nbsp;1</span><span onclick=\\"\\" class=\\"reaction self-voted\\" data-name=\\"zulip\\" data-code=\\"zulip\\" data-type=\\"zulip_extra_emoji\\"><img src=\\"path_to_url">&nbsp;1</span></div> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with reactions displayEmojiReactionUsers: true 4 votes on same emoji 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> <div class=\\"reaction-list\\"><span onclick=\\"\\" class=\\"reaction self-voted\\" data-name=\\"thumbs_up\\" data-code=\\"1f44d\\" data-type=\\"unicode_emoji\\">&nbsp;4</span></div> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) message with reactions displayEmojiReactionUsers: true guest user reacts 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> <div class=\\"reaction-list\\"><span onclick=\\"\\" class=\\"reaction\\" data-name=\\"github_parrot\\" data-code=\\"80\\" data-type=\\"realm_emoji\\"><img src=\\"path_to_url">&nbsp;{userFullName} (guest)</span></div> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) muted sender 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"hidden\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> <div class=\\"special-message muted-message-explanation\\"> This message was hidden because it is from a user you have muted. Long-press to view. </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) sender status emoji: none 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) sender status emoji: realm 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User<img class=\\"status-emoji\\" src=\\"path_to_url"> </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) sender status emoji: unicode 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User<span class=\\"status-emoji\\"></span> </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible other interesting cases (single messages) sender status emoji: zulip extra 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1\\"> <div class=\\"timerow-left\\"></div> Dec 31, 1969 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header stream-header topic-header\\" data-msg-id=\\"1\\" data-narrow=\\"dG9waWM6MTpleGFtcGxlIHRvcGlj\\"> <div class=\\"header stream-text\\" style=\\"color: black; background: hsl(0, 0%, 80%)\\" data-narrow=\\"c3RyZWFtOjE=\\"> # stream 1 </div> <div class=\\"topic-text\\" data-followed=\\"false\\">example topic</div> <div class=\\"topic-date\\">Dec 31, 1969</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1\\" data-msg-id=\\"1\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name sender User\\" class=\\"avatar-img\\" data-sender-id=\\"10\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"10\\"> Nonrandom name sender User<img class=\\"status-emoji\\" src=\\"path_to_url"> </div> <div class=\\"static-timestamp\\">11:59 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible pm:1,2 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"8849\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8849\\" data-msg-id=\\"8849\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-8917\\" data-msg-id=\\"8917\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible pm:1,2 2`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5287\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5287\\" data-msg-id=\\"5287\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5309\\" data-msg-id=\\"5309\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible pm:1,2 3`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5829\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5829\\" data-msg-id=\\"5829\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"5963\\"> <div class=\\"timerow-left\\"></div> Feb 26, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5963\\" data-msg-id=\\"5963\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible pm:1,2 4`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5287\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5287\\" data-msg-id=\\"5287\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5309\\" data-msg-id=\\"5309\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5829\\" data-msg-id=\\"5829\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"5963\\"> <div class=\\"timerow-left\\"></div> Feb 26, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5963\\" data-msg-id=\\"5963\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"8849\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8849\\" data-msg-id=\\"8849\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-8917\\" data-msg-id=\\"8917\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible pm:1,2,3 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5377\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5377\\" data-msg-id=\\"5377\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-5620\\" data-msg-id=\\"5620\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible pm:1,2,3 2`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"5637\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5637\\" data-msg-id=\\"5637\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5727\\" data-msg-id=\\"5727\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible pm:1,2,3 3`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"2794\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-2794\\" data-msg-id=\\"2794\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"4581\\"> <div class=\\"timerow-left\\"></div> Feb 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-4581\\" data-msg-id=\\"4581\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible pm:1,2,3 4`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"2794\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-2794\\" data-msg-id=\\"2794\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"4581\\"> <div class=\\"timerow-left\\"></div> Feb 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-4581\\" data-msg-id=\\"4581\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"5377\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5377\\" data-msg-id=\\"5377\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-5620\\" data-msg-id=\\"5620\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-5637\\" data-msg-id=\\"5637\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example PM message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5727\\" data-msg-id=\\"5727\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example PM message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible stream:1 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1024\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header topic-header\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\" data-msg-id=\\"1024\\"> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Feb 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1024\\" data-msg-id=\\"1024\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-1598\\" data-msg-id=\\"1598\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible stream:1 2`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"7938\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header topic-header\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\" data-msg-id=\\"7938\\"> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-7938\\" data-msg-id=\\"7938\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8060\\" data-msg-id=\\"8060\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible stream:1 3`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"4948\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header topic-header\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\" data-msg-id=\\"4948\\"> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Feb 19, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-4948\\" data-msg-id=\\"4948\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element header-wrapper header topic-header\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAy\\" data-msg-id=\\"5083\\"> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 2</div> <div class=\\"topic-date\\">Feb 19, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5083\\" data-msg-id=\\"5083\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible stream:1 4`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"9181\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header topic-header\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\" data-msg-id=\\"9181\\"> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9181\\" data-msg-id=\\"9181\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"9815\\"> <div class=\\"timerow-left\\"></div> Mar 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9815\\" data-msg-id=\\"9815\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible stream:1 5`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1024\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header topic-header\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\" data-msg-id=\\"1024\\"> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Feb 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1024\\" data-msg-id=\\"1024\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-1598\\" data-msg-id=\\"1598\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"4948\\"> <div class=\\"timerow-left\\"></div> Feb 19, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-4948\\" data-msg-id=\\"4948\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element header-wrapper header topic-header\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAy\\" data-msg-id=\\"5083\\"> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 2</div> <div class=\\"topic-date\\">Feb 19, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-5083\\" data-msg-id=\\"5083\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"7938\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element header-wrapper header topic-header\\" data-narrow=\\"dG9waWM6MTp0b3BpYyAx\\" data-msg-id=\\"7938\\"> <div class=\\"topic-text\\" data-followed=\\"false\\">topic 1</div> <div class=\\"topic-date\\">Mar 5, 1995</div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-7938\\" data-msg-id=\\"7938\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8060\\" data-msg-id=\\"8060\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9181\\" data-msg-id=\\"9181\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"9815\\"> <div class=\\"timerow-left\\"></div> Mar 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9815\\" data-msg-id=\\"9815\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible topic:1:topic 1 1`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1024\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1024\\" data-msg-id=\\"1024\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-1598\\" data-msg-id=\\"1598\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible topic:1:topic 1 2`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"7938\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-7938\\" data-msg-id=\\"7938\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8060\\" data-msg-id=\\"8060\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible topic:1:topic 1 3`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"9181\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9181\\" data-msg-id=\\"9181\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"9815\\"> <div class=\\"timerow-left\\"></div> Mar 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9815\\" data-msg-id=\\"9815\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; exports[`messages -> piece descriptors -> content HTML is stable/sensible topic:1:topic 1 4`] = ` "<div class=\\"msglist-element timerow\\" data-msg-id=\\"1024\\"> <div class=\\"timerow-left\\"></div> Feb 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-1024\\" data-msg-id=\\"1024\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-brief\\" id=\\"msg-1598\\" data-msg-id=\\"1598\\" data-mute-state=\\"shown\\"> <div class=\\"content\\"> <div class=\\"time-container\\"> <div class=\\"msg-timestamp \\"> 12:00 PM </div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"7938\\"> <div class=\\"timerow-left\\"></div> Mar 5, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-7938\\" data-msg-id=\\"7938\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-8060\\" data-msg-id=\\"8060\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name two User\\" class=\\"avatar-img\\" data-sender-id=\\"2\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"2\\"> Nonrandom name two User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9181\\" data-msg-id=\\"9181\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div><div class=\\"msglist-element timerow\\" data-msg-id=\\"9815\\"> <div class=\\"timerow-left\\"></div> Mar 12, 1995 <div class=\\"timerow-right\\"></div> </div><div class=\\"msglist-element message message-full\\" id=\\"msg-9815\\" data-msg-id=\\"9815\\" data-mute-state=\\"shown\\"> <div class=\\"avatar\\"> <img src=\\"path_to_url" alt=\\"Nonrandom name one User\\" class=\\"avatar-img\\" data-sender-id=\\"1\\"> </div> <div class=\\"content\\"> <div class=\\"subheader\\"> <div class=\\"name-and-status-emoji\\" data-sender-id=\\"1\\"> Nonrandom name one User </div> <div class=\\"static-timestamp\\">12:00 PM</div> </div> <p>This is an example stream message.</p> </div> </div>" `; ```
/content/code_sandbox/src/webview/__tests__/__snapshots__/generateInboundEventEditSequence-test.js.snap.android
unknown
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
39,602
```javascript /* @flow strict-local */ import type { HuddlesUnreadItem, PmsUnreadItem, UserId } from '../types'; import { addItemsToArray, removeItemsFromArray, filterArray } from '../utils/immutability'; type SomeUnreadItem = $ReadOnly<{ unread_message_ids: $ReadOnlyArray<number>, ... }>; export function removeItemsDeeply<T: SomeUnreadItem>( objArray: $ReadOnlyArray<T>, messageIds: $ReadOnlyArray<number>, ): $ReadOnlyArray<T> { let changed = false; const objWithAddedUnreadIds = objArray.map(obj => { const filteredIds = removeItemsFromArray(obj.unread_message_ids, messageIds); if (filteredIds === obj.unread_message_ids) { return obj; } changed = true; return { ...obj, unread_message_ids: filteredIds, }; }); if (!changed) { return objArray; } return filterArray( objWithAddedUnreadIds, sender => sender && sender.unread_message_ids.length > 0, ); } function addItemsDeeply<T: SomeUnreadItem>( input: $ReadOnlyArray<T>, itemsToAdd: $ReadOnlyArray<number>, index: number, ): $ReadOnlyArray<T> { const item = input[index]; const unreadMessageIds = addItemsToArray(item.unread_message_ids, itemsToAdd); if (item.unread_message_ids === unreadMessageIds) { return input; } return [ ...input.slice(0, index), { ...item, unread_message_ids: unreadMessageIds, }, ...input.slice(index + 1), ]; } export const addItemsToPmArray = ( input: $ReadOnlyArray<PmsUnreadItem>, itemsToAdd: $ReadOnlyArray<number>, senderId: UserId, ): $ReadOnlyArray<PmsUnreadItem> => { const index = input.findIndex(sender => sender.sender_id === senderId); if (index !== -1) { return addItemsDeeply(input, itemsToAdd, index); } return [ ...input, { sender_id: senderId, unread_message_ids: itemsToAdd, }, ]; }; export const addItemsToHuddleArray = ( input: $ReadOnlyArray<HuddlesUnreadItem>, itemsToAdd: $ReadOnlyArray<number>, userIds: string, ): $ReadOnlyArray<HuddlesUnreadItem> => { const index = input.findIndex(recipients => recipients.user_ids_string === userIds); if (index !== -1) { return addItemsDeeply(input, itemsToAdd, index); } return [ ...input, { user_ids_string: userIds, unread_message_ids: itemsToAdd, }, ]; }; ```
/content/code_sandbox/src/unread/unreadHelpers.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
599
```javascript /* @flow strict-local */ import type Immutable from 'immutable'; import type { HuddlesUnreadItem, PmsUnreadItem } from '../api/apiTypes'; /** * A summary of (almost) all unread stream messages. * * This is a map from stream IDs, to maps from topics, to lists of * message IDs. Each list is sorted. So e.g. for the number of unreads * in a given topic, say `.get(streamId).get(topic).size`. * * NB this includes messages to muted streams and topics. * * Part of `UnreadState`; see there for more. */ // prettier-ignore export type UnreadStreamsState = Immutable.Map<number, Immutable.Map<string, Immutable.List<number>>>; /** * A summary of (almost) all unread group PMs. * * ("Huddle" is the server's internal term for a group PM conversation.) * * The format is borrowed straight from the initial version of this data the * server gives us at `/register` time, and is a bit quirky. See the * definition of `HuddlesUnreadItem` in `src/api/initialDataTypes.js`. * * Part of `UnreadState`; see there for more. */ export type UnreadHuddlesState = $ReadOnlyArray<HuddlesUnreadItem>; /** * A summary of (almost) all unread 1:1 PMs. * * The format is borrowed straight from the initial version of this data the * server gives us at `/register` time, and is a bit quirky. See the * definition of `PmsUnreadItem` in `src/api/initialDataTypes.js`. * * Part of `UnreadState`; see there for more. * See in particular `UnreadHuddlesState` for group PMs. */ export type UnreadPmsState = $ReadOnlyArray<PmsUnreadItem>; /** * A summary of (almost) all unread messages with @-mentions. * * This is a list of message IDs. It is not necessarily sorted. * * NB that each of these messages is necessarily also either a stream * message, a group PM, or a 1:1 PM, so it will also be found in one of the * other parts of `UnreadState`. * * Part of `UnreadState`; see there for more. */ export type UnreadMentionsState = $ReadOnlyArray<number>; /** * A summary of (almost) all unread messages, even those we don't have. * * For the meaning of "(almost) all", see discussion at `unread_msgs` in * `src/api/initialDataTypes.js`, describing the server feature that gives * us the initial version of this data at `/register` time. * * Starting from that initial version, we keep this data structure up to * date as new messages arrive, as messages are marked as read, etc. */ export type UnreadState = $ReadOnly<{| streams: UnreadStreamsState, huddles: UnreadHuddlesState, pms: UnreadPmsState, mentions: UnreadMentionsState, |}>; ```
/content/code_sandbox/src/unread/unreadModelTypes.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
671
```javascript /* @flow strict-local */ import invariant from 'invariant'; import type { PerAccountApplicableAction } from '../types'; import type { UnreadMentionsState } from './unreadModelTypes'; import { REGISTER_COMPLETE, EVENT_NEW_MESSAGE, EVENT_MESSAGE_DELETE, EVENT_UPDATE_MESSAGE_FLAGS, RESET_ACCOUNT_DATA, } from '../actionConstants'; import { addItemsToArray, removeItemsFromArray } from '../utils/immutability'; import { NULL_ARRAY } from '../nullObjects'; import * as logging from '../utils/logging'; const initialState: UnreadMentionsState = NULL_ARRAY; const eventUpdateMessageFlags = (state, action) => { if (action.flag !== 'read') { return state; } if (action.all) { return initialState; } if (action.op === 'add') { return removeItemsFromArray(state, action.messages); } else if (action.op === 'remove') { const { message_details } = action; if (message_details === undefined) { logging.warn('Got update_message_flags/remove/read event without message_details.'); return state; } const newUnreadMentions = Array.from(message_details) .filter(([id, info]) => info.mentioned && !state.includes(id)) .map(([id, info]) => id); return addItemsToArray(state, newUnreadMentions); } return state; }; export default ( state: UnreadMentionsState = initialState, // eslint-disable-line default-param-last action: PerAccountApplicableAction, ): UnreadMentionsState => { switch (action.type) { case RESET_ACCOUNT_DATA: return initialState; case REGISTER_COMPLETE: return action.data.unread_msgs.mentions; case EVENT_NEW_MESSAGE: { const { flags } = action.message; invariant(flags, 'message in EVENT_NEW_MESSAGE must have flags'); if (flags.includes('read')) { return state; } return (flags.includes('mentioned') || flags.includes('wildcard_mentioned')) && !state.includes(action.message.id) ? addItemsToArray(state, [action.message.id]) : state; } case EVENT_MESSAGE_DELETE: return removeItemsFromArray(state, action.messageIds); case EVENT_UPDATE_MESSAGE_FLAGS: return eventUpdateMessageFlags(state, action); default: return state; } }; ```
/content/code_sandbox/src/unread/unreadMentionsReducer.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
502
```javascript /* @flow strict-local */ import { createSelector } from 'reselect'; import type { Narrow, Selector } from '../types'; import type { UnreadStreamItem } from './UnreadCards'; import { caseInsensitiveCompareFunc } from '../utils/misc'; import { getMute, isTopicVisibleInStream, isTopicVisible } from '../mute/muteModel'; import { getOwnUserId } from '../users/userSelectors'; import { getSubscriptionsById, getStreamsById } from '../subscriptions/subscriptionSelectors'; import { caseNarrow } from '../utils/narrow'; import { getUnread, getUnreadPms, getUnreadHuddles, getUnreadMentions, getUnreadStreams, getUnreadCountForTopic, getUnreadIdsForPmNarrow, } from './unreadModel'; /** The number of unreads in each stream, excluding muted topics, by stream ID. */ export const getUnreadByStream: Selector<{| [number]: number |}> = createSelector( getUnreadStreams, getMute, (unreadStreams, mute) => { const totals = ({}: {| [number]: number |}); for (const [streamId, streamData] of unreadStreams.entries()) { let total = 0; for (const [topic, msgIds] of streamData) { if (isTopicVisibleInStream(streamId, topic, mute)) { total += msgIds.size; } } totals[streamId] = total; } return totals; }, ); /** Total number of unread stream messages -- ??? treatment of muting. */ // TODO: it looks like this excludes muted topics, but *includes* muted streams. export const getUnreadStreamTotal: Selector<number> = createSelector( getUnreadByStream, unreadByStream => Object.values(unreadByStream).reduce((total, x) => +x + total, 0), ); /** * The number of unreads in each 1:1 PM thread, by user ID. * * Just as in the `unread_msgs` data structure, the user used in the key is * * for the self-PM thread, the self user; * * for other 1:1 PM threads, the other user in the thread. * * See also `getUnreadByHuddles`, for group PM threads. */ export const getUnreadByPms: Selector<{| [number]: number |}> = createSelector( getUnreadPms, unreadPms => { const totals = ({}: {| [number]: number |}); unreadPms.forEach(pm => { totals[pm.sender_id] = totals[pm.sender_id] || 0 + pm.unread_message_ids.length; }); return totals; }, ); /** * Total number of unread 1:1 PMs. * * See also `getUnreadHuddlesTotal`, for group PMs. */ export const getUnreadPmsTotal: Selector<number> = createSelector(getUnreadPms, unreadPms => unreadPms.reduce((total, pm) => total + pm.unread_message_ids.length, 0), ); /** * The number of unreads in each group PM thread. * * The keys correspond to `user_ids_string` in the `unread_msgs` data * structure; see `src/api/initialDataTypes.js`. In particular they include * all users in the thread, including the self user. * * See also `getUnreadByPms`, for 1:1 PM threads. */ export const getUnreadByHuddles: Selector<{| [string]: number |}> = createSelector( getUnreadHuddles, unreadHuddles => { const totals = ({}: {| [string]: number |}); unreadHuddles.forEach(huddle => { totals[huddle.user_ids_string] = totals[huddle.user_ids_string] || 0 + huddle.unread_message_ids.length; }); return totals; }, ); /** * Total number of unread group PMs. * * See also `getUnreadPmsTotal`, for 1:1 PMs. */ export const getUnreadHuddlesTotal: Selector<number> = createSelector( getUnreadHuddles, unreadHuddles => unreadHuddles.reduce((total, huddle) => total + huddle.unread_message_ids.length, 0), ); /** Total number of unread @-mentions. */ export const getUnreadMentionsTotal: Selector<number> = createSelector( getUnreadMentions, unreadMentions => unreadMentions.length, ); /** Total number of unreads, with ??? caveats. */ // TODO: This appears to double-count @-mentions. Why not just use `count` // from the `unread_msgs` data structure? // TODO: This seems to include muted streams, though not muted topics; // see `getUnreadStreamTotal`. Looks like this causes #3589. export const getUnreadTotal: Selector<number> = createSelector( getUnreadStreamTotal, getUnreadPmsTotal, getUnreadHuddlesTotal, getUnreadMentionsTotal, (unreadStreamTotal, unreadPmsTotal, unreadHuddlesTotal, mentionsTotal): number => unreadStreamTotal + unreadPmsTotal + unreadHuddlesTotal + mentionsTotal, ); /** * Summary of unread unmuted stream messages, to feed to the unreads screen. * * The exact collection of data included here is just an assortment of what * the unreads screen happens to need. * * Each stream with unmuted unreads appears as an element of the array, and * contains in `.data` an array with an element for each unmuted topic that * has unreads. */ export const getUnreadStreamsAndTopics: Selector<$ReadOnlyArray<UnreadStreamItem>> = createSelector( getSubscriptionsById, getUnreadStreams, getMute, getUnreadMentions, (subscriptionsById, unreadStreams, mute, unreadMentions) => { const result = []; const unreadMsgIds = new Set(unreadMentions); for (const [streamId, streamData] of unreadStreams.entries()) { const subscription = subscriptionsById.get(streamId); if (!subscription) { // We have a loose invariant that you can't have unreads in a stream // you're not subscribed to. It's "loose" because when you unsubscribe // from a stream you had unreads in, the server only asynchronously // marks them as read: // path_to_url#narrow/stream/378-api-design/topic/unreads.20in.20unsubscribed.20streams/near/1456534 // In the UI, though, we generally want to fix things up so that // it's as if the invariant were a real invariant. So if we find // some supposed "unreads" in a stream with no subscription, // avert our eyes; those "unread" records don't count. continue; } const { name, color, invite_only, pin_to_top, is_web_public } = subscription; let totalUnread = 0; const topics = []; for (const [topic, msgIds] of streamData) { if (!isTopicVisible(streamId, topic, subscription, mute)) { continue; } totalUnread += msgIds.size; const isMentioned = msgIds.some(id => unreadMsgIds.has(id)); topics.push({ key: topic, topic, unread: msgIds.size, isMentioned, lastUnreadMsgId: msgIds.last(), }); } if (topics.length === 0) { continue; } topics.sort((a, b) => b.lastUnreadMsgId - a.lastUnreadMsgId); result.push({ key: `stream:${streamId}`, streamId, streamName: name, isPrivate: invite_only, isPinned: pin_to_top, isWebPublic: is_web_public, color, unread: totalUnread, data: topics, }); } result.sort((a, b) => caseInsensitiveCompareFunc(a.streamName, b.streamName)); result.sort((a, b) => +b.isPinned - +a.isPinned); return result; }, ); /** * Total number of unreads in the given narrow... mostly. * * For the @-mention narrow, all-PMs narrow, and search narrows, * just returns 0. * * For the all-messages narrow, the caveats on `getUnreadTotal` apply. */ export const getUnreadCountForNarrow: Selector<number, Narrow> = createSelector( (state, narrow) => narrow, state => getStreamsById(state), state => getOwnUserId(state), state => getUnreadTotal(state), state => getUnread(state), state => getMute(state), (narrow, streams, ownUserId, unreadTotal, unread, mute) => caseNarrow(narrow, { home: () => unreadTotal, stream: streamId => unread.streams .get(streamId) ?.entrySeq() .filter(([topic, _]) => isTopicVisibleInStream(streamId, topic, mute)) .map(([_, msgIds]) => msgIds.size) .reduce((s, x) => s + x, 0) ?? 0, topic: (streamId, topic) => getUnreadCountForTopic(unread, streamId, topic), pm: _ => getUnreadIdsForPmNarrow(unread, narrow, ownUserId).length, // Unread starred messages are impossible, so 0 is correct for the // starred-messages narrow. // TODO: fact-check that. starred: () => 0, // TODO: give a correct answer for the @-mentions narrow. mentioned: () => 0, // For search narrows, shrug, a bogus answer of 0 is fine. search: () => 0, // For the all-PMs narrow, a bogus answer of 0 is perfectly fine // because we never use this selector for that narrow (because we // don't expose it as one you can narrow to in the UI.) allPrivate: () => 0, }), ); ```
/content/code_sandbox/src/unread/unreadSelectors.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
2,258
```javascript /* @flow strict-local */ import React, { useState } from 'react'; import type { Node } from 'react'; import { SectionList } from 'react-native'; import Immutable from 'immutable'; import { useDispatch, useSelector } from '../react-redux'; import SearchEmptyState from '../common/SearchEmptyState'; import PmConversationList from '../pm-conversations/PmConversationList'; import StreamItem from '../streams/StreamItem'; import TopicItem from '../streams/TopicItem'; import { streamNarrow, topicNarrow } from '../utils/narrow'; import { getUnreadConversations, getUnreadStreamsAndTopics } from '../selectors'; import { doNarrow } from '../actions'; /** * An item in the data prepared for this UI by its helper selectors. * * See `getUnreadStreamsAndTopics`. * * The exact collection of data included here is just an assortment of what * the UI in this file happens to need. */ export type UnreadStreamItem = {| key: string, streamId: number, streamName: string, unread: number, color: string, isPinned: boolean, isPrivate: boolean, isWebPublic: boolean | void, data: $ReadOnlyArray<{| key: string, topic: string, isMentioned: boolean, unread: number, lastUnreadMsgId: number, |}>, |}; type Props = $ReadOnly<{||}>; export default function UnreadCards(props: Props): Node { const dispatch = useDispatch(); const conversations = useSelector(getUnreadConversations); const unreadStreamsAndTopics = useSelector(getUnreadStreamsAndTopics); const [collapsedStreamIds, setCollapsedStreamIds] = useState(Immutable.Set<number>()); type Card = | UnreadStreamItem | {| key: 'private', data: $ReadOnlyArray<React$ElementConfig<typeof PmConversationList>> |}; const unreadCards: $ReadOnlyArray<Card> = [ { key: 'private', data: [{ conversations }], }, ...unreadStreamsAndTopics.map(section => collapsedStreamIds.has(section.streamId) ? { ...section, data: [] } : section, ), ]; const handleExpandCollapse = (id: number) => { setCollapsedStreamIds( collapsedStreamIds.has(id) ? collapsedStreamIds.delete(id) : collapsedStreamIds.add(id), ); }; if (unreadStreamsAndTopics.length === 0 && conversations.length === 0) { return <SearchEmptyState text="No unread messages" />; } return ( // $FlowFixMe[incompatible-type-arg] /* $FlowFixMe[prop-missing] SectionList libdef seems confused; should take $ReadOnly objects. */ <SectionList stickySectionHeadersEnabled initialNumToRender={20} sections={unreadCards} renderSectionHeader={({ section }) => section.key === 'private' ? null : ( <StreamItem streamId={section.streamId} name={section.streamName} iconSize={16} isCollapsed={collapsedStreamIds.has(section.streamId)} handleExpandCollapse={handleExpandCollapse} isMuted={false} isPrivate={section.isPrivate} isWebPublic={section.isWebPublic} backgroundColor={section.color} unreadCount={section.unread} extraPaddingEnd={20} onPress={stream => { setTimeout(() => dispatch(doNarrow(streamNarrow(stream.stream_id)))); }} /> ) } renderItem={({ item, section }) => section.key === 'private' ? ( <PmConversationList extraPaddingEnd={20} {...item} /> ) : ( <TopicItem streamId={section.streamId} name={item.topic} isMuted={false} isSelected={false} unreadCount={item.unread} isMentioned={item.isMentioned} onPress={(streamId: number, topic: string) => { setTimeout(() => dispatch(doNarrow(topicNarrow(streamId, topic)))); }} /> ) } /> ); } ```
/content/code_sandbox/src/unread/UnreadCards.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
888
```javascript /* @flow strict-local */ import invariant from 'invariant'; import type { PerAccountApplicableAction } from '../types'; import type { UnreadHuddlesState } from './unreadModelTypes'; import { REGISTER_COMPLETE, EVENT_NEW_MESSAGE, EVENT_MESSAGE_DELETE, EVENT_UPDATE_MESSAGE_FLAGS, RESET_ACCOUNT_DATA, } from '../actionConstants'; import { pmUnreadsKeyFromMessage, pmUnreadsKeyFromOtherUsers, recipientsOfPrivateMessage, } from '../utils/recipient'; import { addItemsToHuddleArray, removeItemsDeeply } from './unreadHelpers'; import { NULL_ARRAY } from '../nullObjects'; import * as logging from '../utils/logging'; import type { PerAccountState } from '../reduxTypes'; import { getOwnUserId } from '../users/userSelectors'; const initialState: UnreadHuddlesState = NULL_ARRAY; const eventNewMessage = (state, action) => { const { message } = action; if (message.type !== 'private') { return state; } if (recipientsOfPrivateMessage(message).length < 3) { return state; } invariant(message.flags, 'message in EVENT_NEW_MESSAGE must have flags'); if (message.flags.includes('read')) { return state; } return addItemsToHuddleArray(state, [message.id], pmUnreadsKeyFromMessage(message)); }; const eventUpdateMessageFlags = (state, action, ownUserId) => { if (action.flag !== 'read') { return state; } if (action.all) { return initialState; } if (action.op === 'add') { return removeItemsDeeply(state, action.messages); } else if (action.op === 'remove') { const { message_details } = action; if (message_details === undefined) { logging.warn('Got update_message_flags/remove/read event without message_details.'); return state; } let newState = state; for (const id of action.messages) { const message = message_details.get(id); if (message && message.type === 'private' && message.user_ids.length >= 2) { const unreadsKey = pmUnreadsKeyFromOtherUsers(message.user_ids, ownUserId); newState = addItemsToHuddleArray(newState, [id], unreadsKey); } } // TODO This re-sorting/deduping is pretty overkill; only the // conversations we actually touched need it. But rather than add // complications to the `addItemsTo` system to support that, let's // spend that effort instead to finally rip that system out in favor // of Immutable.js. return newState.map(({ user_ids_string, unread_message_ids }) => ({ user_ids_string, unread_message_ids: [...new Set(unread_message_ids)].sort((a, b) => a - b), })); } return state; }; export default ( state: UnreadHuddlesState = initialState, // eslint-disable-line default-param-last action: PerAccountApplicableAction, globalState: PerAccountState, ): UnreadHuddlesState => { switch (action.type) { case RESET_ACCOUNT_DATA: return initialState; case REGISTER_COMPLETE: return action.data.unread_msgs.huddles; case EVENT_NEW_MESSAGE: return eventNewMessage(state, action); case EVENT_MESSAGE_DELETE: return removeItemsDeeply(state, action.messageIds); case EVENT_UPDATE_MESSAGE_FLAGS: return eventUpdateMessageFlags(state, action, getOwnUserId(globalState)); default: return state; } }; ```
/content/code_sandbox/src/unread/unreadHuddlesReducer.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
778
```javascript /* @flow strict-local */ import deepFreeze from 'deep-freeze'; import Immutable from 'immutable'; import unreadMentionsReducer from '../unreadMentionsReducer'; import { EVENT_UPDATE_MESSAGE_FLAGS } from '../../actionConstants'; import { NULL_ARRAY } from '../../nullObjects'; import * as eg from '../../__tests__/lib/exampleData'; describe('unreadMentionsReducer', () => { describe('RESET_ACCOUNT_DATA', () => { test('resets state to initial state', () => { const initialState = deepFreeze([1, 2, 3]); const expectedState = []; const actualState = unreadMentionsReducer(initialState, eg.action.reset_account_data); expect(actualState).toEqual(expectedState); }); }); describe('REGISTER_COMPLETE', () => { test('received data from "unread_msgs.mentioned" key replaces the current state ', () => { const initialState = deepFreeze([]); const action = eg.mkActionRegisterComplete({ unread_msgs: { streams: [], huddles: [], pms: [], mentions: [1, 2, 3] }, }); const expectedState = [1, 2, 3]; const actualState = unreadMentionsReducer(initialState, action); expect(actualState).toEqual(expectedState); }); }); describe('EVENT_NEW_MESSAGE', () => { test('if message does not contain "mentioned" flag, do not mutate state', () => { const initialState = deepFreeze([]); const action = eg.mkActionEventNewMessage(eg.streamMessage({ flags: [] })); const actualState = unreadMentionsReducer(initialState, action); expect(actualState).toBe(initialState); }); test('if message has "read" flag, do not mutate state', () => { const initialState = deepFreeze([]); const action = eg.mkActionEventNewMessage(eg.streamMessage({ flags: ['mentioned', 'read'] })); const actualState = unreadMentionsReducer(initialState, action); expect(actualState).toBe(initialState); }); test('if message id already exists, do not mutate state', () => { const initialState = deepFreeze([1, 2]); const action = eg.mkActionEventNewMessage( eg.streamMessage({ id: 2, flags: ['mentioned', 'read'] }), ); const actualState = unreadMentionsReducer(initialState, action); expect(actualState).toBe(initialState); }); test('if "mentioned" flag is set and message id does not exist, append to state', () => { const initialState = deepFreeze([1, 2]); const action = eg.mkActionEventNewMessage(eg.streamMessage({ id: 3, flags: ['mentioned'] })); const expectedState = [1, 2, 3]; const actualState = unreadMentionsReducer(initialState, action); expect(actualState).toEqual(expectedState); }); }); describe('EVENT_UPDATE_MESSAGE_FLAGS', () => { test('when operation is "add" but flag is not "read" do not mutate state', () => { const initialState = deepFreeze([]); const action = { type: EVENT_UPDATE_MESSAGE_FLAGS, id: 0, all: false, allMessages: Immutable.Map(), messages: [1, 2, 3], flag: 'starred', op: 'add', }; const actualState = unreadMentionsReducer(initialState, action); expect(actualState).toBe(initialState); }); test('if id does not exist do not mutate state', () => { const initialState = deepFreeze([1]); const action = deepFreeze({ type: EVENT_UPDATE_MESSAGE_FLAGS, id: 0, all: false, allMessages: Immutable.Map(), messages: [2], flag: 'read', op: 'add', }); const actualState = unreadMentionsReducer(initialState, action); expect(actualState).toBe(initialState); }); test('if ids are in state remove them', () => { const initialState = deepFreeze([1, 2, 3]); const action = deepFreeze({ type: EVENT_UPDATE_MESSAGE_FLAGS, id: 0, all: false, allMessages: Immutable.Map(), messages: [2, 3], flag: 'read', op: 'add', }); const expectedState = [1]; const actualState = unreadMentionsReducer(initialState, action); expect(actualState).toEqual(expectedState); }); test('when operation is "remove", add mentions to unreads', () => { const initialState = deepFreeze([1]); const expectedState = deepFreeze([1, 2]); const messageDetailsEntry = (stream_id, topic, mentioned) => ({ type: 'stream', mentioned: mentioned === true ? true : undefined, stream_id, topic, }); const action = deepFreeze({ type: EVENT_UPDATE_MESSAGE_FLAGS, id: 0, all: false, allMessages: Immutable.Map(), messages: [1, 2, 3], flag: 'read', op: 'remove', message_details: new Map([ [1, messageDetailsEntry(999, 'some topic', true)], [2, messageDetailsEntry(999, 'some topic', true)], [3, messageDetailsEntry(123, 'another topic', false)], ]), }); const actualState = unreadMentionsReducer(initialState, action); expect(actualState).toStrictEqual(expectedState); }); test('when "all" is true reset state', () => { const initialState = deepFreeze([1, 2, 3]); const action = deepFreeze({ type: EVENT_UPDATE_MESSAGE_FLAGS, id: 0, allMessages: Immutable.Map(), messages: [], flag: 'read', op: 'add', all: true, }); const actualState = unreadMentionsReducer(initialState, action); expect(actualState).toBe(NULL_ARRAY); }); }); }); ```
/content/code_sandbox/src/unread/__tests__/unreadMentionsReducer-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,315
```javascript /* @flow strict-local */ import { reducer } from '../unreadModel'; import type { UnreadState } from '../unreadModelTypes'; import type { Message, Stream } from '../../api/apiTypes'; import type { PerAccountState } from '../../reduxTypes'; import * as eg from '../../__tests__/lib/exampleData'; import { randString } from '../../utils/misc'; export const initialState: UnreadState = reducer( undefined, ({ type: randString() }: $FlowFixMe), eg.baseReduxState, ); export const stream0: Stream = eg.makeStream({ stream_id: 0, name: 'stream 0' }); export const stream2: Stream = eg.makeStream({ stream_id: 2, name: 'stream 2' }); const [user0, user1, user2, user3, user4, user5] = [0, 1, 2, 3, 4, 5].map(user_id => eg.makeUser({ user_id }), ); export const makeUnreadState = ( globalState: PerAccountState, messages: $ReadOnlyArray<Message>, ): UnreadState => messages.reduce( (state, message) => reducer(state, eg.mkActionEventNewMessage(message), globalState), initialState, ); export const selectorBaseState: UnreadState = (() => { // We take user1 to be self. // It might be convenient to convert this to the standard eg.selfUser, // and use eg.reduxStatePlus. Until then, this just minimizes how much // we've had to do in order to adapt our pre-existing tests. const globalState = eg.reduxState({ realm: { ...eg.baseReduxState.realm, user_id: user1.user_id }, users: [user0, user1, user2, user3, user4, user5], streams: [stream0, stream2], }); return makeUnreadState(globalState, [ eg.streamMessage({ stream_id: 0, subject: 'a topic', id: 1, flags: ['mentioned'] }), eg.streamMessage({ stream_id: 0, subject: 'a topic', id: 2, flags: ['mentioned'] }), eg.streamMessage({ stream_id: 0, subject: 'a topic', id: 3, flags: ['mentioned'] }), eg.streamMessage({ stream_id: 0, subject: 'another topic', id: 4 }), eg.streamMessage({ stream_id: 0, subject: 'another topic', id: 5 }), eg.streamMessage({ stream_id: 2, subject: 'some other topic', id: 6 }), eg.streamMessage({ stream_id: 2, subject: 'some other topic', id: 7 }), eg.pmMessageFromTo(user0, [user1], { id: 11 }), eg.pmMessageFromTo(user0, [user1], { id: 12 }), eg.pmMessageFromTo(user2, [user1], { id: 13 }), eg.pmMessageFromTo(user2, [user1], { id: 14 }), eg.pmMessageFromTo(user2, [user1], { id: 15 }), eg.pmMessageFromTo(user2, [user1, user3], { id: 21 }), eg.pmMessageFromTo(user2, [user1, user3], { id: 22 }), eg.pmMessageFromTo(user4, [user1, user5], { id: 23 }), eg.pmMessageFromTo(user4, [user1, user5], { id: 24 }), eg.pmMessageFromTo(user4, [user1, user5], { id: 25 }), ]); })(); ```
/content/code_sandbox/src/unread/__tests__/unread-testlib.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
802
```javascript /* @flow strict-local */ import deepFreeze from 'deep-freeze'; import unreadPmsReducer from '../unreadPmsReducer'; import { EVENT_UPDATE_MESSAGE_FLAGS } from '../../actionConstants'; import { NULL_ARRAY } from '../../nullObjects'; import * as eg from '../../__tests__/lib/exampleData'; import { makeUserId } from '../../api/idTypes'; describe('unreadPmsReducer', () => { describe('RESET_ACCOUNT_DATA', () => { test('resets state to initial state', () => { const initialState = deepFreeze([ { sender_id: makeUserId(1), unread_message_ids: [1, 2, 3], }, ]); const expectedState = []; const actualState = unreadPmsReducer( initialState, eg.action.reset_account_data, eg.plusReduxState, ); expect(actualState).toEqual(expectedState); }); }); describe('REGISTER_COMPLETE', () => { test('received data from "unread_msgs.pms" key replaces the current state ', () => { const initialState = deepFreeze([]); const message1 = eg.pmMessage({ id: 1, sender_id: 1 }); const message2 = eg.pmMessage({ id: 2, sender_id: 1 }); const message3 = eg.pmMessage({ id: 3, sender_id: 1 }); const message4 = eg.pmMessage({ id: 4, sender_id: 1 }); const message5 = eg.pmMessage({ id: 5, sender_id: 1 }); const action = eg.mkActionRegisterComplete({ unread_msgs: { streams: [], huddles: [], pms: [ { sender_id: message1.sender_id, unread_message_ids: [message1.id, message2.id, message4.id, message5.id], }, ], mentions: [message1.id, message2.id, message3.id], }, }); const expectedState = [ { sender_id: message1.sender_id, unread_message_ids: [message1.id, message2.id, message4.id, message5.id], }, ]; const actualState = unreadPmsReducer(initialState, action, eg.plusReduxState); expect(actualState).toEqual(expectedState); }); }); describe('EVENT_NEW_MESSAGE', () => { test('if message id already exists, do not mutate state', () => { const message1 = eg.pmMessage({ sender_id: 1 }); const initialState = deepFreeze([ { sender_id: message1.sender_id, unread_message_ids: [message1.id], }, ]); const action = eg.mkActionEventNewMessage(message1); const actualState = unreadPmsReducer(initialState, action, eg.plusReduxState); expect(actualState).toBe(initialState); }); test('if message is not private, return original state', () => { const message4 = eg.streamMessage({ id: 4 }); const initialState = deepFreeze([ { sender_id: makeUserId(1), unread_message_ids: [1, 2, 3], }, ]); const action = eg.mkActionEventNewMessage(message4); const actualState = unreadPmsReducer(initialState, action, eg.plusReduxState); expect(actualState).toBe(initialState); }); test('if message is marked read, do not mutate state', () => { const initialState = deepFreeze([]); const message1 = eg.pmMessage({ sender: eg.otherUser, recipients: [eg.otherUser, eg.selfUser], flags: ['read'], }); const action = eg.mkActionEventNewMessage(message1); const actualState = unreadPmsReducer(initialState, action, eg.plusReduxState); expect(actualState).toBe(initialState); }); test('if message is marked unread in self-PM, append to state', () => { const initialState = deepFreeze([]); const message1 = eg.pmMessage({ sender: eg.selfUser, recipients: [eg.selfUser], }); const action = eg.mkActionEventNewMessage(message1); const expectedState = [ { sender_id: eg.selfUser.user_id, unread_message_ids: [message1.id], }, ]; const actualState = unreadPmsReducer(initialState, action, eg.plusReduxState); expect(actualState).toEqual(expectedState); }); test('if message id does not exist, append to state', () => { const message1 = eg.pmMessage({ id: 1, sender_id: 1 }); const message2 = eg.pmMessage({ id: 2, sender_id: 1 }); const message3 = eg.pmMessage({ id: 3, sender_id: 1 }); const message4 = eg.pmMessage({ id: 4, sender_id: 1 }); const initialState = deepFreeze([ { sender_id: message4.sender_id, unread_message_ids: [message1.id, message2.id, message3.id], }, ]); const action = eg.mkActionEventNewMessage(message4); const expectedState = [ { sender_id: message4.sender_id, unread_message_ids: [message1.id, message2.id, message3.id, message4.id], }, ]; const actualState = unreadPmsReducer(initialState, action, eg.plusReduxState); expect(actualState).toEqual(expectedState); }); test('if sender id does not exist, append to state as new sender', () => { const message4 = eg.pmMessage({ id: 4, sender_id: 2 }); const initialState = deepFreeze([ { sender_id: makeUserId(1), unread_message_ids: [1, 2, 3], }, ]); const action = eg.mkActionEventNewMessage(message4); const expectedState = [ { sender_id: makeUserId(1), unread_message_ids: [1, 2, 3], }, { sender_id: message4.sender_id, unread_message_ids: [message4.id], }, ]; const actualState = unreadPmsReducer(initialState, action, eg.plusReduxState); expect(actualState).toEqual(expectedState); }); }); describe('EVENT_UPDATE_MESSAGE_FLAGS', () => { test('when operation is "add" but flag is not "read" do not mutate state', () => { const initialState = deepFreeze([]); const action = { id: 1, type: EVENT_UPDATE_MESSAGE_FLAGS, all: false, allMessages: eg.makeMessagesState([]), messages: [1, 2, 3], flag: 'starred', op: 'add', }; const actualState = unreadPmsReducer(initialState, action, eg.plusReduxState); expect(actualState).toBe(initialState); }); test('if id does not exist do not mutate state', () => { const initialState = deepFreeze([ { sender_id: makeUserId(1), unread_message_ids: [1, 2, 3, 4, 5], }, { sender_id: makeUserId(2), unread_message_ids: [4, 5], }, ]); const action = deepFreeze({ id: 1, type: EVENT_UPDATE_MESSAGE_FLAGS, all: false, allMessages: eg.makeMessagesState([]), messages: [6, 7], flag: 'read', op: 'add', }); const actualState = unreadPmsReducer(initialState, action, eg.plusReduxState); expect(actualState).toBe(initialState); }); test('if ids are in state remove them', () => { const initialState = deepFreeze([ { sender_id: makeUserId(1), unread_message_ids: [1, 2, 3], }, { sender_id: makeUserId(2), unread_message_ids: [4, 5], }, ]); const action = deepFreeze({ id: 1, type: EVENT_UPDATE_MESSAGE_FLAGS, all: false, allMessages: eg.makeMessagesState([]), messages: [3, 4, 5, 6], flag: 'read', op: 'add', }); const expectedState = [ { sender_id: 1, unread_message_ids: [1, 2], }, ]; const actualState = unreadPmsReducer(initialState, action, eg.plusReduxState); expect(actualState).toEqual(expectedState); }); test('when operation is "remove", add to unreads', () => { const initialState = deepFreeze([ { sender_id: eg.otherUser.user_id, unread_message_ids: [1, 3, 100], }, ]); const action = deepFreeze({ id: 1, type: EVENT_UPDATE_MESSAGE_FLAGS, all: false, allMessages: eg.makeMessagesState([]), messages: [6, 5, 7], flag: 'read', op: 'remove', message_details: new Map([ [5, { type: 'private', user_ids: [eg.otherUser.user_id] }], [6, { type: 'private', user_ids: [eg.otherUser.user_id] }], [7, { type: 'private', user_ids: [eg.selfUser.user_id] }], ]), }); const expectedState = deepFreeze([ { sender_id: eg.otherUser.user_id, unread_message_ids: [1, 3, 5, 6, 100], }, { sender_id: eg.selfUser.user_id, unread_message_ids: [7], }, ]); const actualState = unreadPmsReducer(initialState, action, eg.plusReduxState); expect(actualState).toStrictEqual(expectedState); }); test('on "remove", drop any duplicates', () => { const initialState = deepFreeze([ { sender_id: eg.otherUser.user_id, unread_message_ids: [1, 3] }, ]); const action = deepFreeze({ id: 1, type: EVENT_UPDATE_MESSAGE_FLAGS, all: false, allMessages: eg.makeMessagesState([]), messages: [1, 4], flag: 'read', op: 'remove', message_details: new Map([ [1, { type: 'private', user_ids: [eg.otherUser.user_id] }], [4, { type: 'private', user_ids: [eg.otherUser.user_id] }], ]), }); const expectedState = deepFreeze([ { sender_id: eg.otherUser.user_id, unread_message_ids: [1, 3, 4] }, ]); const actualState = unreadPmsReducer(initialState, action, eg.plusReduxState); expect(actualState).toStrictEqual(expectedState); }); test('when "all" is true reset state', () => { const initialState = deepFreeze([ { sender_id: makeUserId(1), unread_message_ids: [1, 2, 3, 4, 5], }, ]); const action = deepFreeze({ id: 1, type: EVENT_UPDATE_MESSAGE_FLAGS, all: true, allMessages: eg.makeMessagesState([]), messages: [], flag: 'read', op: 'add', }); const actualState = unreadPmsReducer(initialState, action, eg.plusReduxState); expect(actualState).toBe(NULL_ARRAY); }); }); }); ```
/content/code_sandbox/src/unread/__tests__/unreadPmsReducer-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
2,523
```javascript /* @flow strict-local */ import { getUnreadByStream, getUnreadStreamTotal, getUnreadByPms, getUnreadPmsTotal, getUnreadByHuddles, getUnreadHuddlesTotal, getUnreadMentionsTotal, getUnreadTotal, getUnreadStreamsAndTopics, } from '../unreadSelectors'; import * as eg from '../../__tests__/lib/exampleData'; import { initialState, makeUnreadState, selectorBaseState as unreadState, stream0, stream2, } from './unread-testlib'; import { makeMuteState } from '../../mute/__tests__/mute-testlib'; import { UserTopicVisibilityPolicy } from '../../api/modelTypes'; const subscription0 = eg.makeSubscription({ stream: stream0, color: 'red' }); const subscription2 = eg.makeSubscription({ stream: stream2, color: 'blue' }); const subscriptions = [subscription0, subscription2]; describe('getUnreadByStream', () => { test('when no items in streams key, the result is an empty object', () => { const state = eg.reduxState(); const unreadByStream = getUnreadByStream(state); expect(unreadByStream).toEqual({}); }); test('when there are unread stream messages, returns their counts', () => { const state = eg.reduxStatePlus({ subscriptions, unread: unreadState, mute: makeMuteState([[stream0, 'a topic']]), }); const unreadByStream = getUnreadByStream(state); expect(unreadByStream).toEqual({ '0': 2, '2': 2 }); }); }); describe('getUnreadStreamTotal', () => { test('when no items in "streams" key, there are unread message', () => { const state = eg.reduxStatePlus({ unread: initialState, subscriptions: [], }); const unreadCount = getUnreadStreamTotal(state); expect(unreadCount).toEqual(0); }); test('count all the unread messages listed in "streams" key', () => { const state = eg.reduxStatePlus({ unread: unreadState, }); const unreadCount = getUnreadStreamTotal(state); expect(unreadCount).toEqual(7); }); }); describe('getUnreadByPms', () => { test('when no items in streams key, the result is an empty array', () => { const state = eg.reduxStatePlus({ unread: initialState, }); const unreadByStream = getUnreadByPms(state); expect(unreadByStream).toEqual({}); }); test('when there are unread private messages, returns counts by sender_id', () => { const state = eg.reduxStatePlus({ unread: unreadState, }); const unreadByStream = getUnreadByPms(state); expect(unreadByStream).toEqual({ '0': 2, '2': 3 }); }); }); describe('getUnreadPmsTotal', () => { test('when no items in "pms" key, there are unread private messages', () => { const state = eg.reduxStatePlus({ unread: initialState, }); const unreadCount = getUnreadPmsTotal(state); expect(unreadCount).toEqual(0); }); test('when there are keys in "pms", sum up all unread private message counts', () => { const state = eg.reduxStatePlus({ unread: unreadState, }); const unreadCount = getUnreadPmsTotal(state); expect(unreadCount).toEqual(5); }); }); describe('getUnreadByHuddles', () => { test('when no items in streams key, the result is an empty array', () => { const state = eg.reduxStatePlus({ unread: initialState, }); const unreadByStream = getUnreadByHuddles(state); expect(unreadByStream).toEqual({}); }); test('when there are unread stream messages, returns a ', () => { const state = eg.reduxStatePlus({ unread: unreadState, }); const unreadByStream = getUnreadByHuddles(state); expect(unreadByStream).toEqual({ '1,2,3': 2, '1,4,5': 3 }); }); }); describe('getUnreadHuddlesTotal', () => { test('when no items in "huddles" key, there are unread group messages', () => { const state = eg.reduxStatePlus({ unread: initialState, }); const unreadCount = getUnreadHuddlesTotal(state); expect(unreadCount).toEqual(0); }); test('when there are keys in "huddles", sum up all unread group message counts', () => { const state = eg.reduxStatePlus({ unread: unreadState, }); const unreadCount = getUnreadHuddlesTotal(state); expect(unreadCount).toEqual(5); }); }); describe('getUnreadMentionsTotal', () => { test('unread mentions count is equal to the unread array length', () => { const state = eg.reduxStatePlus({ unread: unreadState, }); const unreadCount = getUnreadMentionsTotal(state); expect(unreadCount).toEqual(3); }); }); describe('getUnreadTotal', () => { test('if no key has any items then no unread messages', () => { const state = eg.reduxStatePlus({ unread: initialState, subscriptions: [], }); const unreadCount = getUnreadTotal(state); expect(unreadCount).toEqual(0); }); test('calculates total unread of streams + pms + huddles', () => { const state = eg.reduxStatePlus({ unread: unreadState, }); const unreadCount = getUnreadTotal(state); expect(unreadCount).toEqual(20); }); }); describe('getUnreadStreamsAndTopics', () => { test('if no key has any items then no unread messages', () => { const state = eg.reduxStatePlus({ subscriptions: [], unread: initialState, }); const unreadCount = getUnreadStreamsAndTopics(state); expect(unreadCount).toEqual([]); }); test('group data by stream and topics inside, count unread', () => { const state = eg.reduxStatePlus({ subscriptions, unread: unreadState, }); const unreadCount = getUnreadStreamsAndTopics(state); expect(unreadCount).toEqual([ { key: 'stream:0', streamId: 0, streamName: 'stream 0', color: 'red', unread: 5, isPinned: false, isPrivate: false, isWebPublic: false, data: [ { key: 'another topic', topic: 'another topic', unread: 2, lastUnreadMsgId: 5, isMentioned: false, }, { key: 'a topic', topic: 'a topic', unread: 3, lastUnreadMsgId: 3, isMentioned: true, }, ], }, { key: 'stream:2', streamId: 2, streamName: 'stream 2', color: 'blue', unread: 2, isPinned: false, isPrivate: false, isWebPublic: false, data: [ { key: 'some other topic', topic: 'some other topic', unread: 2, lastUnreadMsgId: 7, isMentioned: false, }, ], }, ]); }); test('streams are sorted alphabetically, case-insensitive, topics by last activity, pinned stream on top', () => { const stream1 = eg.makeStream({ name: 'xyz stream', stream_id: 1 }); const state = eg.reduxStatePlus({ subscriptions: [ { ...subscription2, color: 'green', name: 'def stream' }, eg.makeSubscription({ stream: stream1, color: 'blue', pin_to_top: true }), { ...subscription0, name: 'abc stream' }, ], unread: makeUnreadState(eg.plusReduxState, [ eg.streamMessage({ stream_id: 0, subject: 'z topic', id: 1 }), eg.streamMessage({ stream_id: 0, subject: 'z topic', id: 2 }), eg.streamMessage({ stream_id: 0, subject: 'z topic', id: 3 }), eg.streamMessage({ stream_id: 0, subject: 'a topic', id: 4 }), eg.streamMessage({ stream_id: 0, subject: 'a topic', id: 5 }), eg.streamMessage({ stream_id: 2, subject: 'b topic', id: 6 }), eg.streamMessage({ stream_id: 2, subject: 'b topic', id: 7 }), eg.streamMessage({ stream_id: 2, subject: 'c topic', id: 7 }), eg.streamMessage({ stream_id: 2, subject: 'c topic', id: 8 }), eg.streamMessage({ stream_id: 1, subject: 'e topic', id: 10 }), eg.streamMessage({ stream_id: 1, subject: 'd topic', id: 9 }), ]), // TODO yuck at constructing this modified stream as a throwaway, with magic string mute: makeMuteState([[{ ...stream2, name: 'def stream' }, 'c topic']]), }); const unreadCount = getUnreadStreamsAndTopics(state); expect(unreadCount).toEqual([ { key: 'stream:1', streamId: 1, streamName: 'xyz stream', color: 'blue', isPrivate: false, isPinned: true, isWebPublic: false, unread: 2, data: [ { key: 'e topic', topic: 'e topic', unread: 1, lastUnreadMsgId: 10, isMentioned: false, }, { key: 'd topic', topic: 'd topic', unread: 1, lastUnreadMsgId: 9, isMentioned: false, }, ], }, { key: 'stream:0', streamId: 0, streamName: 'abc stream', color: 'red', isPrivate: false, isPinned: false, isWebPublic: false, unread: 5, data: [ { key: 'a topic', topic: 'a topic', unread: 2, lastUnreadMsgId: 5, isMentioned: false, }, { key: 'z topic', topic: 'z topic', unread: 3, lastUnreadMsgId: 3, isMentioned: false, }, ], }, { key: 'stream:2', streamId: 2, streamName: 'def stream', color: 'green', isPrivate: false, isPinned: false, isWebPublic: false, unread: 2, data: [ { key: 'b topic', topic: 'b topic', unread: 2, lastUnreadMsgId: 7, isMentioned: false, }, ], }, ]); }); test('streams with no subscription are not included', () => { const state = eg.reduxStatePlus({ subscriptions: [], unread: unreadState, }); expect(getUnreadStreamsAndTopics(state)).toEqual([]); }); test('muted streams are not included', () => { const state = eg.reduxStatePlus({ subscriptions: subscriptions.map(s => ({ ...s, in_home_view: false })), unread: unreadState, }); const unreadCount = getUnreadStreamsAndTopics(state); expect(unreadCount).toEqual([]); }); test('unmuted topics in muted streams are included', () => { const state = eg.reduxStatePlus({ subscriptions: [{ ...subscription0, in_home_view: false }], unread: unreadState, mute: makeMuteState([[stream0, 'a topic', UserTopicVisibilityPolicy.Unmuted]]), }); const unreadCount = getUnreadStreamsAndTopics(state); expect(unreadCount).toEqual([ { color: 'red', data: [ { key: 'a topic', topic: 'a topic', unread: 3, lastUnreadMsgId: 3, isMentioned: true, }, ], isPinned: false, isPrivate: false, isWebPublic: false, key: 'stream:0', streamId: 0, streamName: 'stream 0', unread: 3, }, ]); }); test('muted topics inside non muted streams are not included', () => { const state = eg.reduxStatePlus({ subscriptions: [subscription0], unread: unreadState, mute: makeMuteState([[stream0, 'a topic']]), }); const unreadCount = getUnreadStreamsAndTopics(state); expect(unreadCount).toEqual([ { color: 'red', data: [ { key: 'another topic', topic: 'another topic', unread: 2, lastUnreadMsgId: 5, isMentioned: false, }, ], isPinned: false, isPrivate: false, isWebPublic: false, key: 'stream:0', streamId: 0, streamName: 'stream 0', unread: 2, }, ]); }); }); ```
/content/code_sandbox/src/unread/__tests__/unreadSelectors-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
3,068
```javascript /* @flow strict-local */ import deepFreeze from 'deep-freeze'; import unreadHuddlesReducer from '../unreadHuddlesReducer'; import { RESET_ACCOUNT_DATA, EVENT_UPDATE_MESSAGE_FLAGS } from '../../actionConstants'; import { NULL_ARRAY } from '../../nullObjects'; import * as eg from '../../__tests__/lib/exampleData'; import { makeUserId } from '../../api/idTypes'; describe('unreadHuddlesReducer', () => { describe('RESET_ACCOUNT_DATA', () => { test('resets state to initial state', () => { const initialState = deepFreeze([ { user_ids_string: '0,1,2', unread_message_ids: [1, 2, 3], }, ]); const action = deepFreeze({ type: RESET_ACCOUNT_DATA, }); const expectedState = []; const actualState = unreadHuddlesReducer(initialState, action, eg.plusReduxState); expect(actualState).toEqual(expectedState); }); }); describe('REGISTER_COMPLETE', () => { test('received data from "unread_msgs.huddles" key replaces the current state ', () => { const initialState = deepFreeze([]); const action = eg.mkActionRegisterComplete({ unread_msgs: { streams: [], huddles: [ { user_ids_string: '0,1,2', unread_message_ids: [1, 2, 4, 5], }, ], pms: [], mentions: [1, 2, 3], }, }); const expectedState = [ { user_ids_string: '0,1,2', unread_message_ids: [1, 2, 4, 5], }, ]; const actualState = unreadHuddlesReducer(initialState, action, eg.plusReduxState); expect(actualState).toEqual(expectedState); }); }); describe('EVENT_NEW_MESSAGE', () => { test('if message id already exists, do not mutate state', () => { const user1 = eg.makeUser({ user_id: 1 }); const user2 = eg.makeUser({ user_id: 2 }); const user3 = eg.makeUser({ user_id: 3 }); const message1 = eg.pmMessage({ id: 1, recipients: [user1, user2, user3] }); const message2 = eg.pmMessage({ id: 2, recipients: [user1, user2, user3] }); const message3 = eg.pmMessage({ id: 3, recipients: [user1, user2, user3] }); const initialState = deepFreeze([ { user_ids_string: `${user1.user_id},${user2.user_id},${user3.user_id}`, unread_message_ids: [message1.id, message2.id, message3.id], }, ]); const action = eg.mkActionEventNewMessage(message2); const actualState = unreadHuddlesReducer(initialState, action, eg.plusReduxState); expect(actualState).toBe(initialState); }); test('if message is not group, return original state', () => { const streamMessage = eg.streamMessage(); const initialState = deepFreeze([ { user_ids_string: '1,2,3', unread_message_ids: [1, 2, 3], }, ]); const action = eg.mkActionEventNewMessage(streamMessage); const actualState = unreadHuddlesReducer(initialState, action, eg.plusReduxState); expect(actualState).toBe(initialState); }); test('if message has "read" flag, do not mutate state', () => { const selfUser = { ...eg.selfUser, user_id: makeUserId(1) }; const user2 = { ...eg.otherUser, user_id: makeUserId(2) }; const user3 = { ...eg.thirdUser, user_id: makeUserId(3) }; const initialState = deepFreeze([]); const message2 = eg.pmMessage({ sender: user2, recipients: [selfUser, user2, user3], flags: ['read'], }); const action = eg.mkActionEventNewMessage(message2, { ownUserId: selfUser.user_id }); const actualState = unreadHuddlesReducer(initialState, action, eg.plusReduxState); expect(actualState).toBe(initialState); }); test('if message id does not exist, append to state', () => { const selfUser = { ...eg.selfUser, user_id: makeUserId(1) }; const user2 = { ...eg.otherUser, user_id: makeUserId(2) }; const user3 = { ...eg.thirdUser, user_id: makeUserId(3) }; const message4 = eg.pmMessage({ id: 4, recipients: [selfUser, user2, user3] }); const initialState = deepFreeze([ { user_ids_string: `${selfUser.user_id},${user2.user_id},${user3.user_id}`, unread_message_ids: [1, 2, 3], }, ]); const action = eg.mkActionEventNewMessage(message4); const expectedState = [ { user_ids_string: `${selfUser.user_id},${user2.user_id},${user3.user_id}`, unread_message_ids: [1, 2, 3, 4], }, ]; const actualState = unreadHuddlesReducer(initialState, action, eg.plusReduxState); expect(actualState).toEqual(expectedState); }); test('if sender-ids string does not exist, append to state as new', () => { const user1 = { ...eg.selfUser, user_id: makeUserId(1) }; const user2 = { ...eg.otherUser, user_id: makeUserId(2) }; const user3 = { ...eg.thirdUser, user_id: makeUserId(3) }; const message4 = eg.pmMessage({ id: 4, recipients: [user1, user2, user3] }); const initialState = deepFreeze([ { user_ids_string: '0,3,4', unread_message_ids: [1, 2, 3], }, ]); const action = eg.mkActionEventNewMessage(message4); const expectedState = [ { user_ids_string: '0,3,4', unread_message_ids: [1, 2, 3], }, { user_ids_string: `${user1.user_id},${user2.user_id},${user3.user_id}`, unread_message_ids: [4], }, ]; const actualState = unreadHuddlesReducer(initialState, action, eg.plusReduxState); expect(actualState).toEqual(expectedState); }); }); describe('EVENT_UPDATE_MESSAGE_FLAGS', () => { test('when operation is "add" but flag is not "read" do not mutate state', () => { const initialState = deepFreeze([]); const action = { id: 1, type: EVENT_UPDATE_MESSAGE_FLAGS, all: false, allMessages: eg.makeMessagesState([]), messages: [1, 2, 3], flag: 'starred', op: 'add', }; const actualState = unreadHuddlesReducer(initialState, action, eg.plusReduxState); expect(actualState).toBe(initialState); }); test('if id does not exist do not mutate state', () => { const initialState = deepFreeze([ { user_ids_string: '0,1,2', unread_message_ids: [1, 2, 3, 4, 5], }, { user_ids_string: '0,3,4', unread_message_ids: [4, 5], }, ]); const action = deepFreeze({ id: 1, type: EVENT_UPDATE_MESSAGE_FLAGS, all: false, allMessages: eg.makeMessagesState([]), messages: [6, 7], flag: 'read', op: 'add', }); const actualState = unreadHuddlesReducer(initialState, action, eg.plusReduxState); expect(actualState).toBe(initialState); }); test('if ids are in state remove them', () => { const initialState = deepFreeze([ { user_ids_string: '0,1,2', unread_message_ids: [1, 2, 3], }, { user_ids_string: '0,3,4', unread_message_ids: [4, 5], }, ]); const action = deepFreeze({ id: 1, type: EVENT_UPDATE_MESSAGE_FLAGS, all: false, allMessages: eg.makeMessagesState([]), messages: [3, 4, 5, 6], flag: 'read', op: 'add', }); const expectedState = [ { user_ids_string: '0,1,2', unread_message_ids: [1, 2], }, ]; const actualState = unreadHuddlesReducer(initialState, action, eg.plusReduxState); expect(actualState).toEqual(expectedState); }); test('when operation is "remove", add to unreads', () => { const initialState = deepFreeze([ { user_ids_string: '0,1,2', unread_message_ids: [1, 2, 3, 4, 100], }, ]); const action = deepFreeze({ id: 1, type: EVENT_UPDATE_MESSAGE_FLAGS, all: false, allMessages: eg.makeMessagesState([]), messages: [10, 11, 12], flag: 'read', op: 'remove', message_details: new Map([ [10, { type: 'private', user_ids: [1, 2].map(makeUserId) }], [11, { type: 'private', user_ids: [1, 2].map(makeUserId) }], [12, { type: 'private', user_ids: [1, 2, 3].map(makeUserId) }], ]), }); const expectedState = [ { user_ids_string: '0,1,2', unread_message_ids: [1, 2, 3, 4, 10, 11, 100], }, { user_ids_string: '0,1,2,3', unread_message_ids: [12], }, ]; const actualState = unreadHuddlesReducer( initialState, action, eg.reduxStatePlus({ realm: { ...eg.plusReduxState.realm, user_id: makeUserId(0) } }), ); expect(actualState).toEqual(expectedState); }); test('on "remove", drop any duplicates', () => { const initialState = deepFreeze([ { user_ids_string: '0,1,2', unread_message_ids: [1, 2, 3, 4] }, ]); const action = deepFreeze({ id: 1, type: EVENT_UPDATE_MESSAGE_FLAGS, all: false, allMessages: eg.makeMessagesState([]), messages: [2, 10], flag: 'read', op: 'remove', message_details: new Map([ [2, { type: 'private', user_ids: [1, 2].map(makeUserId) }], [10, { type: 'private', user_ids: [1, 2].map(makeUserId) }], ]), }); const expectedState = [{ user_ids_string: '0,1,2', unread_message_ids: [1, 2, 3, 4, 10] }]; const actualState = unreadHuddlesReducer( initialState, action, eg.reduxStatePlus({ realm: { ...eg.plusReduxState.realm, user_id: makeUserId(0) } }), ); expect(actualState).toEqual(expectedState); }); test('when "all" is true reset state', () => { const initialState = deepFreeze([ { user_ids_string: '0,1,2', unread_message_ids: [1, 2, 3, 4, 5], }, ]); const action = deepFreeze({ id: 1, type: EVENT_UPDATE_MESSAGE_FLAGS, all: true, allMessages: eg.makeMessagesState([]), messages: [], flag: 'read', op: 'add', }); const actualState = unreadHuddlesReducer(initialState, action, eg.plusReduxState); expect(actualState).toBe(NULL_ARRAY); }); }); }); ```
/content/code_sandbox/src/unread/__tests__/unreadHuddlesReducer-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
2,741
```javascript // @flow strict-local import * as React from 'react'; import { SafeAreaProvider } from 'react-native-safe-area-context'; import { useColorScheme } from 'react-native'; import { BRAND_COLOR } from '../styles'; import { useGlobalSelector } from '../react-redux'; import { getGlobalSettings, getIsHydrated } from '../directSelectors'; import { themeData } from '../styles/theme'; import { getThemeToUse } from '../settings/settingsSelectors'; type Props = {| +children: React.Node, |}; export default function ZulipSafeAreaProvider(props: Props): React.Node { // This background color appears in a few situations: // // * At startup, just after the loading screen, it covers the whole // screen as a brief flash, just a frame or so. // // * On iOS (where the stack-navigation transition animations have the // new screen slide in from and out to the right), when the animation // has all but the leftmost few pixels covered by the new screen, this // color replaces the remaining sliver of the old screen. In // particular this means at the very end of a push transition, and the // very beginning of a pop, particularly when the user pops by dragging // so that the animation goes at the pace of the user's finger. // // We can make this quirk virtually invisible by giving it the background // color used across the app. const osScheme = useColorScheme(); const backgroundColor = useGlobalSelector(state => { if (!getIsHydrated(state)) { // The only screen we'll be showing at this point is the loading // screen. Match that screen's background. return BRAND_COLOR; } const theme = getGlobalSettings(state).theme; const themeToUse = getThemeToUse(theme, osScheme); return themeData[themeToUse].backgroundColor; }); return <SafeAreaProvider style={{ backgroundColor }}>{props.children}</SafeAreaProvider>; } ```
/content/code_sandbox/src/boot/ZulipSafeAreaProvider.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
447
```javascript /* @flow strict-local */ import React, { PureComponent } from 'react'; import type { Node } from 'react'; import * as api from '../api'; import CompatibilityScreen from '../start/CompatibilityScreen'; type Props = $ReadOnly<{| children: Node, |}>; type State = {| compatibilityCheckFail: boolean, |}; export default class CompatibilityChecker extends PureComponent<Props, State> { state: State = { compatibilityCheckFail: false, }; componentDidMount() { api.checkCompatibility().then(res => { if (res.status === 400) { this.setState({ compatibilityCheckFail: true, }); } }); } render(): Node { const { compatibilityCheckFail } = this.state; return compatibilityCheckFail ? <CompatibilityScreen /> : this.props.children; } } ```
/content/code_sandbox/src/boot/CompatibilityChecker.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
176
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { useColorScheme } from 'react-native'; import { useGlobalSelector } from '../react-redux'; import { getGlobalSettings } from '../directSelectors'; import { themeData, ThemeContext } from '../styles/theme'; import ZulipStatusBar from '../common/ZulipStatusBar'; import { getThemeToUse } from '../settings/settingsSelectors'; type Props = $ReadOnly<{| children: Node, |}>; export default function ThemeProvider(props: Props): Node { const { children } = props; const theme = useGlobalSelector(state => getGlobalSettings(state).theme); const osScheme = useColorScheme(); const themeToUse = getThemeToUse(theme, osScheme); return ( <ThemeContext.Provider value={themeData[themeToUse]}> <ZulipStatusBar /> {children} </ThemeContext.Provider> ); } ```
/content/code_sandbox/src/boot/ThemeProvider.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
205
```javascript /* @flow strict-local */ import Immutable from 'immutable'; import { EVENT_UPDATE_MESSAGE_FLAGS } from '../../actionConstants'; import { reducer } from '../unreadModel'; import { setUnion } from '../../immutableUtils'; import { type UnreadState } from '../unreadModelTypes'; import * as eg from '../../__tests__/lib/exampleData'; import { initialState, makeUnreadState } from './unread-testlib'; describe('setUnion', () => { for (const [desc, xs, ys] of ([ ['empty', [], []], ['nonempty, empty', [1, 2], []], ['empty, nonempty', [], [1, 2]], ['in order', [1, 2], [3, 4]], ['reversed', [3, 4], [1, 2]], ['interleaved', [1, 3], [2, 4]], ['all dupes', [1, 2], [1, 2]], ['some dupes', [1, 2], [2, 3]], ['comparison is numeric, not lexicographic', [11], [2]], ]: [string, number[], number[]][])) { test(desc, () => { const expected = [...new Set([...xs, ...ys])].sort((a, b) => a - b); expect(setUnion(Immutable.List(xs), Immutable.List(ys)).toArray()).toEqual(expected); }); } }); // These are the tests corresponding to unreadStreamsReducer-test.js. // Ultimately we'll want to flip this way of organizing the tests, and // test the whole model together rather than streams/mentions/etc.; // but this way simplifies the conversion from the old tests. describe('stream substate', () => { // Summarize the state, for convenient comparison to expectations. // Specifically just turn the inner `Immutable.List`s into arrays, // to shorten writing the expected data. const summary = (state: UnreadState) => state.streams.map(perStream => perStream.map(perTopic => perTopic.toArray())); describe('RESET_ACCOUNT_DATA', () => { test('resets state to initial state', () => { const state = makeUnreadState(eg.plusReduxState, [eg.streamMessage()]); expect(state).not.toEqual(initialState); expect(reducer(state, eg.action.reset_account_data, eg.plusReduxState)).toEqual(initialState); }); }); describe('REGISTER_COMPLETE', () => { test('received data from "unread_msgs.streams" key replaces the current state ', () => { const message1 = eg.streamMessage({ id: 1 }); const action = eg.mkActionRegisterComplete({ unread_msgs: { streams: [ { stream_id: message1.stream_id, topic: message1.subject, unread_message_ids: [message1.id, 2], }, ], huddles: [], pms: [], mentions: [message1.id, 2, 3], }, }); // prettier-ignore expect(summary(reducer(initialState, action, eg.plusReduxState))).toEqual(Immutable.Map([ [message1.stream_id, Immutable.Map([[message1.subject, [1, 2]]])], ])); }); }); describe('EVENT_UPDATE_MESSAGE', () => { const mkAction = args => { const { message_ids, ...restArgs } = args; return eg.mkActionEventUpdateMessage({ user_id: eg.selfUser.user_id, message_id: message_ids[0], message_ids, edit_timestamp: 10000, ...restArgs, }); }; const baseState = makeUnreadState(eg.plusReduxState, [ eg.streamMessage({ stream_id: 123, subject: 'foo', id: 1 }), eg.streamMessage({ stream_id: 123, subject: 'foo', id: 2 }), eg.streamMessage({ stream_id: 123, subject: 'foo', id: 3 }), eg.streamMessage({ stream_id: 123, subject: 'foo', id: 4 }), eg.streamMessage({ stream_id: 456, subject: 'zzz', id: 6 }), eg.streamMessage({ stream_id: 456, subject: 'zzz', id: 7 }), eg.streamMessage({ stream_id: 123, subject: 'foo', id: 15 }), ]); test('(base state, for comparison)', () => { // prettier-ignore expect(summary(baseState)).toEqual(Immutable.Map([ [123, Immutable.Map([['foo', [1, 2, 3, 4, 15]]])], [456, Immutable.Map([['zzz', [6, 7]]])], ])); }); test('if topic/stream not updated, return original state', () => { const action = mkAction({ message_ids: [5], subject: 'foo' }); const state = reducer(baseState, action, eg.plusReduxState); expect(state.streams).toBe(baseState.streams); }); test('if topic updated, but no unreads, return original state', () => { const action = mkAction({ message_ids: [100], stream_id: 123, orig_subject: 'foo', subject: 'bar', }); const state = reducer(baseState, action, eg.plusReduxState); expect(state.streams).toBe(baseState.streams); }); test('if topic updated, move unreads', () => { const action = mkAction({ message_ids: [3, 4, 15], stream_id: 123, orig_subject: 'foo', subject: 'bar', }); const state = reducer(baseState, action, eg.plusReduxState); // prettier-ignore expect(summary(state)).toEqual(Immutable.Map([ [123, Immutable.Map([['foo', [1, 2]], ['bar', [3, 4, 15]]])], [456, Immutable.Map([['zzz', [6, 7]]])], ])); }); test('if stream updated, move unreads', () => { const action = mkAction({ message_ids: [3, 4, 15], stream_id: 123, new_stream_id: 456, orig_subject: 'foo', }); const state = reducer(baseState, action, eg.plusReduxState); // prettier-ignore expect(summary(state)).toEqual(Immutable.Map([ [123, Immutable.Map([['foo', [1, 2]]])], [456, Immutable.Map([['zzz', [6, 7]], ['foo', [3, 4, 15]]])], ])); }); test('if none left at old topic, prune', () => { const action = mkAction({ message_ids: [1, 2, 3, 4, 15], stream_id: 123, new_stream_id: 456, orig_subject: 'foo', }); const state = reducer(baseState, action, eg.plusReduxState); // prettier-ignore expect(summary(state)).toEqual(Immutable.Map([ [456, Immutable.Map([['zzz', [6, 7]], ['foo', [1, 2, 3, 4, 15]]])], ])); }); test('if moved to topic with existing unreads, ids stay sorted', () => { const action = mkAction({ message_ids: [3, 4, 15], stream_id: 123, new_stream_id: 456, orig_subject: 'foo', subject: 'zzz', }); const state = reducer(baseState, action, eg.plusReduxState); // prettier-ignore expect(summary(state)).toEqual(Immutable.Map([ [123, Immutable.Map([['foo', [1, 2]]])], [456, Immutable.Map([['zzz', [3, 4, 6, 7, 15]]])], ])); }); }); describe('EVENT_NEW_MESSAGE', () => { const action = eg.mkActionEventNewMessage; const baseState = makeUnreadState(eg.plusReduxState, [ eg.streamMessage({ id: 1, subject: 'some topic' }), ]); test('(base state, for comparison)', () => { // prettier-ignore expect(summary(baseState)).toEqual(Immutable.Map([ [eg.stream.stream_id, Immutable.Map([['some topic', [1]]])], ])); }); test('if message is not stream, return original state', () => { const state = reducer(baseState, action(eg.pmMessage({ id: 4 })), eg.plusReduxState); expect(state.streams).toBe(baseState.streams); }); test('if message has "read" flag, do not mutate state', () => { const state = reducer( baseState, action(eg.streamMessage({ sender: eg.selfUser, flags: ['read'] })), eg.plusReduxState, ); expect(state).toBe(baseState); }); test('if message id does not exist, append to state', () => { const state = reducer( baseState, action(eg.streamMessage({ id: 4, subject: 'some topic' })), eg.plusReduxState, ); // prettier-ignore expect(summary(state)).toEqual(Immutable.Map([ [eg.stream.stream_id, Immutable.Map([['some topic', [1, 4]]])], ])); }); test('known stream, new topic', () => { const message = eg.streamMessage({ id: 4, subject: 'another topic' }); const state = reducer(baseState, action(message), eg.plusReduxState); // prettier-ignore expect(summary(state)).toEqual(Immutable.Map([ [eg.stream.stream_id, Immutable.Map([ ['some topic', [1]], ['another topic', [4]], ])], ])); }); test('if stream with topic does not exist, append to state', () => { const otherStream = eg.makeStream(); const state = reducer( baseState, action(eg.streamMessage({ id: 4, stream: otherStream, subject: 'another topic' })), eg.plusReduxState, ); // prettier-ignore expect(summary(state)).toEqual(Immutable.Map([ [eg.stream.stream_id, Immutable.Map([['some topic', [1]]])], [otherStream.stream_id, Immutable.Map([['another topic', [4]]])], ])); }); }); describe('EVENT_UPDATE_MESSAGE_FLAGS', () => { const mkAction = args => { const { all = false, messages, message_details = new Map(), flag = 'read', op = 'add', } = args; return { id: 1, type: EVENT_UPDATE_MESSAGE_FLAGS, allMessages: eg.makeMessagesState([]), all, messages, message_details, flag, op, }; }; const streamAction = args => eg.mkActionEventNewMessage(eg.streamMessage(args)); const baseState = makeUnreadState(eg.plusReduxState, [ eg.streamMessage({ stream_id: 123, subject: 'foo', id: 1 }), eg.streamMessage({ stream_id: 123, subject: 'foo', id: 2 }), eg.streamMessage({ stream_id: 123, subject: 'foo', id: 3 }), eg.streamMessage({ stream_id: 234, subject: 'bar', id: 4 }), eg.streamMessage({ stream_id: 234, subject: 'bar', id: 5 }), ]); const messageDetailsEntry = (stream_id, topic) => ({ type: 'stream', stream_id, topic, }); test('(base state, for comparison)', () => { // prettier-ignore expect(summary(baseState)).toEqual(Immutable.Map([ [123, Immutable.Map([['foo', [1, 2, 3]]])], [234, Immutable.Map([['bar', [4, 5]]])], ])); }); test('when operation is "add" but flag is not "read" do not mutate state', () => { const action = mkAction({ messages: [1, 2, 3], flag: 'starred' }); expect(reducer(initialState, action, eg.plusReduxState)).toBe(initialState); }); test('if id does not exist do not mutate state', () => { const action = mkAction({ messages: [6, 7] }); expect(reducer(baseState, action, eg.plusReduxState)).toBe(baseState); }); test('if ids are in state remove them', () => { const action = mkAction({ messages: [3, 4, 5, 6] }); // prettier-ignore expect(summary(reducer(baseState, action, eg.plusReduxState))).toEqual(Immutable.Map([ [123, Immutable.Map([['foo', [1, 2]]])], ])); }); test("when removing, don't touch unaffected topics or streams", () => { const state = reducer( baseState, streamAction({ stream_id: 123, subject: 'qux', id: 7 }), eg.plusReduxState, ); // prettier-ignore expect(summary(state)).toEqual(Immutable.Map([ [123, Immutable.Map([['foo', [1, 2, 3]], ['qux', [7]]])], [234, Immutable.Map([['bar', [4, 5]]])], ])); const action = mkAction({ messages: [1, 2] }); const newState = reducer(state, action, eg.plusReduxState); // prettier-ignore expect(summary(newState)).toEqual(Immutable.Map([ [123, Immutable.Map([['foo', [3]], ['qux', [7]]])], [234, Immutable.Map([['bar', [4, 5]]])], ])); expect(newState.streams.get(123)?.get('qux')).toBe(state.streams.get(123)?.get('qux')); expect(newState.streams.get(234)).toBe(state.streams.get(234)); }); test('when operation is "remove", add stream messages to unreads', () => { const state = reducer( baseState, streamAction({ stream_id: 234, subject: 'bar', id: 100 }), eg.plusReduxState, ); // prettier-ignore expect(summary(state)).toEqual(Immutable.Map([ [123, Immutable.Map([['foo', [1, 2, 3]]])], [234, Immutable.Map([['bar', [4, 5, 100]]])], ])); const action = mkAction({ messages: [6, 42, 99, 7, 8], op: 'remove', message_details: new Map([ [99, messageDetailsEntry(123, 'foo')], [6, messageDetailsEntry(234, 'bar')], [8, messageDetailsEntry(234, 'bar')], [42, messageDetailsEntry(123, 'foo')], [7, messageDetailsEntry(234, 'baz')], ]), }); const newState = reducer(state, action, eg.plusReduxState); expect(summary(newState)).toEqual( Immutable.Map([ [123, Immutable.Map([['foo', [1, 2, 3, 42, 99]]])], [ 234, Immutable.Map([ ['bar', [4, 5, 6, 8, 100]], ['baz', [7]], ]), ], ]), ); }); test('on "remove", drop any duplicates', () => { const action = mkAction({ messages: [2, 6], op: 'remove', message_details: new Map([ [2, messageDetailsEntry(123, 'foo')], [6, messageDetailsEntry(123, 'foo')], ]), }); const newState = reducer(baseState, action, eg.plusReduxState); expect(summary(newState)).toEqual( Immutable.Map([ [123, Immutable.Map([['foo', [1, 2, 3, 6]]])], [234, Immutable.Map([['bar', [4, 5]]])], ]), ); }); test('when "all" is true reset state', () => { const action = mkAction({ messages: [], all: true }); expect(reducer(baseState, action, eg.plusReduxState).streams).toBe(initialState.streams); }); }); }); ```
/content/code_sandbox/src/unread/__tests__/unreadModel-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
3,646
```javascript /* @flow strict-local */ /** * The feature level at which we want to say "channel" instead of "stream". * * Outside a per-account context, check the feature level of the active * account, if there is one and it has server data. If there isn't an active * account or it doesn't have server data, just choose "channel" terminology * unconditionally. */ // TODO(server-9.0) simplify away // path_to_url#changes-in-zulip-90 export const streamChannelRenameFeatureLevel = 255; /** * A messageId: messageId map, from "stream" terminology to "channel". * * When appropriate (see streamChannelRenameFeatureLevel), use this to patch * UI-string data for all languages, so that the UI says "channel" instead * of "stream". See path_to_url . * * For example, use this to make a copy of messages_en that has * * "Notify stream": "Notify channel", * * instead of * * "Notify stream": "Notify stream", * "Notify channel": "Notify channel", * * and likewise for all the other languages. */ // TODO(server-9.0) simplify away export const streamChannelRenamesMap: {| [string]: string |} = { stream: 'channel', 'Notify stream': 'Notify channel', 'Who can access the stream?': 'Who can access the channel?', 'Only organization administrators and owners can edit streams.': 'Only organization administrators and owners can edit channels.', '{realmName} only allows organization administrators or owners to make public streams.': '{realmName} only allows organization administrators or owners to make public channels.', '{realmName} only allows organization moderators, administrators, or owners to make public streams.': '{realmName} only allows organization moderators, administrators, or owners to make public channels.', '{realmName} only allows full organization members, moderators, administrators, or owners to make public streams.': '{realmName} only allows full organization members, moderators, administrators, or owners to make public channels.', '{realmName} only allows organization members, moderators, administrators, or owners to make public streams.': '{realmName} only allows organization members, moderators, administrators, or owners to make public channels.', '{realmName} only allows organization administrators or owners to make private streams.': '{realmName} only allows organization administrators or owners to make private channels.', '{realmName} only allows organization moderators, administrators, or owners to make private streams.': '{realmName} only allows organization moderators, administrators, or owners to make private channels.', '{realmName} only allows full organization members, moderators, administrators, or owners to make private streams.': '{realmName} only allows full organization members, moderators, administrators, or owners to make private channels.', '{realmName} only allows organization members, moderators, administrators, or owners to make private streams.': '{realmName} only allows organization members, moderators, administrators, or owners to make private channels.', '{realmName} does not allow anybody to make web-public streams.': '{realmName} does not allow anybody to make web-public channels.', '{realmName} only allows organization owners to make web-public streams.': '{realmName} only allows organization owners to make web-public channels.', '{realmName} only allows organization administrators or owners to make web-public streams.': '{realmName} only allows organization administrators or owners to make web-public channels.', '{realmName} only allows organization moderators, administrators, or owners to make web-public streams.': '{realmName} only allows organization moderators, administrators, or owners to make web-public channels.', 'Cannot subscribe to stream': 'Cannot subscribe to channel', 'Stream #{name} is private.': 'Channel #{name} is private.', 'Please specify a stream.': 'Please specify a channel.', 'Please specify a valid stream.': 'Please specify a valid channel.', 'No messages in stream': 'No messages in channel', 'All streams': 'All channels', // 'No messages in topic: {streamAndTopic}': 'No messages in topic: {channelAndTopic}', 'Mute stream': 'Mute channel', 'Unmute stream': 'Unmute channel', '{username} will not be notified unless you subscribe them to this stream.': '{username} will not be notified unless you subscribe them to this channel.', 'Stream notifications': 'Channel notifications', 'No streams found': 'No channels found', 'Mark stream as read': 'Mark channel as read', 'Failed to mute stream': 'Failed to mute channel', 'Failed to unmute stream': 'Failed to unmute channel', 'Stream settings': 'Channel settings', 'Failed to show stream settings': 'Failed to show channel settings', 'You are not subscribed to this stream': 'You are not subscribed to this channel', 'Create new stream': 'Create new channel', Stream: 'Channel', 'Edit stream': 'Edit channel', 'Only organization admins are allowed to post to this stream.': 'Only organization admins are allowed to post to this channel.', 'Copy link to stream': 'Copy link to channel', 'Failed to copy stream link': 'Failed to copy channel link', 'A stream with this name already exists.': 'A channel with this name already exists.', Streams: 'Channels', }; ```
/content/code_sandbox/src/boot/streamChannelRenamesMap.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,157
```javascript /* @flow strict-local */ import { applyMiddleware, compose, createStore } from 'redux'; import type { Store } from 'redux'; // $FlowFixMe[untyped-import] import thunkMiddleware from 'redux-thunk'; // $FlowFixMe[untyped-import] import { createLogger } from 'redux-logger'; // $FlowFixMe[untyped-import] import createActionBuffer from 'redux-action-buffer'; import Immutable from 'immutable'; import { persistStore, autoRehydrate } from '../third/redux-persist'; import type { Config, Persistor } from '../third/redux-persist'; import { stringify, parse } from '../storage/replaceRevive'; import type { Action, GlobalState, ThunkExtras } from '../types'; import config from '../config'; import { REHYDRATE } from '../actionConstants'; import rootReducer from './reducers'; import CompressedAsyncStorage from '../storage/CompressedAsyncStorage'; import createMigration from '../redux-persist-migrate/index'; import { getGlobalSession, getGlobalSettings } from '../directSelectors'; import { migrations } from '../storage/migrations'; import type { Dispatch, GlobalThunkExtras } from '../reduxTypes'; if (process.env.NODE_ENV === 'development') { // Chrome dev tools for Immutable. // // To enable, press F1 from the Chrome dev tools to open the // settings. In the "Console" section, check "Enable custom // formatters". // // $FlowFixMe[untyped-import] const installDevTools = require('immutable-devtools'); // eslint-disable-line import/no-extraneous-dependencies, global-require installDevTools(Immutable); } // AsyncStorage.clear(); // use to reset storage during development /** * Properties on the global state which we explicitly choose not to persist. * * All properties on the global Redux state should appear either here or in * the lists of properties we do persist, below. */ // prettier-ignore export const discardKeys: $ReadOnlyArray<$Keys<GlobalState>> = [ 'alertWords', 'caughtUp', 'fetching', 'presence', 'session', 'topics', 'typing', 'userStatuses', ]; /** * Properties on the global state which we persist because they are local. * * These represent information that belongs to this device (and this * install of the app), where things wouldn't work right if we didn't * persist them. */ // prettier-ignore export const storeKeys: $ReadOnlyArray<$Keys<GlobalState>> = [ 'migrations', 'accounts', 'drafts', 'outbox', 'settings', ]; /** * Properties on the global state which we persist for caching's sake. * * These represent information for which the ground truth is on the * server, but which we persist locally so that we have it cached and * don't have to re-download it. */ // prettier-ignore export const cacheKeys: $ReadOnlyArray<$Keys<GlobalState>> = [ 'flags', 'messages', 'mute', 'mutedUsers', 'narrows', 'pmConversations', 'realm', 'streams', 'subscriptions', 'unread', 'userGroups', 'users', ]; /* eslint-disable no-use-before-define */ const thunkExtras: $Exact<ThunkExtras> = { getGlobalSession: () => getGlobalSession(store.getState()), getGlobalSettings: () => getGlobalSettings(store.getState()), }; const globalThunkExtras: $Exact<GlobalThunkExtras> = { // $FlowFixMe[escaped-generic] // $FlowFixMe[incompatible-type] /* $FlowFixMe[incompatible-cast] The `store` type isn't complete: in particular it ignores thunk actions. We're also using here the fact that the one function `store.dispatch` secretly plays both the role of our `GlobalDispatch` type and our `Dispatch` type... and that in the latter role, the PerAccountState that it acts on is the one belonging to the active account. TODO(#5006): We'll have to add more logic here when per-account and global state become distinct. */ activeAccountDispatch: action => (store.dispatch: Dispatch)(action), }; export const combinedThunkExtras: ThunkExtras & GlobalThunkExtras = { ...thunkExtras, ...globalThunkExtras, }; /** * Return a list of Redux middleware objects to use in our Redux store. * * See Redux docs on its "middleware API": * path_to_url */ function listMiddleware() { const result = [ // Delay ("buffer") actions until a REHYDRATE action comes through. // After dispatching the latter, this will go back and dispatch // all the buffered actions. See docs: // path_to_url createActionBuffer(REHYDRATE), // Handle the fancy "thunk" actions we often use, i.e. async // functions of `dispatch` and `state`. See docs: // path_to_url thunkMiddleware.withExtraArgument(combinedThunkExtras), ]; if (config.enableReduxLogging) { result.push( // Log each action to the console -- often handy in development. // See upstream docs: // path_to_url // and ours: // path_to_url#redux-logger createLogger({ duration: true, // Example options to add for more focused information, depending on // what you're investigating; see docs/howto/debugging.md (link above). // diff: true, // collapsed: true, // collapsed: (getState, action) => action.type !== 'MESSAGE_FETCH_COMPLETE', // predicate: (getState, action) => action.type === 'MESSAGE_FETCH_COMPLETE', }), ); } return result; } /** * The Redux store. We store nearly all application data here. * * For discussion, see: * * docs/architecture.md * * docs/architecture/realtime.md * * docs/background/recommended-reading.md */ // TODO: Represent thunk actions, etc. const store: Store<GlobalState, Action> = createStore( rootReducer, undefined, compose( // Invoke redux-persist-migrate with our migrations. createMigration(migrations, 'migrations'), // Various middleware; see `listMiddleware`. applyMiddleware(...listMiddleware()), // Handle all the boring parts of a REHYDRATE action from redux-persist, // where the live state just gets filled in with the corresponding parts // of the just-loaded state from disk. See upstream docs: // path_to_url#autorehydrateconfig autoRehydrate({ log: true }), ), ); /** * The config options to pass to redux-persist. * * See upstream docs: * path_to_url * * (Why v4? We studied v5 and determined it doesn't make sense for us to * use because its design choices on migrations don't support some important * kinds of migrations. See e5409c578.) */ const reduxPersistConfig: Config = { // The parts of our state for redux-persist to persist, // as keys on the top-level state. whitelist: [...storeKeys, ...cacheKeys], // Store data through our own wrapper for AsyncStorage, in particular // to get compression. storage: CompressedAsyncStorage, serialize: stringify, deserialize: parse, }; /** Invoke redux-persist. We do this once at launch. */ export const restore = (onFinished?: () => void): Persistor => persistStore(store, reduxPersistConfig, onFinished); export default store; ```
/content/code_sandbox/src/boot/store.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,633
```javascript /* @flow strict-local */ import React, { useEffect } from 'react'; import type { Node } from 'react'; import type { Dispatch } from '../reduxTypes'; import { observeStore } from '../redux'; import { Provider } from '../react-redux'; import * as logging from '../utils/logging'; import { getHasAuth, getAccount, tryGetActiveAccountState } from '../selectors'; import store, { restore } from './store'; import { registerAndStartPolling } from '../events/eventActions'; import { sendOutbox } from '../outbox/outboxActions'; import { initNotifications } from '../notification/notifTokens'; type Props = $ReadOnly<{| children: Node, |}>; export default function StoreProvider(props: Props): Node { useEffect( () => observeStore( store, // onChange will fire when this value changes state => { const perAccountState = tryGetActiveAccountState(state); if (!perAccountState) { return undefined; } return getAccount(perAccountState).zulipVersion; }, zulipVersion => { // TODO(#5005): This is for the *active* account; that may not be // the one a given piece of code is working with! // // On fetch, we'll have called this already before entering the // reducers, so this will be redundant. But on switching accounts, // this is the call that will make the change. logging.setTagsFromServerVersion(zulipVersion); }, ), [], ); useEffect(() => { restore(() => { (async () => { const hasAuth = getHasAuth(store.getState()); // The `store` type isn't complete: it ignores thunk actions, etc. // $FlowFixMe[incompatible-type] const dispatch: Dispatch = store.dispatch; // Init right away if there's an active, logged-in account. // NB `getInitialRouteInfo` depends intimately on this behavior. if (hasAuth) { await dispatch(registerAndStartPolling()); // TODO(#3881): Lots of issues with outbox sending dispatch(sendOutbox()); dispatch(initNotifications()); } })(); }); }, []); return <Provider store={store}>{props.children}</Provider>; } ```
/content/code_sandbox/src/boot/StoreProvider.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
493
```javascript /* @flow strict-local */ import type { Action, PerAccountApplicableAction, GlobalState, MigrationsState } from '../types'; import { dubPerAccountState } from '../reduxTypes'; import { isPerAccountApplicableAction } from '../actionTypes'; import accounts from '../account/accountsReducer'; import alertWords from '../alertWords/alertWordsReducer'; import caughtUp from '../caughtup/caughtUpReducer'; import drafts from '../drafts/draftsReducer'; import fetching from '../chat/fetchingReducer'; import flags from '../chat/flagsReducer'; import narrows from '../chat/narrowsReducer'; import messages from '../message/messagesReducer'; import { reducer as mute } from '../mute/muteModel'; import mutedUsers from '../mute/mutedUsersReducer'; import outbox from '../outbox/outboxReducer'; import { reducer as pmConversations } from '../pm-conversations/pmConversationsModel'; import { reducer as presence } from '../presence/presenceModel'; import realm from '../realm/realmReducer'; import session from '../session/sessionReducer'; import settings from '../settings/settingsReducer'; import streams from '../streams/streamsReducer'; import subscriptions from '../subscriptions/subscriptionsReducer'; import topics from '../topics/topicsReducer'; import typing from '../typing/typingReducer'; import { reducer as unread } from '../unread/unreadModel'; import userGroups from '../user-groups/userGroupsReducer'; import { reducer as userStatuses } from '../user-statuses/userStatusesModel'; import users from '../users/usersReducer'; // The `Object.freeze` is to work around a Flow issue: // path_to_url#issuecomment-695064325 const migrations = (state: MigrationsState = Object.freeze({})): MigrationsState => state; /** * Apply a sub-reducer, with perf logging if enabled. * * The `globalState` argument is the "global" state relative to this * sub-reducer: so type GS is `GlobalState` for a global reducer, and * `PerAccountState` for a per-account reducer. */ function applyReducer<GS, A: Action, Key: $Keys<GS> & $Keys<GlobalState>, State>( key: Key, reducer: (void | State, A, GS) => State, state: void | State, action: A, globalState: void | GS, ): State { /* $FlowFixMe[incompatible-type] - We make a small lie about the type, pretending that globalState is not void. This is OK because it's only ever void at the initialization action, and no reducer should do anything there other than return its initial state, so in particular no reducer should even look at globalState. Then on the other hand it's helpful because we want each reducer that ever does use the globalState parameter to require it -- so that Flow can help us be sure to pass it at the reducer's many other call sites, in tests. That means it has to be `globalState: GS`, not `globalState : void | GS`. */ const castGlobalState: GS = globalState; const nextState = reducer(state, action, castGlobalState); return nextState; } // Based on Redux upstream's combineReducers. export default (globalState: void | GlobalState, origAction: Action): GlobalState => { let nextPerAccountState = globalState; if (!nextPerAccountState) { // Initialize the per-account state. This must be the store // initialization action, because the previous state is void. /* $FlowFixMe[incompatible-type]: */ const action: PerAccountApplicableAction = origAction; // prettier-ignore nextPerAccountState = { alertWords: applyReducer('alertWords', alertWords, undefined, action, undefined), caughtUp: applyReducer('caughtUp', caughtUp, undefined, action, undefined), drafts: applyReducer('drafts', drafts, undefined, action, undefined), fetching: applyReducer('fetching', fetching, undefined, action, undefined), flags: applyReducer('flags', flags, undefined, action, undefined), messages: applyReducer('messages', messages, undefined, action, undefined), narrows: applyReducer('narrows', narrows, undefined, action, undefined), mute: applyReducer('mute', mute, undefined, action, undefined), mutedUsers: applyReducer('mutedUsers', mutedUsers, undefined, action, undefined), outbox: applyReducer('outbox', outbox, undefined, action, undefined), pmConversations: applyReducer('pmConversations', pmConversations, undefined, action, undefined), presence: applyReducer('presence', presence, undefined, action, undefined), realm: applyReducer('realm', realm, undefined, action, undefined), streams: applyReducer('streams', streams, undefined, action, undefined), subscriptions: applyReducer('subscriptions', subscriptions, undefined, action, undefined), topics: applyReducer('topics', topics, undefined, action, undefined), typing: applyReducer('typing', typing, undefined, action, undefined), unread: applyReducer('unread', unread, undefined, action, undefined), userGroups: applyReducer('userGroups', userGroups, undefined, action, undefined), userStatuses: applyReducer('userStatuses', userStatuses, undefined, action, undefined), users: applyReducer('users', users, undefined, action, undefined), }; } else if (isPerAccountApplicableAction(origAction)) { // Update the per-account state, for this PerAccountApplicableAction. /* $FlowFixMe[incompatible-type]: TODO teach Flow that isPerAccountApplicableAction checks this */ const action: PerAccountApplicableAction = origAction; let state = dubPerAccountState(nextPerAccountState); // prettier-ignore state = { /* $FlowFixMe[not-an-object]: TODO(#5006) this fixme should go away when PerAccountState is no longer opaque */ ...state, alertWords: applyReducer('alertWords', alertWords, state.alertWords, action, state), caughtUp: applyReducer('caughtUp', caughtUp, state.caughtUp, action, state), drafts: applyReducer('drafts', drafts, state.drafts, action, state), fetching: applyReducer('fetching', fetching, state.fetching, action, state), flags: applyReducer('flags', flags, state.flags, action, state), messages: applyReducer('messages', messages, state.messages, action, state), narrows: applyReducer('narrows', narrows, state.narrows, action, state), // mute is below mutedUsers: applyReducer('mutedUsers', mutedUsers, state.mutedUsers, action, state), outbox: applyReducer('outbox', outbox, state.outbox, action, state), pmConversations: applyReducer('pmConversations', pmConversations, state.pmConversations, action, state), presence: applyReducer('presence', presence, state.presence, action, state), realm: applyReducer('realm', realm, state.realm, action, state), streams: applyReducer('streams', streams, state.streams, action, state), subscriptions: applyReducer('subscriptions', subscriptions, state.subscriptions, action, state), topics: applyReducer('topics', topics, state.topics, action, state), typing: applyReducer('typing', typing, state.typing, action, state), unread: applyReducer('unread', unread, state.unread, action, state), userGroups: applyReducer('userGroups', userGroups, state.userGroups, action, state), userStatuses: applyReducer('userStatuses', userStatuses, state.userStatuses, action, state), users: applyReducer('users', users, state.users, action, state), }; // mute must come after streams, for REGISTER_COMPLETE events state.mute = applyReducer('mute', mute, state.mute, action, state); nextPerAccountState = state; } const state = globalState; const action = origAction; // prettier-ignore const nextState = { ...nextPerAccountState, // TODO(#5006): These mix together per-account and global state. session: applyReducer('session', session, state?.session, action, state), settings: applyReducer('settings', settings, state?.settings, action, state), // All other state. migrations: applyReducer('migrations', migrations, state?.migrations, action, state), accounts: applyReducer('accounts', accounts, state?.accounts, action, state), }; if (state && Object.keys(nextState).every(key => nextState[key] === state[key])) { return state; } return nextState; }; ```
/content/code_sandbox/src/boot/reducers.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,895
```javascript // @flow strict-local import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; import type { Node } from 'react'; import { AccessibilityInfo, View, LayoutAnimation, Platform, useColorScheme } from 'react-native'; import NetInfo from '@react-native-community/netinfo'; import { SafeAreaView } from 'react-native-safe-area-context'; import type { ViewProps } from 'react-native/Libraries/Components/View/ViewPropTypes'; import type { DimensionValue } from 'react-native/Libraries/StyleSheet/StyleSheetTypes'; import * as logging from '../utils/logging'; import { useDispatch, useGlobalSelector } from '../react-redux'; import { getGlobalSession, getGlobalSettings } from '../directSelectors'; import { getThemeToUse } from '../settings/settingsSelectors'; import { useHasStayedTrueForMs } from '../reactUtils'; import type { JSONableDict } from '../utils/jsonable'; import { createStyleSheet } from '../styles'; import ZulipTextIntl from '../common/ZulipTextIntl'; import type { ViewStylePropWithout } from '../reactNativeUtils'; import ZulipStatusBar from '../common/ZulipStatusBar'; import type { ThemeName } from '../reduxTypes'; import { TranslationContext } from './TranslationProvider'; import { appOnline } from '../session/sessionActions'; function useUpdateSessionOnConnectivityChange() { const dispatch = useDispatch(); useEffect(() => { NetInfo.configure({ // This is the default, as of 6.0.0, but // `useShouldShowUncertaintyNotice` depends on this value being // stable. reachabilityRequestTimeout: 15 * 1000, }); return NetInfo.addEventListener(netInfoState => { dispatch( appOnline( // From reading code at @react-native-community/net-info v6.0.0 (the // docs and types don't really give these answers): // // This will be `null` on both platforms while the first known value // of `true` or `false` is being shipped across the asynchronous RN // bridge. // // On Android, it shouldn't otherwise be `null`. The value is set to the // result of an Android function that only returns a boolean: // path_to_url#isConnected() // // On iOS, this can also be `null` while the app asynchronously // evaluates whether a network change should cause this to go from // `false` to `true`. Read on for details (gathered from // src/internal/internetReachability.ts in the library). // // 1. A request loop is started. A HEAD request is made to // path_to_url with a timeout of // 15s (`reachabilityRequestTimeout`), to see if the Internet is // reachable. // - If the `fetch` succeeds and a 204 is received, this will be // made `true`. We'll then sleep for 60s before making the // request again. // - If the `fetch` succeeds and a 204 is not received, or if the // fetch fails, or if the timeout expires, this will be made // `false`. We'll then sleep for only 5s before making the // request again. // 2. The request loop is interrupted if we get a // 'netInfo.networkStatusDidChange' event from the library's // native code, signaling a change in the network state. If that // change would make `netInfoState.type` become or remain // something good (i.e., not 'none' or 'unknown'), and this // (`.isInternetReachable`) is currently `false`, then this will // be made `null`, and the request loop described above will // start again. // // (Several of those parameters are configurable -- timeout durations, // URL, etc.) netInfoState.isInternetReachable, ), ); }); }, [dispatch]); } function useShouldShowUncertaintyNotice(): boolean { const isOnline = useGlobalSelector(state => getGlobalSession(state).isOnline); const result = useHasStayedTrueForMs( // See note in `SessionState` for what this means. isOnline === null, // A decently long time, much longer than it takes to send `true` or // `false` over the RN bridge. // // Also, one second longer than what we set for // `reachabilityRequestTimeout` in NetInfo's config (15s), which is the // longest `isOnline` can be `null` on iOS in an expected case. For // details, see the comment where we dispatch the action to change // `isOnline`. // // If this time passes and `isOnline` is still `null`, we should treat // it as a bug and investigate. 16 * 1000, ); useEffect(() => { if (result) { NetInfo.fetch().then(state => { logging.warn( 'Failed to determine Internet reachability in a reasonable time', // `state`, being inexact, might have unknown properties that // aren't JSONable. Hopefully Sentry would just drop parts that // aren't JSONable instead of panicking or dropping everything. // $FlowFixMe[incompatible-cast] (state: JSONableDict), ); }); } }, [result]); return result; } const OfflineNoticeContext = React.createContext({ isNoticeVisible: false, noticeContentAreaHeight: 0, }); type ProviderProps = {| +children: Node, |}; const backgroundColorForTheme = (theme: ThemeName): string => // TODO(redesign): Choose these more intentionally; these are just the // semitransparent HALF_COLOR flattened with themeData.backgroundColor. // See path_to_url#issuecomment-1282859332 theme === 'light' ? '#bfbfbf' : '#50565e'; /** * Shows a notice if the app is working in offline mode. * * Shows a different notice if we've taken longer than we expect to * determine Internet reachability. IOW, if the user sees this, there's a * bug. * * Shows nothing if the Internet is reachable. * * The notice is a banner at the top of the screen. All screens should * render a OfflineNoticePlaceholder so that banner doesn't hide any of the * screen's content; see there for details. */ export function OfflineNoticeProvider(props: ProviderProps): Node { const theme = useGlobalSelector(state => getGlobalSettings(state).theme); const osScheme = useColorScheme(); const themeToUse = getThemeToUse(theme, osScheme); const _ = useContext(TranslationContext); const isOnline = useGlobalSelector(state => getGlobalSession(state).isOnline); const shouldShowUncertaintyNotice = useShouldShowUncertaintyNotice(); useUpdateSessionOnConnectivityChange(); // Use local UI state for isNoticeVisible instead of computing directly as // a `const`, so we can apply LayoutAnimation.configureNext to just the // visibility state change, instead of, e.g., all layout changes // potentially caused by an APP_ONLINE action. const [isNoticeVisible, setIsNoticeVisible] = useState( isOnline === false || shouldShowUncertaintyNotice, ); useEffect(() => { setIsNoticeVisible(oldValue => { const newValue = isOnline === false || shouldShowUncertaintyNotice; // Don't animate on Android, at least for now. The animation seems to // get stuck: // path_to_url#narrow/stream/48-mobile/topic/android.20.22No.20internet.20connection.22/near/1468556 // If we want to try again, see the commit that removed the Android // animation, for ideas about handling some bad interactions with // react-native-screens. if (Platform.OS === 'ios' && oldValue !== newValue) { // Animate two layout changes that happen at the same time, because // they are triggered by the same render pass: // - the entrance / exit of the offline notice // - the corresponding change in OfflineNoticePlaceholder's height // They're triggered by the same render pass because the same piece // of state, isNoticeVisible, controls both layouts. The placeholder // subscribes to that state with React.useContext. LayoutAnimation.configureNext({ ...LayoutAnimation.Presets.easeInEaseOut, // Enter slowly to give bad, possibly unexpected news. Leave quickly // to give good, hoped-for news. duration: newValue ? 1000 : 300, }); } return newValue; }); }, [isOnline, shouldShowUncertaintyNotice, _]); // Announce connectivity changes to screen-reader users. const haveAnnouncedOffline = useRef(false); const haveAnnouncedUncertain = useRef(false); useEffect(() => { // When announcing, mention Zulip so this doesn't sound like an // announcement from the OS. We don't speak for the OS, and the OS might // disagree about the connectivity state, e.g., because we're wrong // about Zulip's connectivity or because a connection problem somehow // affects Zulip but not other apps. // // (The banner element shouldn't have to mention Zulip because it's // already clear that it's from Zulip: it's part of the UI we draw, as // traversed visually or by a screen reader. The OS should make it clear // when you're traversing a given app's UI, e.g., so an app can't trick // you into giving it sensitive data that you meant for the OS or // another app.) if (shouldShowUncertaintyNotice && !haveAnnouncedUncertain.current) { // TODO(react-native-68): Use announceForAccessibilityWithOptions to // queue this behind any in-progress announcements AccessibilityInfo.announceForAccessibility(_('Zulips Internet connection is uncertain.')); haveAnnouncedUncertain.current = true; } if (isOnline === false && (!haveAnnouncedOffline.current || haveAnnouncedUncertain.current)) { AccessibilityInfo.announceForAccessibility(_('Zulip is offline.')); haveAnnouncedOffline.current = true; haveAnnouncedUncertain.current = false; } else if ( isOnline === true && (haveAnnouncedOffline.current || haveAnnouncedUncertain.current) ) { // TODO(react-native-68): Use announceForAccessibilityWithOptions to // queue this behind any in-progress announcements AccessibilityInfo.announceForAccessibility(_('Zulip is online.')); haveAnnouncedOffline.current = false; haveAnnouncedUncertain.current = false; } }, [isOnline, shouldShowUncertaintyNotice, _]); const styles = useMemo( () => createStyleSheet({ flex1: { flex: 1 }, noticeSurface: { position: 'absolute', // Whether the notice is visible or tucked away above the window. // // (Just as we discovered in 3fa7a7f10 with the lightbox, it seems // the Animated API wouldn't let us do a translate-transform // animation with a percentage; that's issue // path_to_url . // So we use LayoutAnimation, which is probably better anyway // because it lets us animate layout changes at the native layer, // and so won't drop frames when the JavaScript thread is busy.) ...(isNoticeVisible ? { top: 0 } : { bottom: '100%' }), zIndex: 1, width: '100%', // If changing, also change the status bar color in // OfflineNoticePlaceholder. backgroundColor: backgroundColorForTheme(themeToUse), justifyContent: 'center', alignItems: 'center', }, noticeContentArea: { width: '100%', alignItems: 'center', justifyContent: 'center', paddingVertical: 4, }, noticeText: { fontSize: 14 }, }), [isNoticeVisible, themeToUse], ); /** * Our best guess at the computed height of the content area in the * layout caused by this render. * * Pass this to OfflineNoticePlaceholder so it reserves the right amount * of height for the notice when the notice is visible. * * If wrong, expect OfflineNoticePlaceholder to visibly have the wrong * height for a moment but then recover quickly. */ // It's the computed height from the *last* render (or zero if this is the // first render), using the onLayout prop. So, to make a good guess, we // try to avoid changes to the computed height: // - When the notice is offscreen, we set the text to match the more // likely message when the notice comes onscreen, namely the "offline" // message. That means it'll say "offline" when the state is actually // "online", but that's OK because it'll be offscreen. // - When the notice is onscreen, it'll show either an "offline" message // or an "uncertain" message. It's possible but unlikely that just one // message would wrap onto two lines, inviting errors by 0.5x or 2x. // To keep that possibility in check, we don't make either message // very detailed, so they'd be similar in length in any language, and // hopefully both short enough to stay on one line, even with a // large-ish system font setting. const [noticeContentAreaHeight, setNoticeContentAreaHeight] = useState(0); const handleNoticeContentAreaLayoutChange = useCallback(event => { setNoticeContentAreaHeight(event.nativeEvent.layout.height); }, []); const contextValue = useMemo( () => ({ isNoticeVisible, noticeContentAreaHeight }), [isNoticeVisible, noticeContentAreaHeight], ); return ( <View style={styles.flex1}> <SafeAreaView mode="padding" edges={['top', 'right', 'left']} style={styles.noticeSurface} { // Just as we do in the visual UI, offer screen readers a way to // check the connectivity state on demand: the notice will either // be present, with explanatory text, or absent. To make it // "absent" for screen readers, we make this view and its children // unfocusable. // // See also our AccessibilityInfo.announceForAccessibility call, // where we announce online/offline changes so the user doesn't // have to poll for the connectivity state by checking for // presence/absence of this view. ...(isNoticeVisible ? { // Group descendants into a single selectable component. Its // text will automatically be the notice text (confirmed // experimentally), so no need for an `accessibilityLabel`. accessible: true, } : { accessible: false, accessibilityElementsHidden: true, importantForAccessibility: 'no-hide-descendants', }) } > <View onLayout={handleNoticeContentAreaLayoutChange} style={styles.noticeContentArea}> <ZulipTextIntl style={styles.noticeText} text={ shouldShowUncertaintyNotice ? 'Please check your Internet connection' : 'No Internet connection' } /> </View> </SafeAreaView> <View style={styles.flex1}> <OfflineNoticeContext.Provider value={contextValue}> {props.children} </OfflineNoticeContext.Provider> </View> </View> ); } type PlaceholderProps = $ReadOnly<{| ...ViewProps, style?: ViewStylePropWithout<{| // Let this component do its job; don't mess with its height. height: DimensionValue, minHeight: DimensionValue, maxHeight: DimensionValue, |}>, |}>; /** * Empty View that expands from 0 height to give room to the offline notice. * * On every screen, render one of these on the surface that occupies the top * of the screen in the Y direction (e.g., an app bar), inside that * surface's top-inset padding. * * The offline notice will be overlaid on top of that surface in the Z * direction, blocking part of it from view including its top-inset padding. * Use this placeholder to push the content on the underlying surface * downward in the Y direction, just enough so it doesn't get hidden by the * offline notice's content and only when the offline notice is actually * onscreen. * * On Android, where the app doesn't draw underneath the status bar, this * also colors the status bar's background to match the notice. * * Must have the OfflineNoticeProvider above it in the tree. */ export function OfflineNoticePlaceholder(props: PlaceholderProps): Node { const theme = useGlobalSelector(state => getGlobalSettings(state).theme); const osScheme = useColorScheme(); const themeToUse = getThemeToUse(theme, osScheme); const { style: callerStyle } = props; const { isNoticeVisible, noticeContentAreaHeight } = useContext(OfflineNoticeContext); const style = useMemo( () => [ { height: isNoticeVisible ? noticeContentAreaHeight : 0, width: '100%', backgroundColor: 'transparent', }, callerStyle, ], [isNoticeVisible, noticeContentAreaHeight, callerStyle], ); return ( <> { // On Android, have the notice's background color extend through the // status bar. We do this here instead of in OfflineNoticeProvider // so our instruction to the status bar doesn't get clobbered by // another instruction more leafward than OfflineNoticeProvider. isNoticeVisible && ( <ZulipStatusBar // Should match the notice's surface; see OfflineNoticeProvider. backgroundColor={backgroundColorForTheme(themeToUse)} /> ) } <View style={style} /> </> ); } ```
/content/code_sandbox/src/boot/OfflineNoticeProvider.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
3,998
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { useGlobalSelector } from '../react-redux'; import { getIsHydrated } from '../selectors'; import FullScreenLoading from '../common/FullScreenLoading'; type Props = $ReadOnly<{| children: Node, |}>; /** * Where we prevent everything from rendering while waiting for rehydration. */ export default function StoreHydratedGate(props: Props): Node { const { children } = props; const isHydrated = useGlobalSelector(getIsHydrated); return isHydrated ? children : <FullScreenLoading />; } ```
/content/code_sandbox/src/boot/StoreHydratedGate.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
138
```javascript /* @flow strict-local */ import * as React from 'react'; import { Text } from 'react-native'; import { IntlProvider, IntlContext } from 'react-intl'; import type { IntlShape } from 'react-intl'; import type { GetText } from '../types'; import { useGlobalSelector } from '../react-redux'; import { getGlobalSettings } from '../selectors'; import messagesByLanguage from '../i18n/messagesByLanguage'; import { getZulipFeatureLevel, tryGetActiveAccountState } from '../account/accountsSelectors'; import { objectFromEntries } from '../jsBackport'; import { objectEntries } from '../flowPonyfill'; import { streamChannelRenameFeatureLevel, streamChannelRenamesMap, } from './streamChannelRenamesMap'; import { getHaveServerData } from '../haveServerDataSelectors'; // $FlowFixMe[incompatible-type] could put a well-typed mock value here, to help write tests export const TranslationContext: React.Context<GetText> = React.createContext(undefined); const makeGetText = (intl: IntlShape): GetText => { const _ = (message, values_) => { const text = typeof message === 'object' ? message.text : message; const values = typeof message === 'object' ? message.values : values_; return intl.formatMessage( { id: text, // If you see this in dev, it means there's a user-facing // string that hasn't been added to // static/translations/messages_en.json. Please add it! :) defaultMessage: process.env.NODE_ENV === 'development' ? `UNTRANSLATED${text}UNTRANSLATED` : text, }, values, ); }; _.intl = intl; return _; }; /** * Consume IntlProvider's context, and provide it in a different shape. * * See the `GetTypes` type for why we like the new shape. */ function TranslationContextTranslator(props: {| +children: React.Node |}): React.Node { const intlContextValue = React.useContext(IntlContext); return ( <TranslationContext.Provider value={makeGetText(intlContextValue)}> {props.children} </TranslationContext.Provider> ); } type Props = $ReadOnly<{| children: React.Node, |}>; /** * Like messagesByLanguage but with "channel" terminology instead of "stream". */ const messagesByLanguageRenamed = objectFromEntries( objectEntries(messagesByLanguage).map(([language, messages]) => [ language, objectFromEntries( objectEntries(messages).map(([messageId, message]) => { const renamedMessageId = streamChannelRenamesMap[messageId]; if (renamedMessageId == null) { return [messageId, message]; } const renamedMessage = messages[renamedMessageId]; if (renamedMessage === renamedMessageId && message !== messageId) { // The newfangled "channel" string hasn't been translated yet, but // the older "stream" string has. Consider falling back to that. if (/^en($|-)/.test(language)) { // The language is a variety of English. Prefer the newer // terminology, even though awaiting translation. (Most of our // strings don't change at all between one English and another.) return [messageId, renamedMessage]; } // Use the translation we have, even of the older terminology. // (In many languages the translations have used an equivalent // of "channel" all along anyway.) return [messageId, message]; } return [messageId, renamedMessage]; }), ), ]), ); export default function TranslationProvider(props: Props): React.Node { const { children } = props; const language = useGlobalSelector(state => getGlobalSettings(state).language); const activeAccountState = useGlobalSelector(tryGetActiveAccountState); // TODO(server-9.0) remove "stream" terminology const effectiveMessagesByLanguage = activeAccountState == null || !getHaveServerData(activeAccountState) || getZulipFeatureLevel(activeAccountState) >= streamChannelRenameFeatureLevel ? messagesByLanguageRenamed : messagesByLanguage; return ( <IntlProvider locale={language} textComponent={Text} messages={effectiveMessagesByLanguage[language]} > <TranslationContextTranslator>{children}</TranslationContextTranslator> </IntlProvider> ); } ```
/content/code_sandbox/src/boot/TranslationProvider.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
965
```javascript /* @flow strict-local */ import reducers from '../reducers'; import { discardKeys, storeKeys, cacheKeys } from '../store'; import * as eg from '../../__tests__/lib/exampleData'; describe('reducers', () => { test('reducers return the default states on unknown action', () => { // $FlowFixMe[incompatible-call] bogus action object expect(() => reducers({}, { type: 'UNKNOWN_ACTION' })).not.toThrow(); }); test('every reducer is listed in config as "discard", "store" or "cache"', () => { const configKeys = [...discardKeys, ...storeKeys, ...cacheKeys]; const reducerKeys = Object.keys(eg.baseReduxState); expect(configKeys.sort()).toEqual(reducerKeys.sort()); }); }); ```
/content/code_sandbox/src/boot/__tests__/reducers-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
165
```javascript /* @flow strict-local */ import React, { PureComponent } from 'react'; import type { Node, ComponentType } from 'react'; import { AppState, View } from 'react-native'; import * as ScreenOrientation from 'expo-screen-orientation'; import type { GlobalDispatch, Orientation as OrientationT } from '../types'; import { createStyleSheet } from '../styles'; import { connectGlobal } from '../react-redux'; import { handleInitialNotification } from '../notification/notifOpen'; import NotificationListener from '../notification/NotificationListener'; import { ShareReceivedListener, handleInitialShare } from '../sharing'; import { appOrientation } from '../actions'; import PresenceHeartbeat from '../presence/PresenceHeartbeat'; const styles = createStyleSheet({ wrapper: { flex: 1, flexDirection: 'column', alignItems: 'stretch', }, }); type OuterProps = $ReadOnly<{| children: Node, |}>; type SelectorProps = $ReadOnly<{||}>; type Props = $ReadOnly<{| ...OuterProps, // from `connectGlobal` dispatch: GlobalDispatch, ...SelectorProps, |}>; type OrientationLookup = {| [expoKey: $Values<typeof ScreenOrientation.Orientation>]: OrientationT, |}; const orientationLookup: OrientationLookup = { [ScreenOrientation.Orientation.UNKNOWN]: 'PORTRAIT', [ScreenOrientation.Orientation.PORTRAIT_UP]: 'PORTRAIT', [ScreenOrientation.Orientation.PORTRAIT_DOWN]: 'PORTRAIT', [ScreenOrientation.Orientation.LANDSCAPE_LEFT]: 'LANDSCAPE', [ScreenOrientation.Orientation.LANDSCAPE_RIGHT]: 'LANDSCAPE', }; class AppEventHandlersInner extends PureComponent<Props> { handleOrientationChange = (event: ScreenOrientation.OrientationChangeEvent) => { const { dispatch } = this.props; const { orientation } = event.orientationInfo; dispatch(appOrientation(orientationLookup[orientation])); }; notificationListener = new NotificationListener(this.props.dispatch); shareListener = new ShareReceivedListener(); handleMemoryWarning = () => { // Release memory here }; componentDidMount() { const { dispatch } = this.props; dispatch(handleInitialNotification()); handleInitialShare(); AppState.addEventListener('memoryWarning', this.handleMemoryWarning); // The listener doesn't seem to fire in RN's "Debug with Chrome" mode. ScreenOrientation.addOrientationChangeListener(this.handleOrientationChange); this.notificationListener.start(); this.shareListener.start(); } componentWillUnmount() { AppState.removeEventListener('memoryWarning', this.handleMemoryWarning); ScreenOrientation.removeOrientationChangeListeners(); this.notificationListener.stop(); this.shareListener.stop(); } render() { return ( <> <PresenceHeartbeat /> <View style={styles.wrapper}>{this.props.children}</View> </> ); } } const AppEventHandlers: ComponentType<OuterProps> = connectGlobal()(AppEventHandlersInner); export default AppEventHandlers; ```
/content/code_sandbox/src/boot/AppEventHandlers.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
612
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import { SafeAreaView } from 'react-native-safe-area-context'; import type { RouteProp } from '../react-navigation'; import type { MainTabsNavigationProp } from './MainTabsScreen'; import { useDispatch } from '../react-redux'; import { HOME_NARROW, MENTIONED_NARROW, STARRED_NARROW } from '../utils/narrow'; import { TopTabButton, TopTabButtonGeneral } from '../nav/TopTabButton'; import UnreadCards from '../unread/UnreadCards'; import { doNarrow } from '../actions'; import IconUnreadMentions from '../nav/IconUnreadMentions'; import { BRAND_COLOR, createStyleSheet } from '../styles'; import LoadingBanner from '../common/LoadingBanner'; import ServerCompatBanner from '../common/ServerCompatBanner'; import ServerNotifsDisabledBanner from '../common/ServerNotifsDisabledBanner'; import { OfflineNoticePlaceholder } from '../boot/OfflineNoticeProvider'; import ServerNotifsExpiringBanner from '../common/ServerNotifsExpiringBanner'; const styles = createStyleSheet({ wrapper: { flex: 1, flexDirection: 'column', }, iconList: { justifyContent: 'space-between', flexDirection: 'row', }, }); type Props = $ReadOnly<{| navigation: MainTabsNavigationProp<'home'>, route: RouteProp<'home', void>, |}>; export default function HomeScreen(props: Props): Node { const { navigation } = props; const dispatch = useDispatch(); return ( <SafeAreaView mode="padding" edges={['top']} style={styles.wrapper}> <OfflineNoticePlaceholder /> <View style={styles.iconList}> <TopTabButton name="globe" onPress={() => { dispatch(doNarrow(HOME_NARROW)); }} /> <TopTabButton name="star" onPress={() => { dispatch(doNarrow(STARRED_NARROW)); }} /> <TopTabButtonGeneral onPress={() => { dispatch(doNarrow(MENTIONED_NARROW)); }} > <IconUnreadMentions color={BRAND_COLOR} /> </TopTabButtonGeneral> <TopTabButton name="search" onPress={() => { navigation.push('search-messages'); }} /> </View> <ServerCompatBanner /> <ServerNotifsDisabledBanner navigation={navigation} /> <ServerNotifsExpiringBanner /> <LoadingBanner /> <UnreadCards /> </SafeAreaView> ); } ```
/content/code_sandbox/src/main/HomeScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
569
```javascript /* @flow strict-local */ import React, { PureComponent } from 'react'; import type { Node } from 'react'; import { Animated, Easing } from 'react-native'; import type AnimatedValue from 'react-native/Libraries/Animated/nodes/AnimatedValue'; import type { Style } from '../types'; type Props = $ReadOnly<{| style?: Style, children: Node, |}>; export default class AnimatedRotateComponent extends PureComponent<Props> { rotation: AnimatedValue = new Animated.Value(0); componentDidMount() { this.rotation.setValue(0); Animated.loop( Animated.timing(this.rotation, { toValue: 360, duration: 1000, easing: Easing.linear, useNativeDriver: true, }), ).start(); } render(): Node { const { children, style } = this.props; const rotation = this.rotation.interpolate({ inputRange: [0, 360], outputRange: (['0deg', '360deg']: $ReadOnlyArray<string>), }); const animatedStyle = { transform: [{ rotate: rotation }] }; return <Animated.View style={[animatedStyle, style]}>{children}</Animated.View>; } } ```
/content/code_sandbox/src/animation/AnimatedRotateComponent.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
256
```javascript /* @flow strict-local */ import React, { useContext } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import { createBottomTabNavigator, type BottomTabNavigationProp, } from '@react-navigation/bottom-tabs'; import type { RouteProp, RouteParamsOf } from '../react-navigation'; import { getUnreadHuddlesTotal, getUnreadPmsTotal } from '../selectors'; import { useSelector } from '../react-redux'; import type { AppNavigationMethods, AppNavigationProp } from '../nav/AppNavigator'; import { bottomTabNavigatorConfig } from '../styles/tabs'; import HomeScreen from './HomeScreen'; import PmConversationsScreen from '../pm-conversations/PmConversationsScreen'; import { IconInbox, IconStream, IconPeople } from '../common/Icons'; import OwnAvatar from '../common/OwnAvatar'; import ProfileScreen from '../account-info/ProfileScreen'; import styles, { BRAND_COLOR, ThemeContext } from '../styles'; import SubscriptionsScreen from '../streams/SubscriptionsScreen'; export type MainTabsNavigatorParamList = {| +home: RouteParamsOf<typeof HomeScreen>, +subscribed: RouteParamsOf<typeof SubscriptionsScreen>, +'pm-conversations': RouteParamsOf<typeof PmConversationsScreen>, +profile: RouteParamsOf<typeof ProfileScreen>, |}; export type MainTabsNavigationProp< +RouteName: $Keys<MainTabsNavigatorParamList> = $Keys<MainTabsNavigatorParamList>, > = // Screens on this navigator will get a `navigation` prop that reflects // this navigator itself BottomTabNavigationProp<MainTabsNavigatorParamList, RouteName> & // plus the methods it gets from its parent navigator. AppNavigationMethods; const Tab = createBottomTabNavigator< MainTabsNavigatorParamList, MainTabsNavigatorParamList, MainTabsNavigationProp<>, >(); type Props = $ReadOnly<{| navigation: AppNavigationProp<'main-tabs'>, route: RouteProp<'main-tabs', void>, |}>; export default function MainTabsScreen(props: Props): Node { const { backgroundColor } = useContext(ThemeContext); const unreadPmsCount = useSelector(getUnreadHuddlesTotal) + useSelector(getUnreadPmsTotal); return ( <View style={[styles.flexed, { backgroundColor }]}> <Tab.Navigator {...bottomTabNavigatorConfig()} lazy={false} backBehavior="none"> <Tab.Screen name="home" component={HomeScreen} options={{ tabBarLabel: 'Home', tabBarIcon: ({ color }) => <IconInbox size={24} color={color} />, }} /> <Tab.Screen name="subscribed" component={SubscriptionsScreen} options={{ tabBarLabel: 'Streams', tabBarIcon: ({ color }) => <IconStream size={24} color={color} />, }} /> <Tab.Screen name="pm-conversations" component={PmConversationsScreen} options={{ tabBarLabel: 'Direct messages', tabBarIcon: ({ color }) => <IconPeople size={24} color={color} />, tabBarBadge: unreadPmsCount > 0 ? unreadPmsCount : undefined, tabBarBadgeStyle: { color: 'white', backgroundColor: BRAND_COLOR, }, }} /> <Tab.Screen name="profile" component={ProfileScreen} options={{ tabBarLabel: 'Profile', tabBarIcon: ({ color }) => <OwnAvatar size={24} />, }} /> </Tab.Navigator> </View> ); } ```
/content/code_sandbox/src/main/MainTabsScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
776
```javascript /* @flow strict-local */ import React, { PureComponent } from 'react'; import type { Node } from 'react'; import { Animated, Easing } from 'react-native'; import type AnimatedValue from 'react-native/Libraries/Animated/nodes/AnimatedValue'; import type { Style } from '../types'; type Props = $ReadOnly<{| children: Node, visible: boolean, style?: Style, |}>; type State = {| visible: boolean, |}; export default class AnimatedScaleComponent extends PureComponent<Props, State> { state: State = { visible: this.props.visible, }; animatedValue: AnimatedValue = new Animated.Value(this.props.visible ? 1 : 0); UNSAFE_componentWillReceiveProps(nextProps: Props) { if (nextProps.visible) { this.setState({ visible: true }); } Animated.timing(this.animatedValue, { toValue: nextProps.visible ? 1 : 0, duration: 300, useNativeDriver: true, easing: Easing.elastic(), }).start(() => this.setState({ visible: nextProps.visible })); } render(): Node { const { children, style } = this.props; const { visible } = this.state; const animatedStyle = { transform: [{ scale: this.animatedValue }], opacity: this.animatedValue, display: visible ? 'flex' : 'none', }; return <Animated.View style={[animatedStyle, style]}>{children}</Animated.View>; } } ```
/content/code_sandbox/src/animation/AnimatedScaleComponent.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
322
```javascript /* @flow strict-local */ import React, { useContext, useMemo } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import { SafeAreaView } from 'react-native-safe-area-context'; import type { EditingEvent } from 'react-native/Libraries/Components/TextInput/TextInput'; import { ThemeContext, NAVBAR_SIZE } from '../styles'; import SearchInput from '../common/SearchInput'; import NavBarBackButton from './NavBarBackButton'; import type { LocalizableText } from '../types'; import { OfflineNoticePlaceholder } from '../boot/OfflineNoticeProvider'; type Props = $ReadOnly<{| autoFocus: boolean, searchBarOnChange: (text: string) => void, searchBarOnSubmit: (e: EditingEvent) => void, placeholder?: LocalizableText, canGoBack?: boolean, |}>; export default function ModalSearchNavBar(props: Props): Node { // Layout based on path_to_url . // // For details, see comment at ModalNavBar. const { autoFocus, searchBarOnChange, canGoBack = true, searchBarOnSubmit, placeholder } = props; const { backgroundColor } = useContext(ThemeContext); const styles = useMemo( () => ({ surface: { borderColor: 'hsla(0, 0%, 50%, 0.25)', borderBottomWidth: 1, backgroundColor, }, contentArea: { minHeight: NAVBAR_SIZE, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 4, }, }), [backgroundColor], ); return ( <SafeAreaView mode="padding" edges={['top']} style={styles.surface}> <OfflineNoticePlaceholder /> <SafeAreaView mode="padding" edges={['right', 'left']} style={styles.contentArea}> {canGoBack && ( <> <NavBarBackButton /> <View style={{ width: 20 }} /> </> )} <SearchInput autoFocus={autoFocus} onChangeText={searchBarOnChange} onSubmitEditing={searchBarOnSubmit} placeholder={placeholder} /> </SafeAreaView> </SafeAreaView> ); } ```
/content/code_sandbox/src/nav/ModalSearchNavBar.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
459
```javascript /* @flow strict-local */ import { type StackActionType, StackActions, CommonActions, type NavigationAction, } from '@react-navigation/native'; import * as NavigationService from './NavigationService'; import type { Narrow } from '../types'; import type { SharedData } from '../sharing/types'; // TODO: Probably just do a StackActions.pop()? export const navigateBack = (): StackActionType => { const routes = NavigationService.getState().routes; let i = routes.length - 1; while (i >= 0) { if (routes[i].name !== routes[routes.length - 1].name) { break; } i--; } const sameRoutesCount = routes.length - i - 1; return StackActions.pop(sameRoutesCount); }; /* * "Reset" actions, to explicitly prohibit back navigation. */ export const resetToAccountPicker = (): NavigationAction => CommonActions.reset({ index: 0, routes: [{ name: 'account-pick' }] }); export const resetToMainTabs = (): NavigationAction => CommonActions.reset({ index: 0, routes: [{ name: 'main-tabs' }] }); /* * Ordinary "push" actions that will push to the stack. */ /** Only call this via `doNarrow`. See there for details. */ export const navigateToChat = (narrow: Narrow): NavigationAction => // This route name 'chat' appears in one more place than usual: doEventActionSideEffects.js . StackActions.push('chat', { narrow, editMessage: null }); export const replaceWithChat = (narrow: Narrow): NavigationAction => StackActions.replace('chat', { narrow, editMessage: null }); export const navigateToSharing = (sharedData: SharedData): NavigationAction => StackActions.push('sharing', { sharedData }); ```
/content/code_sandbox/src/nav/navActions.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
392
```javascript /* @flow strict-local */ import type { Account } from '../types'; export default (args: {| hasAuth: boolean, accounts: $ReadOnlyArray<Account>, |}): {| initialRouteName: string, initialRouteParams?: { ... } |} => { const { hasAuth, accounts } = args; // If the active account is not logged in, bring the user as close // as we can to AuthScreen, the place where they can log in. if (!hasAuth) { if (accounts.length > 0) { // Let the user pick the account. If there's just one, it'll be // logged out (since `!hasAuth`); therefore it seems right to // let the user choose between that account and some new // account. return { initialRouteName: 'account-pick' }; } else { // Just go to the realm screen and have the user type out the // realm. return { initialRouteName: 'realm-input', initialRouteParams: { initial: true }, }; } } // Show the main UI screen. // // If we don't have server data yet, that screen will show a loading // indicator until the data is loaded. Crucially, an effect in // StoreProvider will make sure we really will be loading. return { initialRouteName: 'main-tabs' }; }; ```
/content/code_sandbox/src/nav/getInitialRouteInfo.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
308
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { BRAND_COLOR, createStyleSheet, NAVBAR_SIZE } from '../styles'; import { Icon } from '../common/Icons'; import type { IconNames } from '../common/Icons'; import Touchable from '../common/Touchable'; const componentStyles = createStyleSheet({ buttonFrame: { width: NAVBAR_SIZE, height: NAVBAR_SIZE, justifyContent: 'center', alignItems: 'center', }, buttonIcon: { textAlign: 'center', }, }); export function TopTabButtonGeneral( props: $ReadOnly<{| children: Node, onPress: () => void, accessibilityLabel?: string, |}>, ): Node { const { children, onPress, accessibilityLabel } = props; return ( <Touchable onPress={onPress} accessibilityLabel={accessibilityLabel} style={componentStyles.buttonFrame} > {children} </Touchable> ); } /** For use in a top tab-style navigation bar, like our {@link HomeScreen}. */ export function TopTabButton( props: $ReadOnly<{| color?: string, name: IconNames, onPress: () => void, accessibilityLabel?: string, |}>, ): Node { const { name, color = BRAND_COLOR, onPress, accessibilityLabel } = props; return ( <TopTabButtonGeneral onPress={onPress} accessibilityLabel={accessibilityLabel}> <Icon size={24} style={componentStyles.buttonIcon} color={color} name={name} /> </TopTabButtonGeneral> ); } ```
/content/code_sandbox/src/nav/TopTabButton.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
352
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { Platform } from 'react-native'; import { navigateBack } from '../actions'; import NavButton from './NavButton'; import { useNavigation } from '../react-navigation'; /** * The button for the start of the app bar, to return to previous screen. * * This serves as what Android calls the "Up button", and iOS calls the * "back button". It navigates back to the previous screen within the app. * * For background, see Android, iOS, and Material guidance on navigation: * path_to_url * path_to_url * path_to_url * path_to_url * * This is a {@link NavButton}. See there for details on how to lay it out. */ // TODO: on iOS, give the right label for a back button export default function NavBarBackButton(props: {| +color?: string |}): Node { const { color } = props; const iconName = Platform.OS === 'android' ? 'arrow-left' : 'chevron-left'; const navigation = useNavigation(); return ( <NavButton name={iconName} accessibilityLabel="Navigate up" color={color} onPress={() => { navigation.dispatch(navigateBack()); }} /> ); } ```
/content/code_sandbox/src/nav/NavBarBackButton.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
284
```javascript /* @flow strict-local */ import React, { useContext, useMemo } from 'react'; import type { Node } from 'react'; import { SafeAreaView } from 'react-native-safe-area-context'; import type { LocalizableReactText } from '../types'; import globalStyles, { ThemeContext, NAVBAR_SIZE } from '../styles'; import ZulipTextIntl from '../common/ZulipTextIntl'; import NavBarBackButton from './NavBarBackButton'; import { OfflineNoticePlaceholder } from '../boot/OfflineNoticeProvider'; type Props = $ReadOnly<{| canGoBack: boolean, title: LocalizableReactText, |}>; export default function ModalNavBar(props: Props): Node { // Layout from path_to_url : // * When we do have a back button, we want 32px between icon and text, // and 16px before icon. See handy spec diagrams at end of page. // // * With no back button, we want 12px before start of text. (This isn't // explicit in the guidelines, but see an example without back button // under "Cross-platform adaptation". Zoom in and compare to the // neighboring example where there is one; this example has a bit less // padding than that one, which should have 16px.) // // * At end of text, always put 12px, as we never have a button there. // (This isn't clear either, but use 12px for symmetry with start.) // // And the `NavBarBackButton` comes with 12px padding around icon and // wants another 4px padding at start. const { canGoBack, title } = props; const { backgroundColor } = useContext(ThemeContext); const styles = useMemo( () => ({ text: [ globalStyles.navTitle, { flex: 1 }, canGoBack ? { marginStart: 20, marginEnd: 8 } : { marginHorizontal: 8 }, ], surface: { borderColor: 'hsla(0, 0%, 50%, 0.25)', borderBottomWidth: 1, backgroundColor, }, contentArea: { minHeight: NAVBAR_SIZE, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 4, }, }), [canGoBack, backgroundColor], ); return ( <SafeAreaView mode="padding" edges={['top']} style={styles.surface}> <OfflineNoticePlaceholder /> <SafeAreaView mode="padding" edges={['right', 'left']} style={styles.contentArea}> {canGoBack && <NavBarBackButton />} <ZulipTextIntl style={styles.text} text={title} numberOfLines={1} ellipsizeMode="tail" /> </SafeAreaView> </SafeAreaView> ); } ```
/content/code_sandbox/src/nav/ModalNavBar.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
621
```javascript /* @flow strict-local */ import React, { useCallback, useContext } from 'react'; import type { Node, ComponentType } from 'react'; import { View } from 'react-native'; // $FlowFixMe[untyped-import] import Color from 'color'; import { SafeAreaView } from 'react-native-safe-area-context'; import type { Narrow, EditMessage, UserId } from '../types'; import type { PmKeyRecipients } from '../utils/recipient'; import LoadingBanner from '../common/LoadingBanner'; import ZulipStatusBar from '../common/ZulipStatusBar'; import { useSelector, useDispatch } from '../react-redux'; import { BRAND_COLOR, NAVBAR_SIZE, ThemeContext } from '../styles'; import Title from '../title/Title'; import NavBarBackButton from './NavBarBackButton'; import { getStreamColorForNarrow } from '../subscriptions/subscriptionSelectors'; import { foregroundColorFromBackground } from '../utils/color'; import { caseNarrowDefault, streamIdOfNarrow, streamNarrow } from '../utils/narrow'; import { doNarrow } from '../actions'; import { isNarrowValid as getIsNarrowValid } from '../selectors'; import NavButton from './NavButton'; import { useNavigation } from '../react-navigation'; import { OfflineNoticePlaceholder } from '../boot/OfflineNoticeProvider'; function ExtraNavButtonStream(props: {| +color: string, +narrow: Narrow |}): Node { const { color, narrow } = props; const navigation = useNavigation(); const isNarrowValid = useSelector(state => getIsNarrowValid(state, narrow)); if (!isNarrowValid) { return null; } return ( <NavButton name="list" color={color} onPress={() => { navigation.push('topic-list', { streamId: streamIdOfNarrow(narrow) }); }} /> ); } function ExtraNavButtonTopic(props: {| +color: string, +narrow: Narrow |}): Node { const { narrow, color } = props; const dispatch = useDispatch(); const handlePress = useCallback(() => { dispatch(doNarrow(streamNarrow(streamIdOfNarrow(narrow)))); }, [dispatch, narrow]); return <NavButton name="arrow-up" color={color} onPress={handlePress} />; } function InfoNavButtonStream(props: {| +color: string, +narrow: Narrow |}): Node { const { color, narrow } = props; const navigation = useNavigation(); const isNarrowValid = useSelector(state => getIsNarrowValid(state, narrow)); if (!isNarrowValid) { return null; } return ( <NavButton name="info" color={color} onPress={() => { navigation.push('stream-settings', { streamId: streamIdOfNarrow(narrow) }); }} /> ); } function InfoNavButtonPrivate(props: {| +color: string, +userId: UserId |}): Node { const { color, userId } = props; const navigation = useNavigation(); return ( <NavButton name="info" color={color} onPress={() => { navigation.push('account-details', { userId }); }} /> ); } function InfoNavButtonGroup(props: {| +color: string, +userIds: PmKeyRecipients |}): Node { const { color, userIds } = props; const navigation = useNavigation(); return ( <NavButton name="info" color={color} onPress={() => { navigation.push('pm-conversation-details', { recipients: userIds }); }} /> ); } /** * The "action items" to include in this app bar. * * I.e., the buttons at the end of the app bar. The spec calls these * "action items": * path_to_url#anatomy */ const ActionItems: ComponentType<{| +color: string, +narrow: Narrow |}> = props => caseNarrowDefault( props.narrow, { stream: () => ( <> <ExtraNavButtonStream {...props} /> <InfoNavButtonStream {...props} /> </> ), topic: () => ( <> <ExtraNavButtonTopic {...props} /> <InfoNavButtonStream {...props} /> </> ), pm: ids => ids.length === 1 ? ( <InfoNavButtonPrivate userId={ids[0]} color={props.color} /> ) : ( <InfoNavButtonGroup userIds={ids} color={props.color} /> ), }, () => false, ); export default function ChatNavBar(props: {| +narrow: Narrow, +editMessage: EditMessage | null, |}): Node { const { narrow, editMessage } = props; const streamColor = useSelector(state => getStreamColorForNarrow(state, narrow)); const buttonColor = streamColor === undefined ? BRAND_COLOR : foregroundColorFromBackground(streamColor); const themeColor = useContext(ThemeContext).color; const textColor = streamColor === undefined ? themeColor : foregroundColorFromBackground(streamColor); const spinnerColor = streamColor === undefined ? 'default' : foregroundColorFromBackground(streamColor); return ( <> <ZulipStatusBar backgroundColor={streamColor} /> <SafeAreaView mode="padding" edges={['top']} style={{ borderColor: streamColor === undefined ? 'hsla(0, 0%, 50%, 0.25)' : Color(streamColor).darken(0.1).hsl().string(), borderBottomWidth: 1, backgroundColor: streamColor, }} > <OfflineNoticePlaceholder /> {/* This SafeAreaView is the app bar: path_to_url#specs */} <SafeAreaView mode="padding" edges={['right', 'left']} style={{ // Ideally this would be `minHeight`, like in our other app bars, // to smoothly accommodate large font sizes. But we seem to have // a layout bug where doing that causes the app bar to take up // over half the screen: // path_to_url#discussion_r724700752 height: NAVBAR_SIZE, paddingHorizontal: 4, flexDirection: 'row', alignItems: 'center', }} > <NavBarBackButton color={buttonColor} /> {/* We put 20px here to get 32px total between the icon and the title text. */} <View style={{ width: 20 }} /> <Title color={textColor} narrow={narrow} editMessage={editMessage} /> <ActionItems color={buttonColor} narrow={narrow} /> </SafeAreaView> <LoadingBanner spinnerColor={spinnerColor} backgroundColor={streamColor} textColor={textColor} /> </SafeAreaView> </> ); } ```
/content/code_sandbox/src/nav/ChatNavBar.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,488
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { Platform } from 'react-native'; import { createStackNavigator, type StackNavigationProp, TransitionPresets, } from '@react-navigation/stack'; import type { StackActionHelpers } from '@react-navigation/native'; import type { NavigationHelpers, EventConsumer, EventMapCore, } from '@react-navigation/core/lib/typescript/src/types'; import type { NavigationState } from '@react-navigation/routers'; import type { RouteParamsOf } from '../react-navigation'; import { useGlobalSelector } from '../react-redux'; import { getHasAuth, getAccounts } from '../selectors'; import getInitialRouteInfo from './getInitialRouteInfo'; import type { GlobalParamList } from './globalTypes'; import AccountPickScreen from '../account/AccountPickScreen'; import RealmInputScreen from '../start/RealmInputScreen'; import AuthScreen from '../start/AuthScreen'; import DevAuthScreen from '../start/DevAuthScreen'; import MainTabsScreen from '../main/MainTabsScreen'; import MessageReactionsScreen from '../reactions/MessageReactionsScreen'; import AccountDetailsScreen from '../account-info/AccountDetailsScreen'; import PmConversationDetailsScreen from '../chat/PmConversationDetailsScreen'; import SearchMessagesScreen from '../search/SearchMessagesScreen'; import New1to1PmScreen from '../user-picker/New1to1PmScreen'; import ChatScreen from '../chat/ChatScreen'; import PasswordAuthScreen from '../start/PasswordAuthScreen'; import LightboxScreen from '../lightbox/LightboxScreen'; import NewGroupPmScreen from '../user-picker/NewGroupPmScreen'; import InviteUsersScreen from '../streams/InviteUsersScreen'; import StreamSettingsScreen from '../streams/StreamSettingsScreen'; import CreateStreamScreen from '../streams/CreateStreamScreen'; import EditStreamScreen from '../streams/EditStreamScreen'; import NotificationsScreen from '../settings/NotificationsScreen'; import NotifTroubleshootingScreen from '../settings/NotifTroubleshootingScreen'; import TopicListScreen from '../topics/TopicListScreen'; import EmojiPickerScreen from '../emoji/EmojiPickerScreen'; import LegalScreen from '../settings/LegalScreen'; import SettingsScreen from '../settings/SettingsScreen'; import UserStatusScreen from '../user-statuses/UserStatusScreen'; import SharingScreen from '../sharing/SharingScreen'; import SelectableOptionsScreen from '../common/SelectableOptionsScreen'; import StreamListScreen from '../subscriptions/StreamListScreen'; import ReadReceiptsScreen from '../message/ReadReceiptsScreen'; import { useHaveServerDataGate } from '../withHaveServerDataGate'; export type AppNavigatorParamList = {| +'account-pick': RouteParamsOf<typeof AccountPickScreen>, +'account-details': RouteParamsOf<typeof AccountDetailsScreen>, +'pm-conversation-details': RouteParamsOf<typeof PmConversationDetailsScreen>, +auth: RouteParamsOf<typeof AuthScreen>, +chat: RouteParamsOf<typeof ChatScreen>, +'dev-auth': RouteParamsOf<typeof DevAuthScreen>, +'emoji-picker': RouteParamsOf<typeof EmojiPickerScreen>, +'main-tabs': RouteParamsOf<typeof MainTabsScreen>, +'all-streams': RouteParamsOf<typeof StreamListScreen>, +'message-reactions': RouteParamsOf<typeof MessageReactionsScreen>, +'password-auth': RouteParamsOf<typeof PasswordAuthScreen>, +'realm-input': RouteParamsOf<typeof RealmInputScreen>, +'search-messages': RouteParamsOf<typeof SearchMessagesScreen>, +'new-1to1-pm': RouteParamsOf<typeof New1to1PmScreen>, +lightbox: RouteParamsOf<typeof LightboxScreen>, +'new-group-pm': RouteParamsOf<typeof NewGroupPmScreen>, +'invite-users': RouteParamsOf<typeof InviteUsersScreen>, +'stream-settings': RouteParamsOf<typeof StreamSettingsScreen>, +'edit-stream': RouteParamsOf<typeof EditStreamScreen>, +'create-stream': RouteParamsOf<typeof CreateStreamScreen>, +'topic-list': RouteParamsOf<typeof TopicListScreen>, +notifications: RouteParamsOf<typeof NotificationsScreen>, +'notif-troubleshooting': RouteParamsOf<typeof NotifTroubleshootingScreen>, +legal: RouteParamsOf<typeof LegalScreen>, +'user-status': RouteParamsOf<typeof UserStatusScreen>, +sharing: RouteParamsOf<typeof SharingScreen>, +settings: RouteParamsOf<typeof SettingsScreen>, +'selectable-options': RouteParamsOf<typeof SelectableOptionsScreen>, +'read-receipts': RouteParamsOf<typeof ReadReceiptsScreen>, |}; /** * A common supertype for navigation props in this and descendant navigators. * * In particular this contains methods like `push`, with all the main * navigator's routes available, and `addListener` with the events that * aren't specific to the stack navigator. */ export type AppNavigationMethods = // The parent navigator's "helper" methods (like `push`) are available on // child navigators too. So we include the stack-specific methods: StackActionHelpers<AppNavigatorParamList> & // as well as the general ones that exist on any kind of navigator. NavigationHelpers<AppNavigatorParamList> & // On the other hand, the *events* available on the child navigator are // apparently only those of the child, not the parent. (In particular // this is encoded in upstream's `CompositeNavigationProp` type: // path_to_url#discussion_r894932407 // .) So for what's available everywhere, we just have the general // events that exist on any kind of navigator. EventConsumer<EventMapCore<NavigationState<AppNavigatorParamList>>>; /** * The type of the `navigation` prop for screens in this navigator. */ export type AppNavigationProp< +RouteName: $Keys<AppNavigatorParamList> = $Keys<AppNavigatorParamList>, > = StackNavigationProp<AppNavigatorParamList, RouteName> & // Intersecting with the methods type should be redundant -- the // StackNavigationProp type should already be a subtype of it. But when // we check that below, we'd get puzzling errors. (Probably the variance, // or in/exactness, of one of the underlying type definitions isn't right: // path_to_url#discussion_r894934679 // .) So add it explicitly. AppNavigationMethods; // Confirm that this navigator's screens' navigation props will be valid // as the methods type. // eslint-disable-next-line (n: AppNavigationProp<>): AppNavigationMethods => n; const Stack = createStackNavigator<GlobalParamList>(); type Props = $ReadOnly<{||}>; export default function AppNavigator(props: Props): Node { const hasAuth = useGlobalSelector(getHasAuth); const accounts = useGlobalSelector(getAccounts); const { initialRouteName, initialRouteParams } = getInitialRouteInfo({ hasAuth, accounts, }); return ( <Stack.Navigator initialRouteName={initialRouteName} headerMode="none" screenOptions={{ ...Platform.select({ android: TransitionPresets.FadeFromBottomAndroid, ios: TransitionPresets.DefaultTransition, }), }} > {/* These screens expect server data in order to function normally. */} <Stack.Screen name="account-details" component={useHaveServerDataGate(AccountDetailsScreen)} /> <Stack.Screen name="pm-conversation-details" component={useHaveServerDataGate(PmConversationDetailsScreen)} /> <Stack.Screen name="chat" component={useHaveServerDataGate(ChatScreen)} /> <Stack.Screen name="emoji-picker" component={useHaveServerDataGate(EmojiPickerScreen)} /> <Stack.Screen name="main-tabs" component={useHaveServerDataGate(MainTabsScreen)} /> <Stack.Screen name="all-streams" component={useHaveServerDataGate(StreamListScreen)} /> <Stack.Screen name="message-reactions" component={useHaveServerDataGate(MessageReactionsScreen)} /> <Stack.Screen name="search-messages" component={useHaveServerDataGate(SearchMessagesScreen)} /> <Stack.Screen name="new-1to1-pm" component={useHaveServerDataGate(New1to1PmScreen)} /> <Stack.Screen name="lightbox" component={useHaveServerDataGate(LightboxScreen)} /> <Stack.Screen name="new-group-pm" component={useHaveServerDataGate(NewGroupPmScreen)} /> <Stack.Screen name="invite-users" component={useHaveServerDataGate(InviteUsersScreen)} /> <Stack.Screen name="stream-settings" component={useHaveServerDataGate(StreamSettingsScreen)} /> <Stack.Screen name="edit-stream" component={useHaveServerDataGate(EditStreamScreen)} /> <Stack.Screen name="create-stream" component={useHaveServerDataGate(CreateStreamScreen)} /> <Stack.Screen name="topic-list" component={useHaveServerDataGate(TopicListScreen)} /> <Stack.Screen name="notifications" component={useHaveServerDataGate(NotificationsScreen)} /> <Stack.Screen name="notif-troubleshooting" component={useHaveServerDataGate(NotifTroubleshootingScreen)} /> <Stack.Screen name="legal" component={useHaveServerDataGate(LegalScreen)} /> <Stack.Screen name="user-status" component={useHaveServerDataGate(UserStatusScreen)} /> <Stack.Screen name="settings" component={useHaveServerDataGate(SettingsScreen)} /> <Stack.Screen name="read-receipts" component={useHaveServerDataGate(ReadReceiptsScreen)} /> {/* These screens do not expect server data in order to function normally. */} <Stack.Screen name="account-pick" component={AccountPickScreen} /> <Stack.Screen name="auth" component={AuthScreen} /> <Stack.Screen name="dev-auth" component={DevAuthScreen} /> <Stack.Screen name="password-auth" component={PasswordAuthScreen} /> <Stack.Screen name="realm-input" component={RealmInputScreen} initialParams={ // $FlowFixMe[incompatible-exact]: initialRouteParams is basically untyped // $FlowFixMe[prop-missing]: initialRouteParams is basically untyped initialRouteName === 'realm-input' ? initialRouteParams : undefined } /> <Stack.Screen name="sharing" component={SharingScreen} /> <Stack.Screen name="selectable-options" component={SelectableOptionsScreen} /> </Stack.Navigator> ); } ```
/content/code_sandbox/src/nav/AppNavigator.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
2,250
```javascript /* @flow strict-local */ import type { AppNavigatorParamList } from './AppNavigator'; import type { SharingNavigatorParamList } from '../sharing/SharingScreen'; import type { MainTabsNavigatorParamList } from '../main/MainTabsScreen'; export type GlobalParamList = {| ...AppNavigatorParamList, ...SharingNavigatorParamList, ...MainTabsNavigatorParamList, |}; ```
/content/code_sandbox/src/nav/globalTypes.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
83
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import { useSelector } from '../react-redux'; import { getUnreadMentionsTotal } from '../selectors'; import { IconMention } from '../common/Icons'; import CountOverlay from '../common/CountOverlay'; type Props = $ReadOnly<{| color: string, |}>; export default function IconUnreadMentions(props: Props): Node { const { color } = props; const unreadMentionsTotal = useSelector(getUnreadMentionsTotal); return ( <View> <CountOverlay unreadCount={unreadMentionsTotal}> <IconMention size={24} color={color} /> </CountOverlay> </View> ); } ```
/content/code_sandbox/src/nav/IconUnreadMentions.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
172
```javascript /* @flow strict-local */ import React, { useContext, useEffect } from 'react'; import type { Node } from 'react'; import { useColorScheme } from 'react-native'; import { NavigationContainer, DefaultTheme, DarkTheme } from '@react-navigation/native'; import { useGlobalSelector } from '../react-redux'; import { ThemeContext } from '../styles'; import * as NavigationService from './NavigationService'; import { getGlobalSettings } from '../selectors'; import AppNavigator from './AppNavigator'; import { getThemeToUse } from '../settings/settingsSelectors'; type Props = $ReadOnly<{||}>; /** * Wrapper for React Nav's component given by `createAppContainer`. * * Must be constructed after the store has been rehydrated. * * - Set `NavigationService`. * * - Call `createAppContainer` with the appropriate `initialRouteName` * and `initialRouteParams` which we get from data in Redux. */ export default function ZulipAppContainer(props: Props): Node { const themeName = useGlobalSelector(state => getGlobalSettings(state).theme); const osScheme = useColorScheme(); const themeToUse = getThemeToUse(themeName, osScheme); useEffect( () => // return a cleanup function: // path_to_url#example-using-hooks-1 () => { NavigationService.isReadyRef.current = false; }, [], ); const themeContext = useContext(ThemeContext); const BaseTheme = themeToUse === 'dark' ? DarkTheme : DefaultTheme; const theme = { ...BaseTheme, dark: themeToUse === 'dark', colors: { ...BaseTheme.colors, primary: themeContext.color, background: themeContext.backgroundColor, card: themeContext.cardColor, border: themeContext.dividerColor, }, }; return ( <NavigationContainer ref={NavigationService.navigationContainerRef} onReady={() => { NavigationService.isReadyRef.current = true; }} theme={theme} > <AppNavigator /> </NavigationContainer> ); } ```
/content/code_sandbox/src/nav/ZulipNavigationContainer.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
448
```javascript /* @flow strict-local */ import React from 'react'; import { type NavigationAction, type NavigationState, typeof NavigationContainer, } from '@react-navigation/native'; export const isReadyRef: {| current: null | boolean |} = React.createRef(); export const navigationContainerRef: {| current: null | React$ElementRef<NavigationContainer>, |} = React.createRef(); const getContainer = () => { if (navigationContainerRef.current === null) { throw new Error('Tried to use NavigationService before `navigationContainerRef` was set.'); } if (isReadyRef.current !== true) { throw new Error('Tried to use NavigationService before `NavigationContainer` was ready.'); } return navigationContainerRef.current; }; export const getState = (): NavigationState<> => getContainer().getRootState(); export const dispatch = (navigationAction: NavigationAction): void => getContainer().dispatch(navigationAction); ```
/content/code_sandbox/src/nav/NavigationService.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
201
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { BRAND_COLOR, createStyleSheet } from '../styles'; import { Icon } from '../common/Icons'; import type { IconNames } from '../common/Icons'; import Touchable from '../common/Touchable'; const componentStyles = createStyleSheet({ buttonFrame: { width: 48, height: 48, justifyContent: 'center', alignItems: 'center', }, buttonIcon: { textAlign: 'center', }, }); /** * A button for use in a (top) app bar. * * This is meant to be used in a Material top app bar: * path_to_url * with touch targets conforming to the spec here: * path_to_url#layout-and-typography * That is, the touch targets are 48x48, and immediately abut each other. * * This component is 48x48, all of it the touch target, with a 24x24 icon. * That means no padding is needed between these, but some padding may be * needed between these and the edge of the app bar; for details, see: * path_to_url#specs */ export default function NavButton( props: $ReadOnly<{| color?: string, name: IconNames, onPress: () => void, accessibilityLabel?: string, |}>, ): Node { const { name, color = BRAND_COLOR, onPress, accessibilityLabel } = props; return ( <Touchable onPress={onPress} accessibilityLabel={accessibilityLabel} style={componentStyles.buttonFrame} > <Icon size={24} style={componentStyles.buttonIcon} color={color} name={name} /> </Touchable> ); } ```
/content/code_sandbox/src/nav/NavButton.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
385
```javascript /* @flow strict-local */ import deepFreeze from 'deep-freeze'; import { navigateBack } from '../navActions'; import * as NavigationService from '../NavigationService'; describe('navigateBack', () => { test('if no routes the count of same routes is 0', () => { // $FlowFixMe[cannot-write] Make Flow understand about mocking. NavigationService.getState = jest.fn().mockReturnValue( deepFreeze({ routes: [], }), ); const action = navigateBack(); expect(action).toMatchObject({ type: 'POP', payload: { count: 0 } }); }); test('if last route differs from routes the count of same routes is 0', () => { // $FlowFixMe[cannot-write] Make Flow understand about mocking. NavigationService.getState = jest.fn().mockReturnValue( deepFreeze({ routes: [{ name: 'main-tabs' }, { name: 'chat' }], }), ); const action = navigateBack(); expect(action).toMatchObject({ type: 'POP', payload: { count: 1 } }); }); test('if several of the routes are the same ignore the params and return their count', () => { // $FlowFixMe[cannot-write] Make Flow understand about mocking. NavigationService.getState = jest.fn().mockReturnValue( deepFreeze({ routes: [ { name: 'login' }, { name: 'main-tabs' }, { name: 'chat', params: { key: 'value' } }, { name: 'chat', params: { key: 'another value' } }, { name: 'chat', params: { anotherKey: 'some value' } }, ], }), ); const action = navigateBack(); expect(action).toMatchObject({ type: 'POP', payload: { count: 3 } }); }); }); ```
/content/code_sandbox/src/nav/__tests__/navActions-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
405
```javascript /* @flow strict-local */ // import { Vibration } from 'react-native'; import { CommonActions } from '@react-navigation/native'; import type { Narrow, ThunkAction } from '../types'; import type { EventAction } from '../actionTypes'; import { EVENT_TYPING_START, EVENT_UPDATE_MESSAGE } from '../actionConstants'; import { ensureTypingStatusExpiryLoop } from '../typing/typingActions'; import * as NavigationService from '../nav/NavigationService'; import { isStreamNarrow, isTopicNarrow, streamIdOfNarrow, topicNarrow, topicOfNarrow, } from '../utils/narrow'; /** * React to actions dispatched for Zulip server events. * * To be dispatched before the event actions are dispatched. */ export default (action: EventAction): ThunkAction<Promise<void>> => async (dispatch, getState) => { switch (action.type) { case EVENT_TYPING_START: dispatch(ensureTypingStatusExpiryLoop()); break; case EVENT_UPDATE_MESSAGE: { // If the conversation we were looking at got moved, follow it. // See #5251 for background. const { event, move } = action; const { propagate_mode } = event; if (!move || !(propagate_mode === 'change_all' || propagate_mode === 'change_later')) { // This edit wasn't a move, or was targeted to a specific message. break; } const navState = NavigationService.getState(); for (const route of navState.routes) { if (route.name !== 'chat') { continue; } // TODO(#5005): Only make these updates if this ChatScreen is for // the account that this event applies to. (I.e., just if this is // the active account.) // $FlowFixMe[incompatible-use]: relying on ChatScreen having route params // $FlowFixMe[prop-missing]: relying on ChatScreen route-params type const narrow: Narrow = route.params.narrow; if ( isTopicNarrow(narrow) && streamIdOfNarrow(narrow) === move.orig_stream_id && topicOfNarrow(narrow) === move.orig_topic ) { // A ChatScreen showing the very conversation that was moved. // Change the ChatScreen's narrow to follow the move. // // Web does this only if the blue box is on one of the affected // messages, in case only some of the conversation was moved. // We don't have a blue box, but: // TODO: Ideally if the moved messages are all offscreen we'd skip this. NavigationService.dispatch({ ...CommonActions.setParams({ narrow: topicNarrow(move.new_stream_id, move.new_topic), }), // Spreading the `setParams` action and adding `source` like // this is the documented way to specify a route (rather than // apply to the focused route): // path_to_url#setparams source: route.key, }); // TODO(#5251): If compose box is open and topic was resolved, warn. } else if (isStreamNarrow(narrow) && streamIdOfNarrow(narrow) === move.orig_stream_id) { // A ChatScreen showing the stream that contained the moved messages. // // TODO(#5251): Update topic input, if it matches. (If the stream // changed too, unclear what to do. Possibly change the // screen's narrow, as if narrowed to the moved topic?) } } break; } default: } }; ```
/content/code_sandbox/src/events/doEventActionSideEffects.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
792
```javascript /* @flow strict-local */ import { EventTypes, type EventType, type RealmUserUpdateEventRaw } from '../api/eventTypes'; import * as logging from '../utils/logging'; import type { PerAccountState, EventAction, MessageEdit } from '../types'; import { EVENT_ALERT_WORDS, EVENT_NEW_MESSAGE, EVENT_PRESENCE, EVENT_REACTION_ADD, EVENT_REACTION_REMOVE, EVENT_TYPING_START, EVENT_TYPING_STOP, EVENT_SUBMESSAGE, EVENT_MESSAGE_DELETE, EVENT_UPDATE_MESSAGE, EVENT_UPDATE_MESSAGE_FLAGS, EVENT_USER_ADD, EVENT_USER_REMOVE, EVENT_MUTED_TOPICS, EVENT_MUTED_USERS, EVENT_USER_GROUP_ADD, EVENT_USER_GROUP_REMOVE, EVENT_USER_GROUP_UPDATE, EVENT_USER_GROUP_ADD_MEMBERS, EVENT_USER_GROUP_REMOVE_MEMBERS, EVENT_USER_STATUS_UPDATE, EVENT_REALM_EMOJI_UPDATE, EVENT_UPDATE_GLOBAL_NOTIFICATIONS_SETTINGS, EVENT_UPDATE_DISPLAY_SETTINGS, EVENT_REALM_FILTERS, EVENT_SUBSCRIPTION, EVENT, } from '../actionConstants'; import { getRealm } from '../selectors'; import { getOwnUserId, tryGetUserForId } from '../users/userSelectors'; import { AvatarURL } from '../utils/avatar'; import { getRealmUrl, getZulipFeatureLevel } from '../account/accountsSelectors'; import { messageMoved } from '../api/misc'; import { ensureUnreachable } from '../generics'; const opToActionUserGroup = { add: EVENT_USER_GROUP_ADD, remove: EVENT_USER_GROUP_REMOVE, update: EVENT_USER_GROUP_UPDATE, add_members: EVENT_USER_GROUP_ADD_MEMBERS, remove_members: EVENT_USER_GROUP_REMOVE_MEMBERS, }; const opToActionReaction = { add: EVENT_REACTION_ADD, remove: EVENT_REACTION_REMOVE, }; const opToActionTyping = { start: EVENT_TYPING_START, stop: EVENT_TYPING_STOP, }; const actionTypeOfEventType = { subscription: EVENT_SUBSCRIPTION, presence: EVENT_PRESENCE, muted_topics: EVENT_MUTED_TOPICS, muted_users: EVENT_MUTED_USERS, realm_emoji: EVENT_REALM_EMOJI_UPDATE, realm_filters: EVENT_REALM_FILTERS, submessage: EVENT_SUBMESSAGE, update_global_notifications: EVENT_UPDATE_GLOBAL_NOTIFICATIONS_SETTINGS, update_display_settings: EVENT_UPDATE_DISPLAY_SETTINGS, user_status: EVENT_USER_STATUS_UPDATE, }; /** * Translate a Zulip event from the server into one of our Redux actions. * * If the action is one we don't currently handle, return null. * If it's one we don't recognize at all, log a warning and return null. * * For reference on the events in the Zulip API, see: * path_to_url * * This function takes the Redux state as an argument because for a handful * of types of events, we have it attach some pieces of the state inside the * resulting action. That is a now-obsolete workaround for letting our * Redux sub-reducers use data from elsewhere in the Redux state; don't add * new uses. * * The new approach is that we pass the global Redux state to each * sub-reducer, and they should use that instead. See ef251f48a for * discussion, and a2000b9c8 and its parent for an example of using it. */ // This FlowFixMe is because this function encodes a large number of // assumptions about the events the server sends, and doesn't check them. export default (state: PerAccountState, event: $FlowFixMe): EventAction | null => { const zulipFeatureLevel = getZulipFeatureLevel(state); const allowEditHistory = getRealm(state).allowEditHistory; const type = (event.type: EventType); switch (type) { // For reference on each type of event, see: // path_to_url#events case 'alert_words': return { type: EVENT_ALERT_WORDS, alert_words: event.alert_words, }; case 'message': return { type: EVENT_NEW_MESSAGE, id: event.id, message: { ...event.message, // Move `flags` key from `event` to `event.message` for // consistency; default to empty if `event.flags` is not set. flags: event.message.flags ?? event.flags ?? [], avatar_url: AvatarURL.fromUserOrBotData({ rawAvatarUrl: event.message.avatar_url, email: event.message.sender_email, userId: event.message.sender_id, realm: getRealmUrl(state), }), edit_history: // Why condition on allowEditHistory? See MessageBase['edit_history']. // Why FL 118 condition? See MessageEdit type. allowEditHistory && zulipFeatureLevel >= 118 ? (event.message.edit_history: $ReadOnlyArray<MessageEdit> | void) : null, }, local_message_id: event.local_message_id, caughtUp: state.caughtUp, ownUserId: getOwnUserId(state), }; case 'delete_message': return { type: EVENT_MESSAGE_DELETE, // Before server feature level 13 (or if we didn't specify the // `bulk_message_deletion` client capability, which we do), this // event has `message_id` instead of `message_ids`. // TODO(server-3.0): Simplify this. messageIds: event.message_ids ?? [event.message_id], }; case 'realm': return { type: EVENT, event: /* prettier-ignore */ event.op === 'update' // Convert to an equivalent `update_dict` event, so reducers only have // to handle that one form. // TODO: handle `extra_data` hack property in the `update` // event, as long as servers still send it ? { id: event.id, type: EventTypes.realm, op: 'update_dict', property: 'default', data: { [event.property]: event.value, }, } : event, }; case 'restart': case 'custom_profile_fields': case 'stream': case 'user_settings': case 'user_topic': return { type: EVENT, event, }; case 'update_message': return { type: EVENT_UPDATE_MESSAGE, event: { ...event, message_ids: event.message_ids.sort((a, b) => a - b) }, move: messageMoved(event), }; case 'subscription': case 'presence': case 'muted_topics': case 'muted_users': case 'realm_emoji': case 'submessage': // TODO(server-5.0): Remove these two when all supported servers can // handle the `user_settings_object` client capability (FL 89). case 'update_global_notifications': // eslint-disable-line no-fallthrough case 'update_display_settings': case 'user_status': // eslint-disable-line no-fallthrough return { ...event, type: actionTypeOfEventType[event.type], }; // See notes on `RealmFilter` and `RealmLinkifier` types. case 'realm_filters': { return { ...event, type: EVENT_REALM_FILTERS, realm_filters: event.realm_filters, }; } // See notes on `RealmFilter` and `RealmLinkifier` types. // // Empirically, servers that know about the new format send two // events for every change to the linkifiers: one in this new // format and one in the 'realm_filters' format. That's whether we // put 'realm_linkifiers' or 'realm_filters' in // `fetch_event_types`. // // Shrug, because we can handle both events, and both events give // the whole array of linkifiers, which we're happy to clobber the // old state with. case 'realm_linkifiers': { return { ...event, type: EVENT_REALM_FILTERS, // We do the same in `registerForEvents`'s transform function. realm_filters: event.realm_linkifiers.map(({ pattern, url_format, id }) => [ pattern, url_format, id, ]), }; } case 'realm_user': { const realm = getRealmUrl(state); switch (event.op) { case 'add': { const { avatar_url: rawAvatarUrl, user_id: userId, email } = event.person; return { type: EVENT_USER_ADD, id: event.id, // TODO: Validate and rebuild `event.person`. person: { ...event.person, avatar_url: AvatarURL.fromUserOrBotData({ rawAvatarUrl, userId, email, realm, }), }, }; } case 'update': { const rawEvent: RealmUserUpdateEventRaw = event; const { user_id: userId } = rawEvent.person; const existingUser = tryGetUserForId(state, userId); if (!existingUser) { // If we get one of these events and don't have // information on the user, there's nothing to do about // it. But it's probably a bug, so, tell Sentry. logging.warn( "`realm_user` event with op `update` received for a user we don't know about", { userId }, ); return null; } const { person } = rawEvent; if (person.avatar_url !== undefined) { return { type: EVENT, event: { ...rawEvent, person: { user_id: person.user_id, avatar_url: AvatarURL.fromUserOrBotData({ rawAvatarUrl: person.avatar_url, userId, email: existingUser.email, realm, }), }, }, }; } else { return { type: EVENT, event: { ...rawEvent, person }, }; } } case 'remove': // TODO: Handle this event and properly form this action. return { type: EVENT_USER_REMOVE, }; default: return null; } } case 'realm_bot': // If implementing, don't forget to convert `avatar_url` on // `op: 'add'`, and (where `avatar_url` is present) on // `op: 'update'`. return null; case 'reaction': return { ...event, // Raw reaction events from the server have a variation on the // properties of `Reaction`: instead of `user_id: UserId`, they have // `user: {| email: string, full_name: string, user_id: UserId |}`. // NB this is different from the reactions in a `/messages` response; // see `getMessages` to compare. user_id: event.user.user_id, type: opToActionReaction[event.op], }; case 'heartbeat': return null; case 'update_message_flags': return { ...event, type: EVENT_UPDATE_MESSAGE_FLAGS, // Servers with feature level 32+ send `op`. Servers will eventually // stop sending `operation`; see #4238. // TODO(server-4.0): Simplify to just use `op`. op: event.op ?? event.operation, message_details: event.message_details ? new Map(Object.entries(event.message_details).map(([k, v]) => [parseInt(k, 10), v])) : undefined, allMessages: state.messages, }; case 'typing': return { ...event, ownUserId: getOwnUserId(state), type: opToActionTyping[event.op], time: new Date().getTime(), }; case 'user_group': return { ...event, type: opToActionUserGroup[event.op], }; case 'pointer': // Ignore these `pointer` events. We've never used this information. // TODO(server-3.0): The server stopped sending these; drop the case. return null; case 'hotspots': // Ignore these `hotspots` events. They're about the tutorial // experience which is specific to the Zulip web app: // path_to_url#hotspots return null; case 'attachment': // Ignore these `attachment` events. We'd want them in a future // where we add a UI that lists the attachments you've uploaded: // path_to_url#attachment-add return null; case 'has_zoom_token': // Ignore these `has_zoom_token` events. We'd want them if // supporting creating a Zoom call: // path_to_url#has_zoom_token return null; case 'drafts': // Ignore these `drafts` events. We'll need them as part of #4932, // syncing drafts with the server. return null; case 'default_streams': case 'default_stream_groups': case 'invites_changed': case 'realm_domains': // Ignore these event types. We'll need them as part of #3962 or // followup tasks to that, supporting inviting other users to Zulip. // We'd also need them as part of a full org-settings UI. return null; case 'realm_export': case 'realm_playgrounds': case 'realm_user_settings_defaults': // Ignore these event types. We'll need them eventually as part of a // full org-settings UI. return null; default: // Note there are also some event types that are mentioned above // (so don't reach this default case), but that at some later stage // we don't fully handle: #3408. ensureUnreachable(type); logging.error(`Unhandled Zulip API event type: ${event.type}`); return null; } }; ```
/content/code_sandbox/src/events/eventToAction.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
3,018
```javascript /* @flow strict-local */ import { addBreadcrumb } from '@sentry/react-native'; // $FlowFixMe[untyped-import] import isEqual from 'lodash.isequal'; import * as NavigationService from '../nav/NavigationService'; import { resetToAccountPicker } from '../nav/navActions'; import { ensureUnreachable } from '../generics'; import type { InitialData } from '../api/initialDataTypes'; import type { GeneralEvent, ThunkAction, PerAccountAction } from '../types'; import type { RegisterAbortReason } from '../actionTypes'; import * as api from '../api'; import { REGISTER_START, REGISTER_ABORT, REGISTER_COMPLETE, DEAD_QUEUE } from '../actionConstants'; import { logout } from '../account/logoutActions'; import eventToAction from './eventToAction'; import doEventActionSideEffects from './doEventActionSideEffects'; import { getAccount, tryGetAuth, getOwnUser, getIdentity } from '../selectors'; import { getHaveServerData } from '../haveServerDataSelectors'; import { roleIsAtLeast } from '../permissionSelectors'; import { Role } from '../api/permissionsTypes'; import { authOfAccount, identityOfAccount, identityOfAuth } from '../account/accountMisc'; import { BackoffMachine, TimeoutError } from '../utils/async'; import { ApiError, RequestError, Server5xxError, NetworkError, ServerTooOldError, kMinAllowedServerVersion, } from '../api/apiErrors'; import * as logging from '../utils/logging'; import { showErrorAlert } from '../utils/info'; import { tryFetch, fetchPrivateMessages } from '../message/fetchActions'; import { MIN_RECENTPMS_SERVER_VERSION } from '../pm-conversations/pmConversationsModel'; import { sendOutbox } from '../outbox/outboxActions'; import { initNotifications, tryStopNotifications } from '../notification/notifTokens'; import { kMinSupportedVersion, kNextMinSupportedVersion, kServerSupportDocUrl, } from '../common/ServerCompatBanner'; import { maybeRefreshServerEmojiData } from '../emoji/data'; const registerStart = (): PerAccountAction => ({ type: REGISTER_START, }); const registerAbortPlain = (reason: RegisterAbortReason): PerAccountAction => ({ type: REGISTER_ABORT, reason, }); const registerAbort = (reason: RegisterAbortReason): ThunkAction<Promise<void>> => async (dispatch, getState) => { dispatch(registerAbortPlain(reason)); if (getHaveServerData(getState()) && reason !== 'unexpected') { // Try again, forever if necessary; the user has an interactable UI and // can look at stale data while waiting. // // Do so by lying that the server has told us our queue is invalid and // we need a new one. // // TODO: Stop lying. ;) // TODO: Instead, let the retry be on-demand, with a banner. dispatch(deadQueue()); // eslint-disable-line no-use-before-define } else { // Tell the user we've given up and let them try the same account or a // different account from the account picker. showErrorAlert( // TODO: Set up these user-facing strings for translation once // `initialFetchAbort`'s callers all have access to a `GetText` // function. One place we dispatch the register is in StoreProvider, // which isn't a descendant of `TranslationProvider`. 'Connection failed', (() => { const realmStr = getIdentity(getState()).realm.toString(); switch (reason) { case 'server': return roleIsAtLeast(getOwnUser(getState()).role, Role.Admin) ? `Could not connect to ${realmStr} because the server encountered an error. Please check the server logs.` : `Could not connect to ${realmStr} because the server encountered an error. Please ask an admin to check the server logs.`; case 'network': return `The network request to ${realmStr} failed.`; case 'timeout': return `Gave up trying to connect to ${realmStr} after waiting too long.`; case 'unexpected': return `Unexpected error while trying to connect to ${realmStr}.`; default: ensureUnreachable(reason); return ''; } })(), ); NavigationService.dispatch(resetToAccountPicker()); } }; const registerComplete = (data: InitialData): PerAccountAction => ({ type: REGISTER_COMPLETE, data, }); /** * Connect to the Zulip event system for real-time updates. * * For background on the Zulip event system and how we use it, see docs from * the client-side perspective: * path_to_url * and a mainly server-side perspective: * path_to_url * * First does POST /register, which is sometimes called the "initial fetch". * because the response comes with a large payload of current-state data * that we fetch as part of initializing the event queue: * path_to_url#the-initial-data-fetch * * Then immediately starts an async loop to poll for events. * * We fetch private messages here so that we can show something useful in * the PM conversations screen, but we hope to stop doing this soon (see * note at `fetchPrivateMessages`). We fetch messages in a few other places: * to initially populate a message list (`ChatScreen`), to grab more * messages on scrolling to the top or bottom of the message list * (`fetchOlder` and `fetchNewer`), and to grab search results * (`SearchMessagesScreen`). */ export const registerAndStartPolling = (): ThunkAction<Promise<void>> => async (dispatch, getState, { getGlobalSettings }) => { const account = getAccount(getState()); const identity = identityOfAccount(account); const auth = authOfAccount(account); const haveServerData = getHaveServerData(getState()); dispatch(registerStart()); let initData: InitialData; try { initData = await tryFetch( // Currently, no input we're giving `registerForEvents` is // conditional on the server version / feature level. If we // need to do that, make sure that data is up-to-date -- we've // been using this `registerForEvents` call to update the // feature level in Redux, which means the value in Redux will // be from the *last* time it was run. That could be a long // time ago, like from the previous app startup. () => api.registerForEvents(auth), // We might have (potentially stale) server data already. If // we do, we'll be showing some UI that lets the user see that // data. If we don't, we'll be showing a full-screen loading // indicator that prevents the user from doing anything useful // -- if that's the case, don't bother retrying on 5xx errors, // to save the user's time and patience. They can retry // manually if they want. haveServerData, ); } catch (errorIllTyped) { const e: mixed = errorIllTyped; // path_to_url if (e instanceof ApiError) { // This should only happen when `auth` is no longer valid. No // use retrying; just log out. // Why not dispatch tryStopNotifications too? Because we don't // expect any API requests to succeed with an invalid auth. And we // *do* expect that whatever invalidated the auth also caused the // server to forget all push tokens. dispatch(logout()); } else if (e instanceof ServerTooOldError) { showErrorAlert( // TODO(i18n): Set up these user-facing strings for translation // once callers all have access to a `GetText` function. One // place we dispatch this action is in StoreProvider, which // isn't a descendant of `TranslationProvider`. 'Could not connect', `${identity.realm.toString()} is running Zulip Server ${e.version.raw()}, which is unsupported. The minimum supported version is Zulip Server ${kMinSupportedVersion.raw()}.`, { url: kServerSupportDocUrl, globalSettings: getGlobalSettings(), }, ); logging.setTagsFromServerVersion(e.version); logging.error(e, { kMinAllowedServerVersion: kMinAllowedServerVersion.raw(), kMinSupportedVersion: kMinSupportedVersion.raw(), kNextMinSupportedVersion: kNextMinSupportedVersion.raw(), }); // Don't delay the logout action by awaiting this request: it may // take a long time or never succeed, and we need to kick the user // out immediately. dispatch(tryStopNotifications(account)); dispatch(logout()); } else if (e instanceof Server5xxError) { dispatch(registerAbort('server')); } else if (e instanceof NetworkError) { dispatch(registerAbort('network')); } else if (e instanceof TimeoutError) { // We always want to abort if we've kept the user waiting an // unreasonably long time. dispatch(registerAbort('timeout')); } else { dispatch(registerAbort('unexpected')); // $FlowFixMe[incompatible-cast]: assuming caught exception was Error logging.warn((e: Error), { message: 'Unexpected error during /register.', }); } return; } const serverVersion = initData.zulip_version; // Set Sentry tags for the server version immediately, so they're accurate // in case we hit an exception in reducers on `registerComplete` below. logging.setTagsFromServerVersion(serverVersion); if (!serverVersion.isAtLeast(kNextMinSupportedVersion)) { // The server version is either one we already don't support, or one // we'll stop supporting the next time we increase our minimum supported // version. Warn so that we have an idea of how widespread this is. // (Include the coarse version in the warning message, so that it splits // into separate Sentry "issues" by coarse version. The Sentry events // will also have the detailed version, from the call above to // `logging.setTagsFromServerVersion`.) logging.warn(`Old server version: ${serverVersion.classify().coarse}`); } dispatch(registerComplete(initData)); // eslint-disable-next-line no-use-before-define dispatch(startEventPolling(initData.queue_id, initData.last_event_id)); // This is part of "register" in that it fills in some missing /register // functionality for older servers; see fetchPrivateMessages for detail. if (!serverVersion.isAtLeast(MIN_RECENTPMS_SERVER_VERSION)) { dispatch(fetchPrivateMessages()); } // We can think of this as part of "register" because it fetches data // that *would've* been in the /register response, except that we pulled // it out to its own endpoint as part of a caching strategy, because the // data changes infrequently. // // It's fine not to set the payload in Redux atomically with the // "proper" /register data in registerComplete. That's because: // - It's not designed to get updated by events, since the data only // changes on a server restart. So #5434 can't be active; that's // "Handle event-vs-fetch races soundly." // - There aren't any dependencies between the /register payload and // this payload, in either direction. (E.g., key-value lookups.) // - While it's possible for the first refreshServerEmojiData to // arrive very late or not at all, following a registerComplete, // Flow will help us ensure that we fail gracefully with a fallback // during the time that the data is missing. During that time, we'll // act just the same as we do for pre-6.0 servers, which don't offer // the endpoint. // // TODO(server-6.0): Change or remove "pre-6.0" comment above. dispatch(maybeRefreshServerEmojiData(initData.server_emoji_data_url)); }; /** * Handle a single Zulip event from the server. * * This is part of our use of the Zulip events system; see `registerAndStartPolling` * for discussion. */ const handleEvent = (event: GeneralEvent, dispatch, getState) => { addBreadcrumb({ category: 'z-event', level: 'info', data: { type: event.type, ...(event.op !== undefined && { op: event.op }) }, }); try { const action = eventToAction(getState(), event); if (!action) { return; } // These side effects should not be moved to reducers, which // are explicitly not the place for side effects (see // path_to_url dispatch(doEventActionSideEffects(action)); // Now dispatch the plain-object action, for our reducers to handle. dispatch(action); } catch (e) { // We had an error processing the event. Log it and carry on. logging.error(e); } }; /** * Poll an event queue on the Zulip server for updates, in a loop. * * This is part of our use of the Zulip events system; see `registerAndStartPolling` * for discussion. */ export const startEventPolling = (queueId: string, eventId: number): ThunkAction<Promise<void>> => async (dispatch, getState) => { let lastEventId = eventId; const backoffMachine = new BackoffMachine(); while (true) { const auth = tryGetAuth(getState()); if (!auth) { // This account is not logged in. break; } // `auth` represents the active account. It might be different from // the one in the previous loop iteration, if we did a backoff wait. // TODO(#5009): Is that really quite OK? let events = undefined; try { const response = await api.pollForEvents(auth, queueId, lastEventId); events = response.events; if (getState().session.eventQueueId === null) { // We don't want to keep polling, e.g., because we've logged out; // see `PerAccountSessionState.eventQueueId` for other cases. break; } else if (!isEqual(getIdentity(getState()), identityOfAuth(auth))) { // During the last poll, the active account changed. Stop polling // for the previous one. // TODO(#5005): Remove this conditional as unreachable, once `auth` // represents the current account (instead of secretly // representing the global "active account" which can change.) break; } else if (queueId !== getState().session.eventQueueId) { // While the most recent poll was happening, another queue was // established for this account, and we've started polling on that // one. Stop polling on this one. // // In theory this could happen if you logged out of this account and // logged back in again. // // TODO(#5009): Instead of this conditional, abort the // `api.pollForEvents` immediately when `eventQueueId` becomes // `null`, then break at that time? break; } } catch (errorIllTyped) { const e: mixed = errorIllTyped; // path_to_url // We had an error polling the server for events. if (e instanceof RequestError && e.httpStatus === 401) { // 401 Unauthorized -> our `auth` is invalid. No use retrying. // Why not dispatch tryStopNotifications too? Because we don't // expect any API requests to succeed with an invalid auth. And we // *do* expect that whatever invalidated the auth also caused the // server to forget all push tokens. dispatch(logout()); break; } // protection from inadvertent DDOS await backoffMachine.wait(); if (e instanceof ApiError && e.code === 'BAD_EVENT_QUEUE_ID') { // The event queue is too old or has been garbage collected. dispatch(deadQueue()); // eslint-disable-line no-use-before-define break; } continue; } for (const event of events) { handleEvent(event, dispatch, getState); } lastEventId = Math.max(lastEventId, ...events.map(x => x.id)); } }; const deadQueuePlain = (): PerAccountAction => ({ type: DEAD_QUEUE, }); const deadQueue = (): ThunkAction<Promise<void>> => async (dispatch, getState) => { dispatch(deadQueuePlain()); await dispatch(registerAndStartPolling()); // TODO(#3881): Lots of issues with outbox sending dispatch(sendOutbox()); dispatch(initNotifications()); }; ```
/content/code_sandbox/src/events/eventActions.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
3,686
```javascript /* @flow strict-local */ import type { LocalizableText } from '../types'; /** * A LocalizableText that always resolves to the given string. * * Useful for wrapping user data, like the name of a user or a stream, * in a context where we sometimes also show a string that needs translation. */ export function noTranslation(value: string): LocalizableText { return { text: '{_}', values: { _: value } }; } ```
/content/code_sandbox/src/i18n/i18n.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
94
```javascript /* @flow strict-local */ import invariant from 'invariant'; import * as logging from '../../utils/logging'; import * as eg from '../../__tests__/lib/exampleData'; import eventToAction from '../eventToAction'; import { EVENT_NEW_MESSAGE } from '../../actionConstants'; import { AvatarURL } from '../../utils/avatar'; function actionMatchesType(action, type): boolean %checks { return action !== null && action.type === type; } describe('eventToAction', () => { const state = eg.plusReduxState; test('filter out unknown event type', () => { // $FlowFixMe[prop-missing]: teach Flow about Jest mocks logging.error.mockReturnValue(); expect(eventToAction(state, { type: 'some unknown type' })).toBe(null); // $FlowFixMe[prop-missing]: teach Flow about Jest mocks expect(logging.error.mock.calls).toHaveLength(1); // $FlowFixMe[prop-missing]: teach Flow about Jest mocks logging.error.mockReset(); }); test('filter out a known boring event type', () => { const event = { type: 'heartbeat' }; expect(eventToAction(state, event)).toBe(null); }); test('for known event, process and return', () => { const event = { type: 'presence' }; const action = eventToAction(state, event); expect(action).not.toBe(null); }); describe('type: message', () => { const serverMessage = { ...eg.streamMessage(), reactions: [], avatar_url: null, edit_history: [ { prev_content: 'foo', prev_rendered_content: '<p>foo</p>', prev_stream: eg.stream.stream_id, prev_topic: 'bar', stream: eg.otherStream.stream_id, timestamp: 0, topic: 'bar!', user_id: eg.selfUser.user_id, }, ], flags: undefined, }; describe('recent servers', () => { const event = { type: 'message', message: serverMessage, flags: ['read'] }; const action = eventToAction(state, event); test('EVENT_NEW_MESSAGE produced', () => { expect(actionMatchesType(action, EVENT_NEW_MESSAGE)).toBeTrue(); }); invariant(actionMatchesType(action, EVENT_NEW_MESSAGE), 'EVENT_NEW_MESSAGE produced'); test('Adds event.flags', () => { expect(action.message.flags).toEqual(['read']); }); test('Converts avatar_url', () => { expect(action.message.avatar_url).toBeInstanceOf(AvatarURL); }); test('Keeps edit_history if allowEditHistory is true', () => { // eslint-disable-next-line no-shadow const action = eventToAction( eg.reduxStatePlus({ realm: { ...eg.plusReduxState.realm, allowEditHistory: true } }), event, ); invariant(actionMatchesType(action, EVENT_NEW_MESSAGE), 'EVENT_NEW_MESSAGE produced'); expect(action.message.edit_history).not.toBeNull(); expect(action.message.edit_history).toEqual(serverMessage.edit_history); }); test('Drops edit_history if allowEditHistory is false', () => { // eslint-disable-next-line no-shadow const action = eventToAction( eg.reduxStatePlus({ realm: { ...eg.plusReduxState.realm, allowEditHistory: false } }), event, ); invariant(actionMatchesType(action, EVENT_NEW_MESSAGE), 'EVENT_NEW_MESSAGE produced'); expect(action.message.edit_history).toBeNull(); }); }); describe('edit_history for FL <118', () => { const serverMessageInner = { ...serverMessage, edit_history: [ { prev_content: 'foo', prev_rendered_content: '<p>foo</p>', prev_stream: eg.stream.stream_id, prev_subject: 'bar', timestamp: 0, user_id: eg.selfUser.user_id, }, ], }; const event = { type: 'message', message: serverMessageInner }; const action = eventToAction( eg.reduxStatePlus({ accounts: [{ ...eg.plusReduxState.accounts[0], zulipFeatureLevel: 117 }], }), event, ); test('EVENT_NEW_MESSAGE produced', () => { expect(actionMatchesType(action, EVENT_NEW_MESSAGE)).toBeTrue(); }); invariant(actionMatchesType(action, EVENT_NEW_MESSAGE), 'EVENT_NEW_MESSAGE produced'); test('edit_history dropped', () => { expect(action.message.edit_history).toBeNull(); }); }); }); }); ```
/content/code_sandbox/src/events/__tests__/eventToAction-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
970
```javascript /* @flow strict-local */ /* eslint-disable global-require */ /** * Message data for all languages we have message data for. * * Keys here are IETF BCP 47 language tags. * * The languages we offer in the UI are a subset of these; see * `src/settings/languages.js`. */ // Note that the filenames reflect a slightly different convention for // language names: they have the names given to them by the `tx` Transifex // client, which are based on the language names that appear in Transifex. export default { am: require('../../static/translations/messages_am.json'), ar: require('../../static/translations/messages_ar.json'), be: require('../../static/translations/messages_be.json'), bg: require('../../static/translations/messages_bg.json'), bn: require('../../static/translations/messages_bn.json'), bqi: require('../../static/translations/messages_bqi.json'), ca: require('../../static/translations/messages_ca.json'), cy: require('../../static/translations/messages_cy.json'), cs: require('../../static/translations/messages_cs.json'), da: require('../../static/translations/messages_da.json'), de: require('../../static/translations/messages_de.json'), el: require('../../static/translations/messages_el.json'), en: require('../../static/translations/messages_en.json'), 'en-GB': require('../../static/translations/messages_en_GB.json'), eo: require('../../static/translations/messages_eo.json'), es: require('../../static/translations/messages_es.json'), eu: require('../../static/translations/messages_eu.json'), fa: require('../../static/translations/messages_fa.json'), fi: require('../../static/translations/messages_fi.json'), fr: require('../../static/translations/messages_fr.json'), gl: require('../../static/translations/messages_gl.json'), gu: require('../../static/translations/messages_gu.json'), hi: require('../../static/translations/messages_hi.json'), hr: require('../../static/translations/messages_hr.json'), hu: require('../../static/translations/messages_hu.json'), id: require('../../static/translations/messages_id.json'), ig: require('../../static/translations/messages_ig.json'), it: require('../../static/translations/messages_it.json'), ja: require('../../static/translations/messages_ja.json'), ko: require('../../static/translations/messages_ko.json'), kw: require('../../static/translations/messages_kw.json'), lt: require('../../static/translations/messages_lt.json'), lv: require('../../static/translations/messages_lv.json'), ml: require('../../static/translations/messages_ml.json'), mn: require('../../static/translations/messages_mn.json'), my: require('../../static/translations/messages_my.json'), nl: require('../../static/translations/messages_nl.json'), no: require('../../static/translations/messages_no.json'), pa: require('../../static/translations/messages_pa.json'), pcm: require('../../static/translations/messages_pcm.json'), pl: require('../../static/translations/messages_pl.json'), pt: require('../../static/translations/messages_pt.json'), 'pt-BR': require('../../static/translations/messages_pt_BR.json'), 'pt-PT': require('../../static/translations/messages_pt_PT.json'), ro: require('../../static/translations/messages_ro.json'), ru: require('../../static/translations/messages_ru.json'), sco: require('../../static/translations/messages_sco.json'), si: require('../../static/translations/messages_si.json'), sk: require('../../static/translations/messages_sk.json'), sr: require('../../static/translations/messages_sr.json'), sv: require('../../static/translations/messages_sv.json'), ta: require('../../static/translations/messages_ta.json'), te: require('../../static/translations/messages_te.json'), tl: require('../../static/translations/messages_tl.json'), tr: require('../../static/translations/messages_tr.json'), uk: require('../../static/translations/messages_uk.json'), ur: require('../../static/translations/messages_ur.json'), uz: require('../../static/translations/messages_uz.json'), vi: require('../../static/translations/messages_vi.json'), yue: require('../../static/translations/messages_yue.json'), 'zh-Hans': require('../../static/translations/messages_zh-Hans.json'), 'zh-Hant': require('../../static/translations/messages_zh-Hant.json'), 'zh-TW': require('../../static/translations/messages_zh_TW.json'), }; ```
/content/code_sandbox/src/i18n/messagesByLanguage.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
922
```javascript /* @flow strict-local */ import invariant from 'invariant'; import Immutable from 'immutable'; import { ZulipVersion } from '../utils/zulipVersion'; import { GravatarURL, UploadedAvatarURL, FallbackAvatarURL } from '../utils/avatar'; /** * PRIVATE: Exported only for tests. * * A special identifier for the type of thing to be replaced/revived. * * Use this in the replacer and reviver, below, to make it easier to * be consistent between them and avoid costly typos. */ export const SERIALIZED_TYPE_FIELD_NAME: '__serializedType__' = '__serializedType__'; /** * Like SERIALIZED_TYPE_FIELD_NAME, but with a distinguishing mark. * * Used in our strategy to ensure successful round-tripping when data * has a key identical to SERIALIZED_TYPE_FIELD_NAME. */ const SERIALIZED_TYPE_FIELD_NAME_ESCAPED: '__serializedType__value' = '__serializedType__value'; /** * Custom replacer for inventive data types JSON doesn't handle. * * To be passed to `JSON.stringify` as its second argument. New * replacement logic must also appear in `reviver` so they stay in * sync. */ // Don't make this an arrow function -- we need `this` to be a special // value; see // path_to_url#The_replacer_parameter. function replacer(key, value) { // The value at the current path before JSON.stringify called its // `toJSON` method, if present. // // When identifying what kind of thing we're working with, we // examine `origValue` instead of `value`, just in case calling // `toJSON` on that kind of thing would remove its identifying // features -- which is to say, just in case that kind of thing has // a `toJSON` method. // // For things that have a `toJSON` method, it may be convenient to // set `data` to `value`, if we trust that `toJSON` gives the output // we want to store there. And it would mean we don't discard the // work `JSON.stringify` did by calling `toJSON`. const origValue = this[key]; if (typeof origValue !== 'object' || origValue === null) { // `origValue` can't be one of our interesting data types, so, // just return it. return origValue; } switch (Object.getPrototypeOf(origValue)) { // Flow bug: path_to_url case (Date.prototype: $FlowIssue): return { data: value, [SERIALIZED_TYPE_FIELD_NAME]: 'Date' }; case (Set.prototype: $FlowIssue): return { data: [...value], [SERIALIZED_TYPE_FIELD_NAME]: 'Set' }; case (Map.prototype: $FlowIssue): return { data: [...value.entries()], [SERIALIZED_TYPE_FIELD_NAME]: 'Map' }; case (ZulipVersion.prototype: $FlowIssue): return { data: value, [SERIALIZED_TYPE_FIELD_NAME]: 'ZulipVersion' }; case (URL.prototype: $FlowIssue): return { data: value, [SERIALIZED_TYPE_FIELD_NAME]: 'URL' }; case (GravatarURL.prototype: $FlowIssue): return { data: GravatarURL.serialize(value), [SERIALIZED_TYPE_FIELD_NAME]: 'GravatarURL' }; case (UploadedAvatarURL.prototype: $FlowIssue): return { data: UploadedAvatarURL.serialize(value), [SERIALIZED_TYPE_FIELD_NAME]: 'UploadedAvatarURL', }; case (FallbackAvatarURL.prototype: $FlowIssue): return { data: FallbackAvatarURL.serialize(value), [SERIALIZED_TYPE_FIELD_NAME]: 'FallbackAvatarURL', }; case (Immutable.List.prototype: $FlowIssue): return { data: value, [SERIALIZED_TYPE_FIELD_NAME]: 'ImmutableList' }; case (Immutable.Map.prototype: $FlowIssue): { const firstKey = origValue.keySeq().first(); return { data: value, // We assume that any `Immutable.Map` will have // - all string keys, // - all numeric keys, or // - no keys (be empty). // // We store string-keyed maps with `ImmutableMap`, // number-keyed maps with `ImmutableMapNumKeys`, and empty // maps with either one of those (chosen arbitrarily) because // the reviver will give the same output for both of them // (i.e., an empty `Immutable.Map`). [SERIALIZED_TYPE_FIELD_NAME]: typeof firstKey === 'number' ? 'ImmutableMapNumKeys' : 'ImmutableMap', }; } default: { // If the identity of the first item in the prototype chain // isn't good enough as a distinguishing mark, we can put some // plain conditions here. } } // Don't forget to handle a value's `toJSON` method, if present, as // described above. invariant(typeof origValue.toJSON !== 'function', 'unexpected toJSON'); // If storing an interesting data type, don't forget to handle it // here, and in `reviver`. const origValuePrototype = Object.getPrototypeOf(origValue); invariant( // Flow bug: path_to_url origValuePrototype === (Object.prototype: $FlowIssue) || origValuePrototype === (Array.prototype: $FlowIssue), `stringify: unexpected class: ${origValuePrototype.constructor.name}`, ); // Ensure that objects with a [SERIALIZED_TYPE_FIELD_NAME] property // round-trip. if (SERIALIZED_TYPE_FIELD_NAME in origValue) { const copy = { ...origValue }; delete copy[SERIALIZED_TYPE_FIELD_NAME]; return { [SERIALIZED_TYPE_FIELD_NAME]: 'Object', data: copy, [SERIALIZED_TYPE_FIELD_NAME_ESCAPED]: origValue[SERIALIZED_TYPE_FIELD_NAME], }; } return origValue; } /** * Custom reviver for inventive data types JSON doesn't handle. * * To be passed to `JSON.parse` as its second argument. New * reviving logic must also appear in `replacer` so they stay in * sync. */ function reviver(key, value) { if (value !== null && typeof value === 'object' && SERIALIZED_TYPE_FIELD_NAME in value) { const data = value.data; switch (value[SERIALIZED_TYPE_FIELD_NAME]) { case 'Date': return new Date(data); case 'Set': return new Set(data); case 'Map': return new Map(data); case 'ZulipVersion': return new ZulipVersion(data); case 'URL': return new URL(data); case 'GravatarURL': return GravatarURL.deserialize(data); case 'UploadedAvatarURL': return UploadedAvatarURL.deserialize(data); case 'FallbackAvatarURL': return FallbackAvatarURL.deserialize(data); case 'ImmutableList': return Immutable.List(data); case 'ImmutableMap': return Immutable.Map(data); case 'ImmutableMapNumKeys': { return Immutable.Map(Object.keys(data).map(k => [Number.parseInt(k, 10), data[k]])); } case 'Object': return { ...data, [SERIALIZED_TYPE_FIELD_NAME]: value[SERIALIZED_TYPE_FIELD_NAME_ESCAPED], }; default: // This should be impossible for data that came from our // corresponding replacer, above. If we do have a bug that leads to // this case, there's nothing we can return that isn't likely to be // a corrupt data structure that causes a crash somewhere else // downstream; so just fail immediately. throw new Error(`Unhandled serialized type: ${value[SERIALIZED_TYPE_FIELD_NAME]}`); } } return value; } export function stringify(data: mixed): string { const result = JSON.stringify(data, replacer); if (result === undefined) { // Flow says that the output for JSON.stringify could be // undefined. From MDN: // // `JSON.stringify()` can return `undefined` when passing in // "pure" values like `JSON.stringify(function(){})` or // `JSON.stringify(undefined)`. // // We don't expect any of those inputs, but we'd want to know if // we get one, since it means something has gone quite wrong. throw new Error('undefined result for stringify'); } return result; } export function parse(data: string): mixed { return JSON.parse(data, reviver); } ```
/content/code_sandbox/src/storage/replaceRevive.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,862
```javascript /* @flow strict-local */ import LegacyAsyncStorage from '@react-native-async-storage/async-storage'; import invariant from 'invariant'; import { SQLDatabase } from './sqlite'; import * as logging from '../utils/logging'; // A better name for this class might be simply AsyncStorage. // But for now we reserve that name for the thing that's a (nearly) drop-in // replacement for the upstream AsyncStorage, which isn't this class itself // but rather an instance of it. export class AsyncStorageImpl { // This is a Promise rather than directly a SQLDatabase because... well, // anything that wants to consume it needs to be prepared to wait in any // case, so will be calling something like `_db()` that returns a Promise. // And then that might as well return the same Promise every time, rather // than unwrapping it up front and wrapping it in a new Promise on each call. dbSingleton: void | Promise<SQLDatabase> = undefined; version: number = 1; // Hard-coded for now, with just the migration from legacy AsyncStorage. _db(): Promise<SQLDatabase> { if (this.dbSingleton) { return this.dbSingleton; } this.dbSingleton = this._initDb(); return this.dbSingleton; } async _initDb() { const db = new SQLDatabase('zulip.db'); await db.transaction(tx => { // This schema is just like the one in RN's AsyncStorage (see // ReactDatabaseSupplier.java), except for a small fix: the latter // doesn't mention NOT NULL on the `key` column. In standard SQL // that'd be redundant with PRIMARY KEY (though c'mon, EIBTI) but // SQLite has a quirk that PRIMARY KEY does *not* imply NOT NULL: // path_to_url#the_primary_key tx.executeSql(` CREATE TABLE IF NOT EXISTS keyvalue ( key TEXT PRIMARY KEY NOT NULL, value TEXT NOT NULL ) `); // TODO consider adding STRICT to the schema; requires SQLite 3.37, // from 2021-11: path_to_url // We'll use this to record successful migrations, such as from legacy // AsyncStorage. // There should only be one row. tx.executeSql(` CREATE TABLE IF NOT EXISTS migration ( version INTEGER NOT NULL ) `); }); await this._migrate(db); return db; } async _migrate(db) { const version = (await db.query('SELECT version FROM migration LIMIT 1'))[0]?.version ?? 0; if (version === this.version) { return; } if (version > this.version) { logging.error('AsyncStorage: schema is from future', { targetVersion: this.version, storedVersion: version, }); throw new Error('AsyncStorage: schema is from future'); } invariant(this.version === 1, 'AsyncStorage._migrate currently assumes target version 1'); if (version !== 0) { logging.error('AsyncStorage: no migration path', { storedVersion: version, targetVersion: this.version, }); throw new Error('AsyncStorage: no migration path'); } // Perform the migration. For now, we're hardcoding that the only // migration is from version 0 to version 1. await db.transaction(async tx => { await this._migrateFromLegacyAsyncStorage(tx); tx.executeSql('DELETE FROM migration'); tx.executeSql('INSERT INTO migration (version) VALUES (?)', [this.version]); }); } // The migration strategy. How do we move the user's data from the old // AsyncStorage to the new database? // // On Android, we could bypass this by arranging to use the old thing's // database and table name. Might need some tweaking of expo-sqlite in // order to control the database name fully enough. // // But on iOS, it's not so simple. Values over 1024 characters // (RCTInlineValueThreshold, in RNCAsyncStorage.m) are written as separate // files. Values up to that threshold go into a single JSON blob (for the // whole key-value store) that's written as one file. So rather than try // to duplicate that, we just keep the legacy AsyncStorage as a // dependency, and use it to read the old data if the new doesn't exist. // // Then once we're doing that for iOS, might as well do it for Android // too, and not have to follow the old names. async _migrateFromLegacyAsyncStorage(tx) { // TODO: It would be nice to reduce the LegacyAsyncStorage dependency to // be read-only -- in particular, for new installs to stop creating an // empty legacy store, which on Android happens just from initializing // the legacy AsyncStorage module. This will basically mean vendoring // the library into src/third-party/, and then stripping out // everything not needed for read-only use. const keys = await LegacyAsyncStorage.getAllKeys(); const values = await Promise.all(keys.map(key => LegacyAsyncStorage.getItem(key))); tx.executeSql('DELETE FROM keyvalue'); for (let i = 0; i < keys.length; i++) { const value = values[i]; if (value == null) { // TODO warn continue; } tx.executeSql('INSERT INTO keyvalue (key, value) VALUES (?, ?)', [keys[i], value]); } // TODO: After this migration has been out for a while and things seem fine, // add another to delete the legacy storage. } async getItem(key: string): Promise<string | null> { const db = await this._db(); const rows = await db.query<{ value: string }>('SELECT value FROM keyvalue WHERE key = ?', [ key, ]); return rows.length > 0 ? rows[0].value : null; } async setItem(key: string, value: string): Promise<void> { const db = await this._db(); return db.transaction(tx => { tx.executeSql('INSERT OR REPLACE INTO keyvalue (key, value) VALUES (?, ?)', [key, value]); }); } async multiSet(keyValuePairs: Array<Array<string>>): Promise<void> { const db = await this._db(); return db.transaction(tx => { for (const kv of keyValuePairs) { tx.executeSql('INSERT OR REPLACE INTO keyvalue (key, value) VALUES (?, ?)', kv); } }); } async removeItem(key: string): Promise<void> { const db = await this._db(); return db.transaction(tx => { tx.executeSql('DELETE FROM keyvalue WHERE key = ?', [key]); }); } async getAllKeys(): Promise<string[]> { const db = await this._db(); const rows = await db.query<{ key: string }>('SELECT key FROM keyvalue'); return rows.map(r => r.key); } async clear(): Promise<void> { const db = await this._db(); return db.transaction(tx => { tx.executeSql('DELETE FROM keyvalue'); }); } /** * Forget the AsyncStorage implementation's internal, non-persistent state. * * This should only be used in tests. It has an effect similar to exiting * the program (but leaving the persistent storage intact), so that the * next use of AsyncStorage will behave as if freshly starting up the * program. */ async devForgetState(): Promise<void> { this.dbSingleton = undefined; } } /** * A sound, nearly-drop-in replacement for RN's AsyncStorage. * * The methods should be invoked as methods, like `AsyncStorage.foo()`. * * Under that convention, and for the methods it has, this is a perfectly * drop-in replacement for the upstream AsyncStorage, meaning that it will * always satisfy the spec for how the upstream AsyncStorage behaves. * * The difference is that it also satisfies a tighter spec: each operation * either happens completely or not at all. No operation corrupts the * database or has only partial effect, even if the process is killed or * encounters I/O errors. * * This is accomplished by using SQLite, and doing each operation in a * transaction. The upstream AsyncStorage does the same thing on Android; * but on iOS, it uses an ad-hoc database which is susceptible to complete * corruption if interrupted. * * (If one pokes around other than by invoking the methods as methods, this * implementation has incidental other differences: these are real methods * that come from a prototype and use `this`, while the upstream * AsyncStorage is a plain object with functions as its own properties.) */ export const AsyncStorage: AsyncStorageImpl = new AsyncStorageImpl(); ```
/content/code_sandbox/src/storage/AsyncStorage.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,938
```javascript // @flow strict-local import { openDatabase, type SQLResultSet, type WebSQLDatabase, type SQLTransaction as WebSQLTransaction, } from 'expo-sqlite'; import invariant from 'invariant'; /* eslint-disable no-use-before-define */ /* eslint-disable no-underscore-dangle */ /* eslint-disable no-void */ /* eslint-disable ft-flow/type-id-match */ type SQLArgument = number | string; /** * A Promise-based wrapper on expo-sqlite. */ export class SQLDatabase { db: WebSQLDatabase; constructor(name: string) { this.db = openDatabase(name); } /** * Like the `transaction` method in expo-sqlite, but promisified. * * The transaction will stay open as long as the Promise the callback * returned stays unsettled. That means the callback can use `await` as * usual. * * For performance reasons, though, avoid using `await` other than on * `executeSql` results or already-settled values. In particular, avoid * awaiting network requests or other things that take time but don't need * to occupy the CPU. That's because the current implementation of this * method effectively busy-waits, by making trivial SQL queries, when SQL * queries are getting to run but the transaction has no other SQL queries * outstanding. */ // TODO: It'd be good to be able to remove the performance warning above. // (Well, part of it; having a transaction block on something // potentially really slow like a network request will generally be a // bad idea just because of blocking other things in the app from // proceeding, even if it doesn't involve busy-waiting.) // // This will involve modifying expo-sqlite, replacing much of the // node-websql code under it. // // More background on that performance warning: // path_to_url#discussion_r779300110 transaction(cb: SQLTransaction => void | Promise<void>): Promise<void> { return new Promise((resolve, reject) => this.db.transaction( tx => void keepQueueLiveWhile(tx, () => cb(new SQLTransactionImpl(this, tx))), reject, resolve, ), ); } /** * Like the `readTransaction` method in expo-sqlite, but promisified. * * See `transaction` for performance considerations on how to use `await` * inside the callback. */ readTransaction(cb: SQLTransaction => void | Promise<void>): Promise<void> { return new Promise((resolve, reject) => this.db.readTransaction( tx => void keepQueueLiveWhile(tx, () => cb(new SQLTransactionImpl(this, tx))), reject, resolve, ), ); } /** * Convenience method for a single read-only query. * * This uses `readTransaction` to do its work, so it will be serialized * relative to any transactions made with `transaction`. * * Warning: nothing checks that the returned rows actually match the given * Row type. The actual rows will be objects keyed on the column names in * the query. For effective type-checking, always pass a type parameter * that matches the query. For example: * db.query<{ foo: number, bar: string }>('SELECT foo, bar FROM stuff'); */ async query<Row: { ... } = { ... }>( statement: string, args?: $ReadOnlyArray<SQLArgument>, ): Promise<Row[]> { let p: void | Promise<Row[]> = undefined; await this.readTransaction(tx => { p = tx.executeSql(statement, args).then(r => r.rows._array); }); invariant(p, 'transaction finished; statement promise should be initialized'); return p; } } // An absurd little workaround for expo-sqlite, or really the @expo/websql / // node-websql library under it, being too eager to check a transaction's // queue and declare it complete. // // Also for it not handling errors in callbacks, so that an exception in a // transaction's application-level code causes it to commit (!) if the // transaction callback itself throws an exception, and to get the whole // database object stuck if a statement callback throws an exception: // path_to_url#discussion_r779288813 // path_to_url#discussion_r779300110 // Instead, on any such exception we cause the transaction to roll back. async function keepQueueLiveWhile(tx: WebSQLTransaction, f: () => void | Promise<void>) { let error = false; let done = false; // To prevent a commit before the transaction is actually ready for it, we // keep a trivial statement in the queue until we're done. It goes in // before we make our first `await`, and every time the queue reaches it // we synchronously put a new such statement in the queue, until the end. // // On the other hand if the app code for the transaction raised an // exception, we want to force the transaction to abort. We can do that // by issuing an invalid SQL statement. (Per the actual Web SQL Database // spec, we could do it by just throwing from this statement callback, but // node-websql has a bug. The bug has been half-fixed: // path_to_url // but expo-websql doesn't have that fix.) const hold = () => tx.executeSql('SELECT 1', [], () => error ? tx.executeSql('SELECT error') : done ? undefined : hold(), ); hold(); try { await f(); } catch { error = true; } finally { done = true; } // A neat touch would be to pass through the actual error message. // Sadly `tx.executeSql('SELECT ?, error', [String(error)])` doesn't // produce any hint of the string; the resulting message is just // SQLITE_ERROR: no such column: error // So, encode the error string as a SQL identifier? (With a prefix // to ensure it doesn't hit a builtin, or reserved word?) Need to // be darn sure the encoding is correct and doesn't cause injection. // // For now, we content ourselves with aborting the transaction at all. } class SQLTransactionImpl { db: SQLDatabase; tx: WebSQLTransaction; constructor(db: SQLDatabase, tx: WebSQLTransaction) { this.db = db; this.tx = tx; } /** * Like the `executeSql` method in expo-sqlite, but promisified. */ executeSql(statement: string, args?: $ReadOnlyArray<SQLArgument>): Promise<SQLResultSet> { return new Promise((resolve, reject) => { this.tx.executeSql( statement, args, (t, r) => resolve(r), (t, e) => { reject(e); return true; // true means propagate the error and roll back the transaction }, ); }); } } export type SQLTransaction = SQLTransactionImpl; ```
/content/code_sandbox/src/storage/sqlite.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,583
```javascript /* @flow strict-local */ import invariant from 'invariant'; import { NativeModules } from 'react-native'; import { AsyncStorage } from './AsyncStorage'; import * as logging from '../utils/logging'; const NODE_ENV = process.env.NODE_ENV; /** Assert the given string is plausibly the JSON encoding of some value. */ function assertPlausiblyJSONEncoded(value: string) { // To keep it quick, just look at the first character. This should be // enough to catch bugs that are just sending arbitrary strings. // // Every JSON value is either null, true, false, // or a number, string, array, or object. invariant(/^[ntf\-0-9"[{]/.test(value), 'value must be JSON-encoded'); } export default class CompressedAsyncStorage { static async getItem(key: string): Promise<string | null> { const item = await AsyncStorage.getItem(key); // It's possible that getItem() is called on uncompressed state, for // example when a user updates their app from a version without // compression to a version with compression. So we need to detect that. // // We can detect compressed states by inspecting the first few // characters of `result`. First, a leading 'z' indicates a // "Zulip"-compressed string; otherwise, the string is the only other // format we've ever stored, namely uncompressed JSON (which, // conveniently, never starts with a 'z'). // // Then, a Zulip-compressed string looks like `z|TRANSFORMS|DATA`, where // TRANSFORMS is a space-separated list of the transformations that we // applied, in order, to the data to produce DATA and now need to undo. // E.g., `zlib base64` means DATA is a base64 encoding of a zlib // encoding of the underlying data. We call the "z|TRANSFORMS|" part // the "header" of the string. if (item !== null && item.startsWith('z')) { // In this block, `item` is compressed state. const header = item.substring(0, item.indexOf('|', item.indexOf('|') + 1) + 1); if ( NativeModules.TextCompressionModule && header === NativeModules.TextCompressionModule.header ) { // TODO: It'd be real nice to handle this decompression on the // native side within getItem, so that we pass the data one way // native->JS instead of three ways native->JS->native->JS. return NativeModules.TextCompressionModule.decompress(item); } else { // Panic! If we are confronted with an unknown format, there is // nothing we can do to save the situation. Log an error and ignore // the data. This error should not happen unless a user downgrades // their version of the app. const err = new Error(`No decompression module found for format ${header}`); logging.error(err); throw err; } } // Uncompressed state return item; } /** (The value must be a result of `JSON.stringify`.) */ // The invariant that the value is JSON is relied on by `getItem`, to // guarantee that our compression header can't appear in uncompressed data. static async setItem(key: string, value: string): Promise<mixed> { if (NODE_ENV !== 'production') { assertPlausiblyJSONEncoded(value); } return AsyncStorage.setItem( key, NativeModules.TextCompressionModule ? await NativeModules.TextCompressionModule.compress(value) : value, ); } /** (Each value must be a result of `JSON.stringify`.) */ // The invariant that the value is JSON is relied on by `getItem`, to // guarantee that our compression header can't appear in uncompressed data. static async multiSet(keyValuePairs: Array<Array<string>>): Promise<mixed> { if (NODE_ENV !== 'production') { // eslint-disable-next-line no-unused-vars for (const [_, value] of keyValuePairs) { assertPlausiblyJSONEncoded(value); } } return AsyncStorage.multiSet( NativeModules.TextCompressionModule ? await Promise.all( keyValuePairs.map(async ([key, value]) => [ key, // TODO: It'd be real nice to handle this compression on the // native side within multiSet, so that we pass the data one // way JS->native instead of three ways JS->native->JS->native. await NativeModules.TextCompressionModule.compress(value), ]), ) : keyValuePairs, ); } static removeItem: (key: string) => Promise<void> = key => AsyncStorage.removeItem(key); static getAllKeys: () => Promise<string[]> = () => AsyncStorage.getAllKeys(); static clear: () => Promise<void> = () => AsyncStorage.clear(); } ```
/content/code_sandbox/src/storage/CompressedAsyncStorage.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,074
```javascript // @flow strict-local import type { ReadWrite, SubsetProperties } from '../generics'; import { ZulipVersion } from '../utils/zulipVersion'; import type { GlobalState } from '../types'; import { objectFromEntries } from '../jsBackport'; // Like GlobalState, but making all properties optional. type PartialState = $ReadOnly<$Rest<GlobalState, { ... }>>; // Like GlobalState, but with only the properties from historicalStoreKeys. type StoreKeysState = SubsetProperties< GlobalState, { migrations: mixed, accounts: mixed, drafts: mixed, outbox: mixed, settings: mixed }, >; // Like GlobalState, but making optional all except historicalStoreKeys. // This is the type we pretend our migrations take and return. type LessPartialState = $ReadOnly<{ ...$Rest<GlobalState, { ... }>, ...StoreKeysState }>; /** * Exported only for tests. * * The value of `storeKeys` when the `dropCache` migrations were written. */ // prettier-ignore export const historicalStoreKeys: $ReadOnlyArray<$Keys<StoreKeysState>> = [ // Never edit this list. 'migrations', 'accounts', 'drafts', 'outbox', 'settings', // Why never edit? The existing migrations below that refer to // `dropCache` are relying on this continuing to have the same value. // So if `storeKeys` changes, we'll need a new separate `dropCache` with // the new list, for use in new migrations, while the existing migrations // continue to use the existing `dropCache` with this list. ]; /** * The value of `cacheKeys` as of migration 24. */ // prettier-ignore export const historicalCacheKeys24: $ReadOnlyArray<$Keys<GlobalState>> = [ // Never edit this list. 'flags', 'messages', 'mute', 'narrows', 'pmConversations', 'realm', 'streams', 'subscriptions', 'unread', 'userGroups', 'users', // Why never edit? Much like for `historicalStoreKeys` above, but in this // case this is about a one-off migration we don't expect to repeat. ]; /** * Drop all server data, as a rehydrate-time migration. * * For any change to our Redux state affecting the data we fetch from the * server, use this so that we simply re-fetch it from the server. * * If the change also affects any of the data in `historicalStoreKeys` * above, then the migration needs specific code to handle those too; * otherwise, `dropCache` suffices as the entire migration. * * Rationale: Most of our data is just copied from the server, and gets routinely * discarded any time the event queue expires and we make a new `/register` * call. That's much more frequent than a new app release, let alone one * with a data migration... so forcing the same thing in a migration is * inexpensive, and makes a simple way to handle most migrations. * * One important difference from an expired event queue: `DEAD_QUEUE` * leaves the stale data mostly in place, to be clobbered by fresh data * by the subsequent `REGISTER_COMPLETE`. Here, because the old data may not work * with the current code at all, we have to actually discard it up front. * The behavior is similar to `ACCOUNT_SWITCH`, which also discards most * data: we'll show the loading screen while fetching initial data. See * the `REHYDRATE` handlers in `sessionReducer` and `navReducer` for how * that happens. */ function dropCache(state: LessPartialState): LessPartialState { const result: $Shape<ReadWrite<LessPartialState>> = {}; historicalStoreKeys.forEach(key => { // $FlowFixMe[prop-missing] /* $FlowFixMe[incompatible-type] This is well-typed only because it's the same `key` twice. */ result[key] = state[key]; }); return result; } // This is the inward-facing type; see later export for jsdoc. const migrationsInner: {| [string]: (LessPartialState) => LessPartialState |} = { // The type is a lie, in several ways: // * The actual object contains only the properties we persist: // those in `storeKeys` and `cacheKeys`, but not `discardKeys`. // * Conversely, the actual object may be missing some of the expected // properties. (We skip these migrations entirely if the `migrations` // property is missing, e.g. on first launch. But with our pre-#4841 // unsound storage, a previous run could have managed to store // `migrations` and any subset of the other keys.) // * The actual input is from an older version of the code, one with // different data structures -- after all, that's the point of the // migration -- which usually have a different type. // * For all but the latest migration, the same is true of the output. // // Still, it seems a more helpful approximation than nothing. Where the // falsehoods show through, we freely tell Flow to ignore them. // Example if removing a top-level subtree entirely: // import { AsyncStorage } from 'react-native'; // ... // AsyncStorage.removeItem('reduxPersist:messages'); '6': state => ({ // This rolls up all previous migrations, to clean up after our bug #3553. // Mostly we can just `dropCache`, to reload data from the server... ...dropCache(state), accounts: state.accounts.map(a => ({ ...a, // but in the case of `ackedPushToken` let's be a bit more precise, // and avoid clobbering it if present. (Don't copy this pattern for a // normal migration; this uncertainty is specific to recovering from #3553.) ackedPushToken: a.ackedPushToken !== undefined ? a.ackedPushToken : null, })), }), '8': dropCache, // Forget any acked push tokens, so we send them again. This is part of // fixing #3695, taking care of any users who were affected before they // got the version with the fix. '9': state => ({ ...state, accounts: state.accounts.map(a => ({ ...a, ackedPushToken: null, })), }), // Convert old locale names to new, more-specific locale names. '10': state => { const newLocaleNames = { zh: 'zh-Hans', id: 'id-ID' }; // $FlowIgnore[prop-missing]: `locale` renamed to `language` in 31 // $FlowIgnore[incompatible-type]: `locale` renamed to `language` in 31 const locale: string = state.settings.locale; const newLocale = newLocaleNames[locale] ?? locale; // $FlowIgnore[prop-missing] return { ...state, settings: { ...state.settings, locale: newLocale, }, }; }, // Fixes #3567 for users with cached realm urls with multiple trailing slashes. '11': state => ({ ...state, accounts: state.accounts.map(a => ({ ...a, /* $FlowIgnore[prop-missing]: `a.realm` is a string until migration 15 */ realm: a.realm.replace(/\/+$/, ''), })), }), // Add Accounts.zulipVersion, as string | null. '12': state => ({ ...state, accounts: state.accounts.map(a => ({ ...a, zulipVersion: null, })), }), // Convert Accounts.zulipVersion from `string | null` to `ZulipVersion | null`. '13': state => ({ ...state, accounts: state.accounts.map(a => ({ ...a, zulipVersion: typeof a.zulipVersion === 'string' ? new ZulipVersion(a.zulipVersion) : null, })), }), // Add Accounts.zulipFeatureLevel, as number | null. '14': state => ({ ...state, accounts: state.accounts.map(a => ({ ...a, zulipFeatureLevel: null, })), }), // Convert Accounts[].realm from `string` to `URL` '15': state => ({ ...state, accounts: state.accounts.map(a => ({ ...a, /* $FlowIgnore[incompatible-call]: `a.realm` will be a string here */ realm: new URL(a.realm), })), }), // Convert `narrows` from object-as-map to `Immutable.Map`. '16': dropCache, // Convert messages[].avatar_url from `string | null` to `AvatarURL`. '17': dropCache, // Convert `UserOrBot.avatar_url` from raw server data to // `AvatarURL`. '18': dropCache, // Change format of keys representing narrows: from JSON to our format, // then for PM narrows adding user IDs. '21': state => ({ ...dropCache(state), // The old format was a rather hairy format that we don't want to // permanently keep around the code to parse. For PMs, there's an // extra wrinkle in that any conversion would require using additional // information to look up the IDs. Drafts are inherently short-term, // and are already discarded whenever switching between accounts; // so we just drop them here. drafts: {}, }), // Change format of keys representing PM narrows, dropping emails. '22': state => ({ ...dropCache(state), drafts: objectFromEntries( Object.keys(state.drafts).map(key => // NB the original version of this migration was buggy; it ended up // just dropping drafts outright for PM narrows. Fortunately that's // not all that bad; see 21 above where we chose that same behavior. [key.replace(/^pm:d:(.*?):.*/s, 'pm:$1'), state.drafts[key]], ), ), }), // Convert `messages` from object-as-map to `Immutable.Map`. '23': dropCache, // Dummy `dropCache` for #4458. // See `purge` call in src/third/redux-persist/persistStore.js. '24': dropCache, // Convert `unread.streams` from over-the-wire array to `Immutable.Map`. '25': dropCache, // Rename locale `id-ID` back to `id`. '26': state => { // $FlowIgnore[prop-missing]: `locale` renamed to `language` in 31 // $FlowIgnore[incompatible-type]: `locale` renamed to `language` in 31 const locale: string = state.settings.locale; const newLocale = locale === 'id-ID' ? 'id' : locale; // $FlowIgnore[prop-missing] return { ...state, settings: { ...state.settings, locale: newLocale, }, }; }, // Remove accounts with "in-progress" login state (empty `.email`), // after #4491 '27': state => ({ ...state, accounts: state.accounts.filter(a => a.email !== ''), }), // Add "open links with in-app browser" setting. '28': state => ({ ...state, settings: { ...state.settings, browser: 'default', }, }), // Make `sender_id` on `Outbox` required. '29': state => ({ ...state, outbox: state.outbox.filter(o => o.sender_id !== undefined), }), // Add `doNotMarkMessagesAsRead` in `SettingsState`. // (At the time, we used no migration and let this just be handled // automatically by merging with the new initial state. For similar // changes today, we use an explicit migration. See 37 below, which added // a migration corresponding to what we would have had here.) // Use valid language tag for Portuguese (Portugal) // $FlowIgnore[prop-missing]: `locale` renamed to `language` in 31 '30': state => ({ ...state, settings: { ...state.settings, locale: // $FlowIgnore[prop-missing] state.settings.locale === 'pt_PT' ? 'pt-PT' : state.settings.locale, }, }), // Rename to `state.settings.language` from `state.settings.locale`. '31': state => { // $FlowIgnore[prop-missing]: migration fudge const { locale, ...settingsRest } = state.settings; return { ...state, settings: { ...settingsRest, // $FlowIgnore[incompatible-cast] - is string when migration runs language: (locale: string), }, }; }, // Switch to zh-TW as a language option instead of zh-Hant. '32': state => ({ ...state, settings: { ...state.settings, language: state.settings.language === 'zh-Hant' ? 'zh-TW' : state.settings.language, }, }), // Add Accounts.userId, as UserId | null. '33': state => ({ ...state, accounts: state.accounts.map(a => ({ ...a, userId: null, })), }), // Add mandatoryTopics to RealmState. // (At the time, we used no migration and let this just be handled // automatically by merging with the new initial state. For similar // changes today, we use an explicit migration. See 37 below, which added // a `dropCache` migration corresponding to what we would have had here.) // Drop server data from before Accounts had userId. This way we have an // invariant that if there's server data, then the active Account has userId. '34': dropCache, // Make `stream_id` on `StreamOutbox` required. '35': state => ({ ...state, outbox: state.outbox.filter(o => o.type === 'private' || o.stream_id !== undefined), }), // Add messageContentDeleteLimitSeconds and messageContentEditLimitSeconds // to RealmState. // (At the time, we used no migration and let this just be handled // automatically by merging with the new initial state. For similar // changes today, we use an explicit migration. See 37 below, which added // a `dropCache` migration corresponding to what we would have had here.) // Add pushNotificationsEnabled to RealmState. // (At the time, we used no migration and let this just be handled // automatically by merging with the new initial state. For similar // changes today, we use an explicit migration. See 37 below, which added // a `dropCache` migration corresponding to what we would have had here.) // Add `accounts[].lastDismissedServerPushSetupNotice`, as Date | null. '36': state => ({ ...state, accounts: state.accounts.map(a => ({ ...a, lastDismissedServerPushSetupNotice: null })), }), // Add name and description to RealmState. // (At the time, we used no migration and let this just be handled // automatically by merging with the new initial state. For similar // changes today, we use an explicit migration. See 37 below, which added // a `dropCache` migration corresponding to what we would have had here.) // Handle explicitly the migrations above (before 30, 34, 36, and this // one) that were done implicitly by the behavior of `autoRehydrate` on a // REHYDRATE action. /* $FlowIgnore[prop-missing]: `doNotMarkMessagesAsRead` renamed to `markMessagesReadOnScroll` in 52 */ '37': state => ({ // This handles the migrations affecting RealmState, before 34, 36, and here. ...dropCache(state), // Handle the migration before 30. settings: { ...state.settings, /* $FlowIgnore[prop-missing]: `doNotMarkMessagesAsRead` renamed to `markMessagesReadOnScroll` in 52 */ doNotMarkMessagesAsRead: state.settings.doNotMarkMessagesAsRead ?? false, }, }), // Change format of keys representing stream and topic narrows, adding IDs. '38': state => ({ ...state, drafts: objectFromEntries( // Just drop drafts for stream and topic narrows, for the same reasons // as for PM narrows in migration 21 above. Object.keys(state.drafts) .filter(key => !key.startsWith('stream:') && !key.startsWith('topic:')) .map(key => [key, state.drafts[key]]), ), }), // Change format of keys representing stream/topic narrows, dropping names. '39': state => ({ ...state, drafts: objectFromEntries( Object.keys(state.drafts).map(key => [ key .replace(/^stream:d:(\d+):.*/s, 'stream:$1') .replace(/^topic:d:(\d+):.*?\x00(.*)/s, 'topic:$1:$2'), state.drafts[key], ]), ), }), // Change `state.mute` data structure: was an array with stream names. '40': dropCache, // Add is_web_public to Stream and Subscription. '41': dropCache, // Add webPublicStreamsEnabled, enableSpectatorAccess, and // createWebPublicStreamPolicy to state.realm. '42': dropCache, // Add isOwner and isModerator to state.realm. '43': dropCache, // Add isGuest to state.realm. '44': dropCache, // Add createPublicStreamPolicy and createPrivateStreamPolicy to state.realm. '45': dropCache, // Add waitingPeriodThreshold to state.realm. '46': dropCache, // Add displayEmojiReactionUsers to state.realm. '47': dropCache, // Add customProfileFields to state.realm. '48': dropCache, // Add defaultExternalAccounts to state.realm. '49': dropCache, // Add allowEditHistory to state.realm. '50': dropCache, // Add serverEmojiData to state.realm. '51': dropCache, // Change boolean doNotMarkMessagesAsRead to enum markMessagesReadOnScroll '52': state => { // $FlowIgnore[prop-missing] const { doNotMarkMessagesAsRead, ...restSettings } = state.settings; return { ...state, settings: { ...restSettings, markMessagesReadOnScroll: // $FlowIgnore[incompatible-cast] - is boolean when migration runs (doNotMarkMessagesAsRead: boolean) ? 'never' // newline to narrow FlowIgnore's scope, above : 'always', }, }; }, // Add enableReadReceipts to state.realm. '53': dropCache, // Add emailAddressVisibility to state.realm '54': dropCache, // Drop old never-used message flags from state.flags. '55': dropCache, // Add presenceEnabled to state.realm. '56': dropCache, // Fix tiny case where an `undefined` could sneak in on ACCOUNT_SWITCH '57': state => ({ ...state, accounts: state.accounts.filter(Boolean) }), // Remove malformed partial `Account`s. Perhaps we could salvage some, if // they're just missing e.g. `zulipFeatureLevel` but we don't think the // bug affected many people, and when it did, it quickly followed a state // where `accounts` was empty, probably because the user asked to remove // the last account. '58': state => ({ ...state, accounts: state.accounts.filter(account => [ 'realm', 'apiKey', 'email', 'userId', 'zulipVersion', 'zulipFeatureLevel', 'ackedPushToken', 'lastDismissedServerPushSetupNotice', ].every(key => /* $FlowIgnore[method-unbinding]: This is the standard way to call `hasOwnProperty`. See discussion: path_to_url#narrow/stream/243-mobile-team/topic/Flow.20158.20errors/near/1375563 */ Object.prototype.hasOwnProperty.call(account, key), ), ), }), // Change `state.mute` data structure: was a plain JS Map. '59': dropCache, // Changed `state.presence` (twice), but no migration because that's in `discardKeys`. // Discard invalid enum values from `state.mute`. '60': dropCache, // Fix emailAddressVisibility accidentally being undefined/dropped '61': dropCache, // Add silenceServerPushSetupWarnings to accounts. '62': state => ({ ...state, accounts: state.accounts.map(a => ({ ...a, silenceServerPushSetupWarnings: false })), }), // Made UserOrBot.role required; removed is_owner, is_admin, is_guest '63': dropCache, // Add enableGuestUserIndicator to state.realm '64': dropCache, // Add pushNotificationsEnabledEndTimestamp to state.realm '65': dropCache, // Add `accounts[].lastDismissedServerNotifsExpiringBanner`, as Date | null. '66': state => ({ ...state, accounts: state.accounts.map(a => ({ ...a, lastDismissedServerNotifsExpiringBanner: null })), }), // TIP: When adding a migration, consider just using `dropCache`. // (See its jsdoc for guidance on when that's the right answer.) }; /** * Migrations for data persisted by previous versions of the app. * * These are run by `redux-persist-migrate` when the previously persisted * state is loaded ("rehydrated") by `redux-persist`; they transform that * state object before it's applied to our live state. The state includes * a version number to track which migrations are already reflected in it, * so that each only has to be run once. */ /* $FlowFixMe[incompatible-type] This discrepancy between PartialState (which the exported type claims to accept) and LessPartialState (the type actually accepted by the implementation, migrationsInner) is where we pretend that the storeKeys are all present. */ export const migrations: {| [string]: (PartialState) => PartialState |} = migrationsInner; ```
/content/code_sandbox/src/storage/migrations.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
4,997
```javascript // @flow strict-local import type { GlobalState } from '../../types'; import { historicalStoreKeys, migrations } from '../migrations'; import { storeKeys } from '../../boot/store'; import { createMigrationFunction } from '../../redux-persist-migrate'; import { ZulipVersion } from '../../utils/zulipVersion'; import * as eg from '../../__tests__/lib/exampleData'; describe('historicalStoreKeys', () => { test('equals current storeKeys', () => { // If this test starts failing, we'll want to clone historicalStoreKeys // into one with the old value and one with the new. See comment there. expect(historicalStoreKeys).toEqual(storeKeys); }); }); describe('migrations', () => { const migrate = createMigrationFunction(migrations, 'migrations'); // A plausible-ish state from before all surviving migrations. const base = { // Include something non-empty for each of the storeKeys. migrations: { version: 3 }, accounts: [{ email: 'me@example.com', apiKey: '1234', realm: 'path_to_url }], drafts: { '[]': 'draft text' }, // Real Outbox values have more properties, but fudge that. outbox: [{ isOutbox: true, isSent: false, type: 'private' }], // Settings from their reducer's initial value at this version. settings: { locale: 'en', theme: 'default', offlineNotification: true, onlineNotification: true, experimentalFeaturesEnabled: false, streamNotification: false, }, // Include something extraneous, too. foo: 1, }; // What `base` becomes after migrations up through 9. const base9 = { ...base, migrations: { version: 9 }, accounts: [{ ...base.accounts[0], ackedPushToken: null }], }; // What `base` becomes after migrations up through 15. const base15 = { ...base9, migrations: { version: 15 }, accounts: [ { ...base9.accounts[0], realm: new URL('path_to_url zulipFeatureLevel: null, zulipVersion: null, }, ], }; // What `base` becomes after migrations up through 37. const base37 = { migrations: { version: 37 }, accounts: [ { ...base15.accounts[0], lastDismissedServerPushSetupNotice: null, userId: null, }, ], drafts: {}, // cleared outbox: [], // cleared of lacking sender_id settings: { language: 'en', // renamed from locale theme: 'default', offlineNotification: true, onlineNotification: true, experimentalFeaturesEnabled: false, streamNotification: false, // added: browser: 'default', doNotMarkMessagesAsRead: false, }, }; // What `base` becomes after migrations up through 52. const base52 = { ...base37, migrations: { version: 52 }, settings: { language: 'en', theme: 'default', offlineNotification: true, onlineNotification: true, experimentalFeaturesEnabled: false, streamNotification: false, browser: 'default', // renamed/retyped from boolean doNotMarkMessagesAsRead markMessagesReadOnScroll: 'always', }, }; // What `base` becomes after migrations up through 62. const base62 = { ...base52, migrations: { version: 62 }, // $FlowIgnore[prop-missing] same type-lie as in the test, below at end accounts: base52.accounts.map(a => ({ ...a, silenceServerPushSetupWarnings: false, })), }; // What `base` becomes after migrations up through 66. const base66 = { ...base62, migrations: { version: 66 }, accounts: base62.accounts.map(a => ({ ...a, lastDismissedServerNotifsExpiringBanner: null })), }; // What `base` becomes after all migrations. const endBase = { ...base66, migrations: { version: 66 }, }; for (const [desc, before, after] of [ // Test the behavior with no migration state, which doesn't apply any // of the specific migrations. ['empty state -> just store version', {}, { migrations: endBase.migrations }], [ 'no migration state -> just store version, leave everything else', { nonsense: [1, 2, 3] }, { migrations: endBase.migrations, nonsense: [1, 2, 3] }, ], // Test the whole sequence all together. This covers many of the // individual migrations. (This might not be a good design if we were // going to be adding more migrations in this sequence; but pretty soon // we aren't.) ['whole sequence', base, endBase], // Test the latest use of `dropCache`. All the earlier uses are // redundant with this one, because none of the migration steps notice // whether any properties outside `storeKeys` are present or not. [ 'check dropCache at 65', // Just before the `dropCache`, plus a `cacheKeys` property, plus junk. { ...base62, migrations: { version: 64 }, mute: [], nonsense: [1, 2, 3] }, // Should wind up with the same result as without the extra properties. endBase, ], // // Now test individual migrations further, where needed. // Ignore `dropCache`, which we covered above. // 6 is redundant with 9 // 9 covered by whole [ 'check 10 with locale zh', // with locale id, 10 gets reverted by 26 { ...base9, settings: { ...base9.settings, locale: 'zh' } }, { ...endBase, settings: { ...endBase.settings, language: 'zh-Hans' } }, ], // 12 covered by whole [ 'check 13', { ...base9, migrations: { version: 12 }, accounts: [{ ...base9.accounts[0], zulipVersion: '1.2.3' }], }, { ...endBase, accounts: [{ ...endBase.accounts[0], zulipVersion: new ZulipVersion('1.2.3') }], }, ], // 14 covered by whole // 15 covered by whole // 21 covered by whole [ 'check 22', { ...base15, migrations: { version: 21 }, drafts: { 'pm:d:12:other@example.com': 'text', 'topic:s:general\x00stuff': 'other text' }, }, // This migration itself leaves the `topic:` draft in place. But it // gets dropped later by migration 38. { ...endBase, drafts: { 'pm:12': 'text' } }, // NB the original version of this migration was buggy; it would drop // the PM drafts entirely, so this test case would end up as: // { ...endBase, drafts: {} }, // WRONG // Should have written tests for it the first time. :-) ], [ 'check 26', { ...base15, settings: { ...base15.settings, locale: 'id-ID' } }, { ...endBase, settings: { ...endBase.settings, language: 'id' } }, ], [ 'check 27', { ...base15, accounts: [{ ...base15.accounts[0], email: '' }] }, { ...endBase, accounts: [] }, ], // 28 covered by whole [ 'check 29 with outbox-message that does have sender_id', { ...base15, outbox: [{ ...base15.outbox[0], sender_id: 345 }] }, { ...endBase, outbox: [{ ...base15.outbox[0], sender_id: 345 }] }, ], [ 'check 30', { ...base15, settings: { ...base15.settings, locale: 'pt_PT' } }, { ...endBase, settings: { ...endBase.settings, language: 'pt-PT' } }, ], // 31 covered by whole [ 'check 32', { ...base15, settings: { ...base15.settings, locale: 'zh-Hant' } }, { ...endBase, settings: { ...endBase.settings, language: 'zh-TW' } }, ], // 33 covered by whole [ 'check 35 with missing stream_id', { ...base15, outbox: [{ ...base15.outbox[0], type: 'stream', sender_id: 345 }] }, { ...endBase, outbox: [] }, ], [ 'check 35 with stream_id present', { ...base15, outbox: [{ ...base15.outbox[0], type: 'stream', sender_id: 345, stream_id: 17 }], }, { ...endBase, outbox: [{ ...base15.outbox[0], type: 'stream', sender_id: 345, stream_id: 17 }], }, ], // 36 covered by whole [ 'check 37 with setting already false', { ...base15, settings: { ...base15.settings, doNotMarkMessagesAsRead: false } }, { ...endBase, settings: { ...endBase.settings, markMessagesReadOnScroll: 'always' } }, ], [ 'check 37 with setting already true', { ...base15, settings: { ...base15.settings, doNotMarkMessagesAsRead: true } }, { ...endBase, settings: { ...endBase.settings, markMessagesReadOnScroll: 'never' } }, ], [ 'check 38', { ...base37, drafts: { 'topic:s:general\x00stuff': 'text', 'stream:s:general': 'more text', 'pm:12': 'pm text', }, }, { ...endBase, drafts: { 'pm:12': 'pm text' } }, ], [ 'check 39', { ...base37, migrations: { version: 38 }, drafts: { 'topic:d:8:general\x00stuff': 'text', 'stream:d:8:general': 'more text', 'pm:12': 'pm text', }, }, { ...endBase, drafts: { 'topic:8:stuff': 'text', 'stream:8': 'more text', 'pm:12': 'pm text' }, }, ], [ 'check 52 with old setting false', { ...base37, migrations: { version: 51 }, settings: { ...base37.settings, doNotMarkMessagesAsRead: false }, }, { ...endBase, settings: { ...endBase.settings, markMessagesReadOnScroll: 'always' } }, ], [ 'check 52 with old setting true', { ...base37, migrations: { version: 51 }, settings: { ...base37.settings, doNotMarkMessagesAsRead: true }, }, { ...endBase, settings: { ...endBase.settings, markMessagesReadOnScroll: 'never' } }, ], [ 'check 57 with an `undefined` in state.accounts', { ...base52, migrations: { version: 56 }, accounts: [...base37.accounts, undefined] }, { ...endBase, accounts: [...endBase.accounts] }, ], [ 'check 58 with a malformed Account in state.accounts', { ...base52, migrations: { version: 57 }, accounts: [ { userId: eg.selfUser.user_id, zulipFeatureLevel: eg.recentZulipFeatureLevel, zulipVersion: eg.recentZulipVersion, lastDismissedServerPushSetupNotice: null, }, ...base37.accounts, ], }, { ...endBase, accounts: [...endBase.accounts] }, ], // 61 covered by whole ]) { test(desc, async () => { // $FlowIgnore[incompatible-exact] // $FlowIgnore[incompatible-type] /* $FlowIgnore[prop-missing] this really is a lie -- and kind of central to migration */ const incomingState: $Rest<GlobalState, { ... }> = before; expect(migrate(incomingState)).toEqual(after); }); } }); ```
/content/code_sandbox/src/storage/__tests__/migrations-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
2,824
```javascript /* @flow strict-local */ import invariant from 'invariant'; import * as eg from '../../__tests__/lib/exampleData'; import { objectEntries } from '../../flowPonyfill'; import type { GlobalState } from '../../types'; import CompressedAsyncStorage from '../CompressedAsyncStorage'; import { stringify, parse } from '../replaceRevive'; const getRoundTrippedStateValue = async <K: $Keys<GlobalState>, V: $Values<GlobalState>>( key: K, value: V, ): Promise<V> => { // 1: Serialize a "live" object; e.g., a ZulipVersion instance. const stringifiedValue = stringify(value); // 2: Write to storage. Parts of this are mocked; so, stress-test // those mocks: // - Compression via TextCompressionModule on Android // - AsyncStorage: the library provides a mock implementation // that writes to a variable instead of to the disk await CompressedAsyncStorage.setItem(key, stringifiedValue); // 3: Read from storage. Parts of this are mocked; so, stress-test // those mocks: // - Decompression via TextCompressionModule on Android // - AsyncStorage: the library provides a mock implementation // that reads from a variable instead of from the disk const valueFromStorage = await CompressedAsyncStorage.getItem(key); invariant(valueFromStorage != null, 'valueFromStorage is not null/undefined'); // 4: "revive", e.g., a ZulipVersion instance. const parsedValueFromStorage = parse(valueFromStorage); // $FlowIgnore[incompatible-cast] return (parsedValueFromStorage: V); }; const getRoundTrippedState = async (globalState: GlobalState): Promise<GlobalState> => { const entries = await Promise.all( objectEntries(globalState).map( async <K: $Keys<GlobalState>, V: $Values<GlobalState>>([key: K, value: V]): Promise< [K, V], > => [ // $FlowIgnore[incompatible-cast] (key: K), // $FlowIgnore[incompatible-cast] (await getRoundTrippedStateValue(key, value): V), ], ), ); // $FlowIgnore[incompatible-indexer] return Object.fromEntries(entries); }; /** * Test several pieces of the Redux storage logic at once. * * We're counting on a lot of our Redux state to round-trip through * storage. Jest can't realistically test everything in this process * -- in particular, the storage itself, and any native code involved * -- but, in the places where it can't, at least it can stress-test * the mocks we've written and use elsewhere, to make sure they're * reasonably faithful. * * `eg.plusReduxState` represents standard example data, though not * the entire range of possible data; see its jsdoc. Still, we'll want * to know about any failures to round-trip that arise from changes to * that. */ test('`eg.plusReduxState` round-trips through storage', async () => { const stateBefore = eg.plusReduxState; // The `GlobalState` annotation seems to guide Flow to better error // messages; without it, Flow seems to get confused by the `await`. const stateAfter: GlobalState = await getRoundTrippedState(stateBefore); // `AvatarURL` instances are generally lazy with their `new URL` // computations; they have a stateful piece that might be a string // or a `URL` object. We could figure out how to teach Jest that // that difference doesn't matter, but for now, just normalize both // states by "waking up" their `AvatarURL`s. [stateBefore, stateAfter].forEach(s => { s.users.forEach(u => u.avatar_url.get(100)); s.realm.nonActiveUsers.forEach(u => u.avatar_url.get(100)); s.realm.crossRealmBots.forEach(u => u.avatar_url.get(100)); s.messages.forEach(m => m.avatar_url.get(100)); }); expect(stateAfter).toEqual(stateBefore); }); ```
/content/code_sandbox/src/storage/__tests__/storage-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
911
```javascript // @flow strict-local // $FlowFixMe[missing-export] -- present in test version of module import { deleteDatabase } from 'expo-sqlite'; import LegacyAsyncStorage from '@react-native-async-storage/async-storage'; import { AsyncStorage } from '../AsyncStorage'; import { SQLDatabase } from '../sqlite'; describe('AsyncStorage', () => { afterEach(async () => { await AsyncStorage.clear(); }); test('getItem / setItem', async () => { expect(await AsyncStorage.getItem('a')).toEqual(null); await AsyncStorage.setItem('a', '1'); expect(await AsyncStorage.getItem('a')).toEqual('1'); await AsyncStorage.setItem('a', '2'); expect(await AsyncStorage.getItem('a')).toEqual('2'); expect(await AsyncStorage.getItem('b')).toEqual(null); }); test('multiSet', async () => { await AsyncStorage.multiSet([ ['a', '1'], ['b', '2'], ]); expect(await AsyncStorage.getItem('a')).toEqual('1'); expect(await AsyncStorage.getItem('b')).toEqual('2'); }); test('removeItem', async () => { await AsyncStorage.setItem('a', '1'); expect(await AsyncStorage.getItem('a')).toEqual('1'); await AsyncStorage.removeItem('a'); expect(await AsyncStorage.getItem('a')).toEqual(null); await AsyncStorage.removeItem('a'); expect(await AsyncStorage.getItem('a')).toEqual(null); }); test('getAllKeys', async () => { await AsyncStorage.setItem('a', '1'); await AsyncStorage.setItem('b', '2'); expect(await AsyncStorage.getAllKeys()).toEqual(['a', 'b']); }); test('clear', async () => { await AsyncStorage.setItem('a', '1'); await AsyncStorage.setItem('b', '2'); expect(await AsyncStorage.getAllKeys()).toEqual(['a', 'b']); await AsyncStorage.clear(); expect(await AsyncStorage.getAllKeys()).toEqual([]); }); }); describe('AsyncStorage: migration from legacy AsyncStorage', () => { beforeAll(async () => { await AsyncStorage.devForgetState(); await deleteDatabase('zulip.db'); await LegacyAsyncStorage.clear(); }); afterEach(async () => { await AsyncStorage.devForgetState(); await deleteDatabase('zulip.db'); await LegacyAsyncStorage.clear(); }); test('with no legacy data', async () => { expect(await AsyncStorage.getAllKeys()).toEqual([]); }); test('with legacy data', async () => { LegacyAsyncStorage.setItem('a', '1'); LegacyAsyncStorage.setItem('b', '2'); expect(await AsyncStorage.getAllKeys()).toEqual(['a', 'b']); expect(await AsyncStorage.getItem('a')).toEqual('1'); expect(await AsyncStorage.getItem('b')).toEqual('2'); // Make some updates, then simulate the program exiting and restarting. await AsyncStorage.setItem('c', '3'); await AsyncStorage.removeItem('b'); await AsyncStorage.devForgetState(); // Expect to still get the updated state, not a newly-re-migrated state. expect(await AsyncStorage.getAllKeys()).toEqual(['a', 'c']); expect(await AsyncStorage.getItem('a')).toEqual('1'); expect(await AsyncStorage.getItem('c')).toEqual('3'); }); test('with legacy data and failed migration', async () => { LegacyAsyncStorage.setItem('a', '1'); LegacyAsyncStorage.setItem('b', '2'); expect(await AsyncStorage.getAllKeys()).toEqual(['a', 'b']); // Simulate the migration having not completed: // Pretend one of the keys didn't make it over await AsyncStorage.removeItem('b'); await AsyncStorage.devForgetState(); const db = new SQLDatabase('zulip.db'); await db.transaction(tx => { // and that the migration didn't record success. tx.executeSql('DELETE FROM migration'); }); // Expect to get the original legacy data, re-migrated. expect(await AsyncStorage.getAllKeys()).toEqual(['a', 'b']); expect(await AsyncStorage.getItem('a')).toEqual('1'); expect(await AsyncStorage.getItem('b')).toEqual('2'); }); }); ```
/content/code_sandbox/src/storage/__tests__/AsyncStorage-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
858
```javascript /* @flow strict-local */ import { Platform, NativeModules } from 'react-native'; import { AsyncStorage } from '../AsyncStorage'; import CompressedAsyncStorage from '../CompressedAsyncStorage'; import * as logging from '../../utils/logging'; import { randString } from '../../utils/misc'; test('smoke-test all methods, end to end', async () => { await CompressedAsyncStorage.clear(); expect(await CompressedAsyncStorage.getAllKeys()).toEqual([]); await CompressedAsyncStorage.setItem('a', JSON.stringify('aa')); await CompressedAsyncStorage.multiSet([ ['b', JSON.stringify('bb')], ['c', JSON.stringify('cc')], ]); expect([...(await CompressedAsyncStorage.getAllKeys())].sort()).toEqual(['a', 'b', 'c']); expect(await CompressedAsyncStorage.getItem('a')).toEqual(JSON.stringify('aa')); expect(await CompressedAsyncStorage.getItem('b')).toEqual(JSON.stringify('bb')); expect(await CompressedAsyncStorage.getItem('d')).toEqual(null); await CompressedAsyncStorage.removeItem('b'); expect([...(await CompressedAsyncStorage.getAllKeys())].sort()).toEqual(['a', 'c']); expect(await CompressedAsyncStorage.getItem('b')).toEqual(null); await CompressedAsyncStorage.clear(); expect(await CompressedAsyncStorage.getAllKeys()).toEqual([]); }); describe('setItem', () => { const key = 'foo!'; const value = '123!'; // For checking that AsyncStorage.setItem is called in ways we expect. const asyncStorageSetItemSpy = jest.spyOn(AsyncStorage, 'setItem'); beforeEach(() => asyncStorageSetItemSpy.mockClear()); const run = async () => CompressedAsyncStorage.setItem(key, value); describe('success', () => { test('resolves correctly', async () => { await expect(run()).resolves.toBe(undefined); }); test('AsyncStorage.setItem called correctly', async () => { await run(); expect(asyncStorageSetItemSpy).toHaveBeenCalledTimes(1); expect(asyncStorageSetItemSpy).toHaveBeenCalledWith( key, Platform.OS === 'ios' ? value : await NativeModules.TextCompressionModule.compress(value), ); }); }); describe('failure', () => { // Mock `.setItem` to simulate failure, and reset when we're done. /* $FlowFixMe[method-unbinding] - If things were to actually go wrong, it'd probably make those tests not work at all, so we'd know; see path_to_url#narrow/stream/243-mobile-team/topic/Flow.20158.20errors/near/1375705 */ const savedMethod = AsyncStorage.setItem; beforeEach(() => { // $FlowFixMe[cannot-write] Make Flow understand about mocking. AsyncStorage.setItem = jest.fn(async (k: string, v: string): Promise<null> => { throw new Error(); }); }); afterAll(() => { // $FlowFixMe[cannot-write] Make Flow understand about mocking. AsyncStorage.setItem = savedMethod; }); test('rejects correctly', async () => { await expect(run()).rejects.toThrow(Error); }); }); }); describe('multiSet', () => { const keyValuePairs = [ ['foo', JSON.stringify('bar')], ['food', JSON.stringify('bard')], ]; // For checking that AsyncStorage.multiSet is called in ways we expect. const asyncStorageMultiSetSpy = jest.spyOn(AsyncStorage, 'multiSet'); beforeEach(() => asyncStorageMultiSetSpy.mockClear()); const run = async () => CompressedAsyncStorage.multiSet(keyValuePairs); describe('success', () => { test('resolves correctly', async () => { await run(); expect(asyncStorageMultiSetSpy).toHaveBeenCalledTimes(1); expect(asyncStorageMultiSetSpy).toHaveBeenCalledWith( Platform.OS === 'ios' ? keyValuePairs : await Promise.all( keyValuePairs.map(async ([key, value]) => [ key, await NativeModules.TextCompressionModule.compress(value), ]), ), ); }); }); describe('failure', () => { // Mock `.multiSet` to simulate failure, and reset when we're done. /* $FlowFixMe[method-unbinding] - If things were to actually go wrong, it'd probably make those tests not work at all, so we'd know; see path_to_url#narrow/stream/243-mobile-team/topic/Flow.20158.20errors/near/1375705 */ const savedMethod = AsyncStorage.multiSet; beforeEach(() => { // $FlowFixMe[cannot-write] Make Flow understand about mocking. AsyncStorage.multiSet = jest.fn(async (p: string[][]): Promise<null> => { throw new Error(); }); }); afterAll(() => { // $FlowFixMe[cannot-write] Make Flow understand about mocking. AsyncStorage.multiSet = savedMethod; }); test('rejects correctly', async () => { await expect(run()).rejects.toThrow(Error); }); }); }); describe('getItem', () => { const key = 'foo!'; const value = '123!'; // For checking that AsyncStorage.getItem is called in ways we expect. const asyncStorageGetItemSpy = jest.spyOn(AsyncStorage, 'getItem'); beforeEach(() => asyncStorageGetItemSpy.mockClear()); beforeAll(async () => { // Store something in `AsyncStorage` for our // `CompressedAsyncStorage.getItem` to retrieve. await AsyncStorage.setItem( key, Platform.OS === 'ios' ? value : await NativeModules.TextCompressionModule.compress(value), ); // suppress `logging.error` output // $FlowFixMe[prop-missing] - teach Flow about mocks logging.error.mockReturnValue(); }); const run = async () => CompressedAsyncStorage.getItem(key); describe('success', () => { test('calls AsyncStorage.getItem as we expect it to', async () => { await run(); expect(asyncStorageGetItemSpy).toHaveBeenCalledTimes(1); expect(asyncStorageGetItemSpy).toHaveBeenCalledWith(key); }); test('resolves correctly', async () => { await expect(run()).resolves.toBe(value); }); }); describe('failure', () => { // Mock `.getItem` to simulate failure, and reset when we're done. /* $FlowFixMe[method-unbinding] - If things were to actually go wrong, it'd probably make those tests not work at all, so we'd know; see path_to_url#narrow/stream/243-mobile-team/topic/Flow.20158.20errors/near/1375705 */ const savedMethod = AsyncStorage.getItem; beforeEach(() => { // $FlowFixMe[cannot-write] Make Flow understand about mocking. AsyncStorage.getItem = jest.fn(async (k: string): Promise<string | null> => { throw new Error(); }); }); afterAll(() => { // $FlowFixMe[cannot-write] Make Flow understand about mocking. AsyncStorage.getItem = savedMethod; }); test('rejects correctly', async () => { await expect(run()).rejects.toThrow(Error); }); }); if (Platform.OS === 'android') { describe('android', () => { test('panics when value is in unknown compression format', async () => { const unknownHeader = 'z|mock-unknown-format|'; await AsyncStorage.setItem( `${key}-unknown`, `${unknownHeader}${Buffer.from('123!').toString('hex')}`, ); await expect(CompressedAsyncStorage.getItem(`${key}-unknown`)).rejects.toThrow( `No decompression module found for format ${unknownHeader}`, ); }); }); } }); describe('set/get together', () => { test('round-tripping of single key-value pair works', async () => { const key = randString(); const value = JSON.stringify(randString()); await CompressedAsyncStorage.setItem(key, value); expect(await CompressedAsyncStorage.getItem(key)).toEqual(value); }); test('round-tripping of multiple key-value pairs works', async () => { const keyValuePairs = [ [randString(), JSON.stringify(randString())], [randString(), JSON.stringify(randString())], ]; await CompressedAsyncStorage.multiSet(keyValuePairs); expect( await Promise.all( keyValuePairs.map(async ([key, _]) => [key, await CompressedAsyncStorage.getItem(key)]), ), ).toEqual(keyValuePairs); }); }); ```
/content/code_sandbox/src/storage/__tests__/CompressedAsyncStorage-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,825
```javascript // @flow strict-local import sqlite3 from 'sqlite3'; // $FlowFixMe[missing-export] -- present in test version of module import { openDatabase, deleteDatabase, type SQLResultSet } from 'expo-sqlite'; /* eslint-disable import/no-extraneous-dependencies */ // $FlowFixMe[untyped-import]: actually comes from our mock-immediate.js import * as immediate from 'immediate'; import invariant from 'invariant'; import { objectFromEntries } from '../../jsBackport'; import { SQLDatabase } from '../sqlite'; /* eslint-disable no-underscore-dangle */ /* eslint-disable no-return-assign */ describe('sqlite3', () => { test('smoke', async () => { const db = new sqlite3.Database(':memory:'); const result = await new Promise((resolve, reject) => { db.get('SELECT 42 as n', (err, row) => (err ? reject(err) : resolve(row))); }); expect(result).toEqual({ n: 42 }); }); }); describe('expo-sqlite', () => { const dbName = 'test.db'; beforeAll(async () => { await deleteDatabase(dbName); }); afterEach(async () => { await deleteDatabase(dbName); }); // These helpers `promiseTxn`, `promiseRead`, and `select` are convenient // for stitching the database control flow into the control flow of a // test. They're similar to parts of our promisified wrapper... // namely the outermost, simplest parts. const promiseTxn = (db, cb) => new Promise((resolve, reject) => db.transaction(cb, reject, resolve)); const promiseRead = (db, cb) => new Promise((resolve, reject) => db.readTransaction(cb(resolve), reject, resolve)); const select = (db, sql, args = []) => promiseRead(db, resolve => tx => tx.executeSql(sql, args, (t, r) => resolve(r))).then( r => r.rows._array, ); test('smoke', async () => { const db = openDatabase(dbName); const rows = await select(db, 'SELECT 42 AS n'); expect(rows).toEqual([{ n: 42 }]); }); test('transaction with no internal await', async () => { const db = openDatabase(dbName); await promiseTxn(db, tx => { tx.executeSql('CREATE TABLE foo (x INT)'); tx.executeSql('INSERT INTO foo (x) VALUES (?)', [1]); tx.executeSql('INSERT INTO foo (x) VALUES (?)', [2]); }); const rows = await select(db, 'SELECT x FROM foo'); expect(rows).toEqual([{ x: 1 }, { x: 2 }]); }); test('transaction with internal await^W callback ', async () => { const db = openDatabase(dbName); await promiseTxn(db, tx => { tx.executeSql('CREATE TABLE foo (x INT)'); tx.executeSql('INSERT INTO foo (x) VALUES (?)', [1], () => tx.executeSql('INSERT INTO foo (x) VALUES (?)', [2]), ); }); const rows = await select(db, 'SELECT x FROM foo'); expect(rows).toEqual([{ x: 1 }, { x: 2 }]); }); test('BROKEN: transaction with internal asynchrony other than executeSql', async () => { // This test shows that if using expo-sqlite you try to make a // transaction that involves some asynchronous work between SQL queries, // the transaction gets committed in a half-done state. Moreover // the subsequent statements get silently ignored, with no error. // // This failure mode gets triggered very easily if you try to use // Promises. But if you actually have some asynchronous work to do, // then this hits even if you express the flow in pure callback terms. // So we'll demonstrate it that way here. // // (In our promisifying wrapper, we work around this issue; see // `keepQueueLiveWhile` in our sqlite.js, and the "with internal await" // tests below.) const db = openDatabase(dbName); let txEnded = false; await promiseTxn(db, tx => { tx.executeSql('CREATE TABLE foo (name TEXT, value INT)'); // Get some data from SQL. tx.executeSql('SELECT 2 + 2 AS total', [], (t, result) => { const { total } = result.rows._array[0]; // Use that data to compute something synchronously, and store it. const double = 2 * total; tx.executeSql('INSERT INTO foo (name, value) VALUES (?, ?)', ['double', double]); // So far, all's well. // Now do some *asynchronous* computation, using the data we // read earlier in the transaction. const asyncSquare = (x, cb) => setTimeout(() => cb(x * x), 0); asyncSquare(total, square => { // By the time we get here, the transaction will have found its // queue empty and decided it's complete. // So when we try to write this result, nothing will happen. tx.executeSql('INSERT INTO foo (name, value) VALUES (?, ?)', ['square', square]); // The new statement goes into a queue which will never again // get read. We don't even get an exception -- the next line // runs fine (as we confirm below): txEnded = true; }); }); }); // Let that asynchronous computation complete, and confirm the callback // completes without an exception. jest.runAllTimers(); while (!txEnded) { await null; } // Now read what data got written. const rows = await select(db, 'SELECT name, value FROM foo'); const data = objectFromEntries(rows.map(({ name, value }) => [name, value])); // This would be a good answer: // expect(data).toEqual({ double: 8, square: 16 }); // FAILS // Instead, we get: expect(data).toEqual({ double: 8 }); // bad: missing the second INSERT }); describe('transactions failing in app code', () => { beforeAll(() => immediate.allowUnhandled()); afterAll(() => immediate.disallowUnhandled()); afterEach(() => expect(immediate.takeUnhandled()).toEqual([])); // TODO Here's a Jest gotcha. Try to report it? // Say you have `foo: () => Promise<{ foo: number }[]>`. // You write `expect(foo()).toEqual([{ foo: 3 }])`. // // This is buggy -- should say `await foo()`, or `.resolves.toEqual()`. // But you don't notice that; maybe you've forgotten `foo` returns a Promise. // // Jest reports an error. But the gotcha is: it just says // Expected: [{"foo": 3}] // Received: {} // That is, the thing received is represented as `{}`. It looks like // a plain object. There's no hint that it's actually a Promise. // That's pretty misleading for debugging. test('BROKEN: throws early', async () => { // Do a bit of boring setup. const db = openDatabase(dbName); await promiseTxn(db, tx => { tx.executeSql('CREATE TABLE foo (x INT)'); tx.executeSql('INSERT INTO foo (x) VALUES (?)', [1]); }); expect(await select(db, 'SELECT x FROM foo')).toEqual([{ x: 1 }]); expect(immediate.takeUnhandled()).toEqual([]); // Now attempt a transaction, and hit an exception in the transaction // callback. await promiseTxn(db, tx => { tx.executeSql('INSERT INTO foo (x) VALUES (?)', [2]); throw new Error('Fiddlesticks!'); }); // This goes unnoticed by the expo-sqlite implementation, propagating // unhandled up to an `immediate` callback. (So e.g. with a // Promise-based `immediate` implementation, it'd be an unhandled // Promise rejection.) expect(immediate.takeUnhandled()).toMatchObject([new Error('Fiddlesticks!')]); // In itself, that's only a code smell, not a live bug. But, as usual // for unhandled Promise rejections, it does result in a live bug -- // or in any case in user-visible effects that don't seem desirable. // A good behavior for that failed transaction to have would be: // expect(await select(db, 'SELECT x FROM foo')).toEqual([{ x: 1 }]); // FAILS // i.e.: the transaction got rolled back, and we move on. // The actual behavior is: expect(await select(db, 'SELECT x FROM foo')).toEqual([{ x: 1 }, { x: 2 }]); // BAD // The transaction committed! // And indeed, we can carry on with more transactions as if all's well. await promiseTxn(db, tx => { tx.executeSql('INSERT INTO foo (x) VALUES (?)', [3]); }); expect(await select(db, 'SELECT x FROM foo')).toEqual([{ x: 1 }, { x: 2 }, { x: 3 }]); // BAD }); // This describes desired behavior that's currently broken. test.skip('BROKEN: throws later -> cleanly rolls back and errors', async () => { const db = openDatabase(dbName); await promiseTxn(db, tx => { tx.executeSql('CREATE TABLE foo (x INT)'); tx.executeSql('INSERT INTO foo (x) VALUES (?)', [1]); }); expect(await select(db, 'SELECT x FROM foo')).toEqual([{ x: 1 }]); // This time, throw in a query callback. // The transaction's error callback gets called (so promiseTxn rejects) await expect( promiseTxn(db, tx => { tx.executeSql('INSERT INTO foo (x) VALUES (?)', [2], (err, r) => { tx.executeSql('INSERT INTO foo (x) VALUES (?)', [3]); throw new Error('Fiddlesticks!'); }); }), ).rejects.toThrowError('Fiddlesticks!'); // and the whole transaction gets rolled back. expect(await select(db, 'SELECT x FROM foo')).toEqual([{ x: 1 }]); // Subsequent queries work fine. await promiseTxn(db, tx => { tx.executeSql('INSERT INTO foo (x) VALUES (?)', [4]); }); expect(await select(db, 'SELECT x FROM foo')).toEqual([{ x: 1 }, { x: 4 }]); }); test('BROKEN: throws later -> actual, broken behavior', async () => { const db = openDatabase(dbName); await promiseTxn(db, tx => { tx.executeSql('CREATE TABLE foo (x INT)'); tx.executeSql('INSERT INTO foo (x) VALUES (?)', [1]); }); expect(await select(db, 'SELECT x FROM foo')).toEqual([{ x: 1 }]); // $FlowFixMe[prop-missing] // $FlowFixMe[incompatible-use] db._db.allowUnhandled(); let _ops = undefined; const p1 = new Promise((resolve, reject) => (_ops = { resolve, reject })); invariant(_ops, 'ops should be initialized'); const ops = _ops; // The overall transaction reports no error; neither its success nor // failure callback ever gets called. // eslint-disable-next-line no-unused-vars const p = promiseTxn(db, tx => { tx.executeSql('INSERT INTO foo (x) VALUES (?)', [2], (err, r) => { tx.executeSql('INSERT INTO foo (x) VALUES (?)', [3]); ops.resolve(); throw new Error('Fiddlesticks!'); }); }); // Instead... well, in the actual expo-sqlite implementation, there's // an unhandled Promise rejection, as the `then` callback in the // definition of `exec` in `SQLite.ts` throws. In our mock // implementation, we selectively let that slide with `allowUnhandled`. // Because expo-sqlite never calls the transaction callbacks, we need // our own mechanism to await everything being settled. await p1; // This would just hang: // await p; // Then: the `db` object gets left in a stuck state. (Internally, // `this._running` on the `WebSQLDatabase` is stuck as true.) So if // we try any query, even something read-only: // expect(await select(db, 'SELECT x FROM foo')).toEqual([{ x: 1 }]); // it just never completes. // (There isn't an obvious good way to write a test *of* that // particular broken behavior, though.) }); }); }); describe('our promisified sqlite', () => { const dbName = 'test.db'; beforeAll(async () => { await deleteDatabase(dbName); }); afterEach(async () => { await deleteDatabase(dbName); }); test('smoke', async () => { const db = new SQLDatabase(dbName); const rows = await db.query<{ n: number }>('SELECT 42 AS n', []); expect(rows).toEqual([{ n: 42 }]); }); test('transaction with no internal await', async () => { const db = new SQLDatabase(dbName); await db.transaction(tx => { tx.executeSql('CREATE TABLE foo (x INT)'); tx.executeSql('INSERT INTO foo (x) VALUES (?)', [1]); tx.executeSql('INSERT INTO foo (x) VALUES (?)', [2]); }); const rows = await db.query<{ x: number }>('SELECT x FROM foo', []); expect(rows).toEqual([{ x: 1 }, { x: 2 }]); }); test('transaction with internal await', async () => { const db = new SQLDatabase(dbName); await db.transaction(async tx => { tx.executeSql('CREATE TABLE foo (x INT)'); await tx.executeSql('INSERT INTO foo (x) VALUES (?)', [1]); tx.executeSql('INSERT INTO foo (x) VALUES (?)', [2]); }); const rows = await db.query<{ x: number }>('SELECT x FROM foo', []); expect(rows).toEqual([{ x: 1 }, { x: 2 }]); }); test('read-transaction with no internal await', async () => { const db = new SQLDatabase(dbName); let a: SQLResultSet | void = undefined; let b: SQLResultSet | void = undefined; await db.readTransaction(async tx => { tx.executeSql('SELECT 1 AS n').then(r => (a = r)); tx.executeSql('SELECT 2 AS n').then(r => (b = r)); }); expect(a?.rows._array).toEqual([{ n: 1 }]); expect(b?.rows._array).toEqual([{ n: 2 }]); }); test('read-transaction with internal await', async () => { const db = new SQLDatabase(dbName); let a: SQLResultSet | void = undefined; let b: SQLResultSet | void = undefined; await db.readTransaction(async tx => { a = await tx.executeSql('SELECT 1 AS n'); b = await tx.executeSql('SELECT 2 AS n'); }); expect(a?.rows._array).toEqual([{ n: 1 }]); expect(b?.rows._array).toEqual([{ n: 2 }]); }); test('transaction with internal asynchrony other than executeSql', async () => { // This corresponds to the similar test for expo-sqlite above, and // shows that we've successfully worked around that issue. let p1 = undefined; let p2 = undefined; const db = new SQLDatabase(dbName); const txPromise = db.transaction(async tx => { tx.executeSql('CREATE TABLE foo (name TEXT, value INT)'); p1 = tx.executeSql('SELECT 2 + 2 AS total'); const result = await p1; const { total } = result.rows._array[0]; // Use that data to compute something synchronously, and store it. const double = 2 * total; tx.executeSql('INSERT INTO foo (name, value) VALUES (?, ?)', ['double', double]); // Now do some *asynchronous* computation, using the data we // read earlier in the transaction. We'll use the exact same function as above: const asyncSquare = (x, cb) => setTimeout(() => cb(x * x), 0); p2 = new Promise(resolve => asyncSquare(total, resolve)); const square = await p2; tx.executeSql('INSERT INTO foo (name, value) VALUES (?, ?)', ['square', square]); }); // Let that asynchronous computation complete. This gets a bit ugly: we // need to tell Jest to run the timer embedded inside that async // computation, and that does no good until the timer has been created, // so we end up having to walk through the async flow step by step. // prettier-ignore while (!p1) { await null; } await p1; // prettier-ignore while (!p2) { await null; } jest.runAllTimers(); await txPromise; const rows = await db.query<{ name: string, value: number }>('SELECT name, value FROM foo', []); const data = objectFromEntries(rows.map(({ name, value }) => [name, value])); expect(data).toEqual({ double: 8, square: 16 }); }); describe('transactions failing in app code', () => { // These tests correspond to "BROKEN" tests above for expo-sqlite // itself, and check that we've successfully worked around those issues. test('throws early', async () => { // Do a bit of boring setup. const db = new SQLDatabase(dbName); await db.transaction(async tx => { tx.executeSql('CREATE TABLE foo (x INT)'); tx.executeSql('INSERT INTO foo (x) VALUES (?)', [1]); }); // Now attempt a transaction, and hit an exception in the transaction // callback. await expect( db.transaction(async tx => { tx.executeSql('INSERT INTO foo (x) VALUES (?)', [2]); throw new Error('Fiddlesticks!'); }), ).rejects.toThrowError(); // The transaction gets rolled back. Its data wasn't committed: const rows = await db.query<{ x: number }>('SELECT x FROM foo', []); expect(rows).toEqual([{ x: 1 }]); // and we can move on to other transactions, and those go just fine: await db.transaction(async tx => { tx.executeSql('INSERT INTO foo (x) VALUES (?)', [3]); }); const rows2 = await db.query<{ x: number }>('SELECT x FROM foo', []); expect(rows2).toEqual([{ x: 1 }, { x: 3 }]); }); test('throws later', async () => { // Do a bit of boring setup. const db = new SQLDatabase(dbName); await db.transaction(async tx => { tx.executeSql('CREATE TABLE foo (x INT)'); tx.executeSql('INSERT INTO foo (x) VALUES (?)', [1]); }); // Now attempt a transaction, and hit an exception after awaiting some // previous result. await expect( db.transaction(async tx => { await tx.executeSql('INSERT INTO foo (x) VALUES (?)', [2]); tx.executeSql('INSERT INTO foo (x) VALUES (?)', [3]); throw new Error('Fiddlesticks!'); }), ).rejects.toThrowError(); // The transaction gets rolled back. Its data wasn't committed: const rows = await db.query<{ x: number }>('SELECT x FROM foo', []); expect(rows).toEqual([{ x: 1 }]); // and we can move on to other transactions, and those go just fine: await db.transaction(async tx => { tx.executeSql('INSERT INTO foo (x) VALUES (?)', [4]); }); const rows2 = await db.query<{ x: number }>('SELECT x FROM foo', []); expect(rows2).toEqual([{ x: 1 }, { x: 4 }]); }); }); }); ```
/content/code_sandbox/src/storage/__tests__/sqlite-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
4,502
```javascript /* @flow strict-local */ import Immutable from 'immutable'; import { FallbackAvatarURL, GravatarURL, UploadedAvatarURL } from '../../utils/avatar'; import { ZulipVersion } from '../../utils/zulipVersion'; import { stringify, parse, SERIALIZED_TYPE_FIELD_NAME } from '../replaceRevive'; import * as eg from '../../__tests__/lib/exampleData'; import { makeUserId } from '../../api/idTypes'; const data = { // prettier-ignore jsMap: new Map([['a', 1], ['b', 2], ['c', 3]]), // prettier-ignore jsMapWithTypeKey: new Map([['a', 1], [SERIALIZED_TYPE_FIELD_NAME, { b: [2] }]]), // prettier-ignore jsMapNumKeys: new Map([[1, 2], [3, 4]]), jsSet: new Set([1, 2, 'a', null, { b: [3] }]), list: Immutable.List([1, 2, 'a', null]), map: Immutable.Map([ ['a', 1], ['b', 2], ['c', 3], ['d', 4], ]), mapWithTypeKey: Immutable.Map([ ['a', 1], [SERIALIZED_TYPE_FIELD_NAME, { b: [2], [SERIALIZED_TYPE_FIELD_NAME]: { c: [3] } }], ]), // prettier-ignore mapNumKeys: Immutable.Map([[1, 1], [2, 2], [3, 3], [4, 4]]), emptyMap: Immutable.Map([]), date: new Date('2021-11-11T00:00:00.000Z'), zulipVersion: new ZulipVersion('3.0.0'), url: new URL('path_to_url gravatarURL: GravatarURL.validateAndConstructInstance({ email: eg.selfUser.email }), uploadedAvatarURL: UploadedAvatarURL.validateAndConstructInstance({ realm: eg.realm, absoluteOrRelativeUrl: '/user_avatars/2/e35cdbc4771c5e4b94e705bf6ff7cca7fa1efcae.png?x=x&version=2', }), fallbackAvatarURL: FallbackAvatarURL.validateAndConstructInstance({ realm: eg.realm, userId: makeUserId(1), }), plainObjectWithTypeKey: { a: 1, [SERIALIZED_TYPE_FIELD_NAME]: { b: [2], [SERIALIZED_TYPE_FIELD_NAME]: { c: [3] }, }, }, }; const stringified = { jsMap: '{"data":[["a",1],["b",2],["c",3]],"__serializedType__":"Map"}', jsMapWithTypeKey: '{"data":[["a",1],["__serializedType__",{"b":[2]}]],"__serializedType__":"Map"}', jsMapNumKeys: '{"data":[[1,2],[3,4]],"__serializedType__":"Map"}', jsSet: '{"data":[1,2,"a",null,{"b":[3]}],"__serializedType__":"Set"}', list: '{"data":[1,2,"a",null],"__serializedType__":"ImmutableList"}', map: '{"data":{"a":1,"b":2,"c":3,"d":4},"__serializedType__":"ImmutableMap"}', mapWithTypeKey: '{"data":{"__serializedType__":"Object","data":{"a":1},"__serializedType__value":{"__serializedType__":"Object","data":{"b":[2]},"__serializedType__value":{"c":[3]}}},"__serializedType__":"ImmutableMap"}', mapNumKeys: '{"data":{"1":1,"2":2,"3":3,"4":4},"__serializedType__":"ImmutableMapNumKeys"}', emptyMap: '{"data":{},"__serializedType__":"ImmutableMap"}', date: '{"data":"2021-11-11T00:00:00.000Z","__serializedType__":"Date"}', zulipVersion: '{"data":"3.0.0","__serializedType__":"ZulipVersion"}', url: '{"data":"path_to_url","__serializedType__":"URL"}', gravatarURL: '{"data":"path_to_url","__serializedType__":"GravatarURL"}', uploadedAvatarURL: '{"data":"path_to_url","__serializedType__":"UploadedAvatarURL"}', fallbackAvatarURL: '{"data":"path_to_url","__serializedType__":"FallbackAvatarURL"}', plainObjectWithTypeKey: '{"__serializedType__":"Object","data":{"a":1},"__serializedType__value":{"__serializedType__":"Object","data":{"b":[2]},"__serializedType__value":{"c":[3]}}}', }; describe('Stringify', () => { Object.keys(data).forEach(key => { it(key, () => { expect(stringify(data[key])).toEqual(stringified[key]); }); }); test('catches an unexpectedly unhandled value with a `toJSON` method', () => { expect(() => stringify(new Performance())).toThrow(); }); test("catches a value that's definitely not serializable as-is", () => { expect(() => stringify(() => 'foo')).toThrow(); }); test('catches an unexpectedly unhandled value of an interesting type', () => { class Dog { noise = 'woof'; makeNoise() { console.log(this.noise); // eslint-disable-line no-console } } expect(() => stringify(new Dog())).toThrow(); }); }); describe('Parse', () => { Object.keys(data).forEach(key => { it(key, () => { expect(parse(stringified[key])).toEqual(data[key]); }); }); }); ```
/content/code_sandbox/src/storage/__tests__/replaceRevive-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,278
```javascript /* @flow strict-local */ import React, { useEffect } from 'react'; import type { Node } from 'react'; import { createMaterialTopTabNavigator, type MaterialTopTabNavigationProp, } from '@react-navigation/material-top-tabs'; import type { RouteParamsOf, RouteProp } from '../react-navigation'; import type { AppNavigationMethods, AppNavigationProp } from '../nav/AppNavigator'; import type { SharedData } from './types'; import { createStyleSheet } from '../styles'; import { materialTopTabNavigatorConfig } from '../styles/tabs'; import { useGlobalSelector } from '../react-redux'; import ZulipTextIntl from '../common/ZulipTextIntl'; import Screen from '../common/Screen'; import { getHasAuth } from '../selectors'; import { resetToAccountPicker } from '../nav/navActions'; import ShareToStream from './ShareToStream'; import ShareToPm from './ShareToPm'; import { useHaveServerDataGate } from '../withHaveServerDataGate'; export type SharingNavigatorParamList = {| +'share-to-stream': RouteParamsOf<typeof ShareToStream>, +'share-to-pm': RouteParamsOf<typeof ShareToPm>, |}; export type SharingNavigationProp< +RouteName: $Keys<SharingNavigatorParamList> = $Keys<SharingNavigatorParamList>, > = // Screens on this navigator will get a `navigation` prop that reflects // this navigator itself MaterialTopTabNavigationProp<SharingNavigatorParamList, RouteName> & // plus the methods it gets from its parent navigator. AppNavigationMethods; const Tab = createMaterialTopTabNavigator<SharingNavigatorParamList>(); type Props = $ReadOnly<{| navigation: AppNavigationProp<'sharing'>, route: RouteProp<'sharing', {| sharedData: SharedData |}>, |}>; const styles = createStyleSheet({ tab: { padding: 8, fontSize: 16, }, }); export default function SharingScreen(props: Props): Node { const { params } = props.route; const { navigation } = props; const hasAuth = useGlobalSelector(getHasAuth); useEffect(() => { if (!hasAuth) { // If there is no active logged-in account, abandon the sharing attempt, // and present the account picker screen to the user. // TODO(?): Offer to come back and finish the share after auth navigation.dispatch(resetToAccountPicker()); } }, [hasAuth, navigation]); return ( <Screen canGoBack={false} title="Share on Zulip" shouldShowLoadingBanner={false}> <Tab.Navigator {...materialTopTabNavigatorConfig()} swipeEnabled> <Tab.Screen name="share-to-stream" component={useHaveServerDataGate(ShareToStream)} initialParams={params} options={{ tabBarLabel: ({ color }) => ( <ZulipTextIntl style={[styles.tab, { color }]} text="Stream" /> ), }} /> <Tab.Screen name="share-to-pm" component={useHaveServerDataGate(ShareToPm)} initialParams={params} options={{ tabBarLabel: ({ color }) => ( <ZulipTextIntl style={[styles.tab, { color }]} text="Direct message" /> ), }} /> </Tab.Navigator> </Screen> ); } ```
/content/code_sandbox/src/sharing/SharingScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
726
```javascript /* @flow strict-local */ import React, { useState, useCallback } from 'react'; import type { Node } from 'react'; import type { UserId, UserOrBot } from '../types'; import Screen from '../common/Screen'; import UserPickerCard from '../user-picker/UserPickerCard'; type Props = $ReadOnly<{| onComplete: ($ReadOnlyArray<UserId>) => void, |}>; export default function ChooseRecipientsScreen(props: Props): Node { const { onComplete } = props; const [filter, setFilter] = useState<string>(''); const handleComplete = useCallback( (selected: $ReadOnlyArray<UserOrBot>) => { onComplete(selected.map(u => u.user_id)); }, [onComplete], ); return ( <Screen search scrollEnabled={false} searchBarOnChange={setFilter} canGoBack={false}> <UserPickerCard filter={filter} onComplete={handleComplete} showOwnUser /> </Screen> ); } ```
/content/code_sandbox/src/sharing/ChooseRecipientsScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
205
```javascript /* @flow strict-local */ import { NativeModules, DeviceEventEmitter, Platform } from 'react-native'; import * as NavigationService from '../nav/NavigationService'; import type { SharedData } from './types'; import { navigateToSharing } from '../actions'; const Sharing = NativeModules.Sharing ?? { readInitialSharedContent: () => // TODO: Implement on iOS. null, }; const goToSharing = (data: SharedData) => { NavigationService.dispatch(navigateToSharing(data)); }; export const handleInitialShare = async () => { const initialSharedData: SharedData | null = await Sharing.readInitialSharedContent(); if (initialSharedData !== null) { goToSharing(initialSharedData); } }; export class ShareReceivedListener { unsubs: Array<() => void> = []; /** Private. */ listen(name: string, handler: (...empty) => void | Promise<void>) { if (Platform.OS === 'android') { const subscription = DeviceEventEmitter.addListener(name, handler); this.unsubs.push(() => subscription.remove()); } } /** Private. */ unlistenAll() { while (this.unsubs.length > 0) { this.unsubs.pop()(); } } handleShareReceived: SharedData => void = data => { goToSharing(data); }; /** Start listening. Don't call twice without intervening `stop`. */ start() { if (Platform.OS === 'android') { this.listen('shareReceived', this.handleShareReceived); } } /** Stop listening. */ stop() { this.unlistenAll(); } } ```
/content/code_sandbox/src/sharing/index.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
351
```javascript /* @flow strict-local */ export type SharedFile = {| name: string, mimeType: string, url: string, |}; /** * The data we get when the user "shares" to Zulip from another app. * * On Android, these objects are sent to JS from our platform-native code, * constructed there by `getParamsFromIntent` in `SharingHelper.kt`. * The correspondence of that code with this type isn't type-checked. * * (On iOS, we don't currently support this feature in the first place.) */ // prettier-ignore export type SharedData = // Note: Keep these in sync with platform-native code. | {| type: 'text', sharedText: string |} | {| type: 'file', files: $ReadOnlyArray<SharedFile> |}; ```
/content/code_sandbox/src/sharing/types.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
174
```javascript /* @flow strict-local */ import React from 'react'; import type { ComponentType } from 'react'; import type { ValidationError } from './ShareWrapper'; import type { SharingNavigationProp } from './SharingScreen'; import type { RouteProp } from '../react-navigation'; import type { Dispatch, Auth, Stream } from '../types'; import type { SharedData } from './types'; import { connect } from '../react-redux'; import Input from '../common/Input'; import StreamAutocomplete from '../autocomplete/StreamAutocomplete'; import TopicAutocomplete from '../autocomplete/TopicAutocomplete'; import AnimatedScaleComponent from '../animation/AnimatedScaleComponent'; import { streamNarrow } from '../utils/narrow'; import { getAuth, getRealm, getStreamsByName } from '../selectors'; import { fetchTopicsForStream } from '../topics/topicActions'; import ShareWrapper from './ShareWrapper'; type OuterProps = $ReadOnly<{| navigation: SharingNavigationProp<'share-to-stream'>, route: RouteProp<'share-to-stream', {| sharedData: SharedData |}>, |}>; type SelectorProps = $ReadOnly<{| streamsByName: Map<string, Stream>, auth: Auth, mandatoryTopics: boolean, |}>; type Props = $ReadOnly<{| ...OuterProps, ...SelectorProps, dispatch: Dispatch, |}>; type State = $ReadOnly<{| /** The text the user has typed into the "stream name" field. */ streamName: string, /** An actual stream ID corresponding to streamName, or null if none does. */ streamId: number | null, topic: string, isStreamFocused: boolean, isTopicFocused: boolean, |}>; class ShareToStreamInner extends React.PureComponent<Props, State> { state = { streamName: '', streamId: null, topic: '', isStreamFocused: false, isTopicFocused: false, }; blurStream = () => { this.setState({ isStreamFocused: false }); }; focusStream = () => { this.setState({ isStreamFocused: true }); }; blurTopic = () => { this.setState({ isTopicFocused: false }); }; focusTopic = () => { const { streamId } = this.state; const { dispatch } = this.props; if (streamId !== null) { // We have an actual stream selected. Fetch its recent topic names. // TODO: why do we do this? `TopicAutocomplete` does the same thing, // with an effect that reruns when the stream changes. const narrow = streamNarrow(streamId); dispatch(fetchTopicsForStream(narrow)); } // If what's entered in the stream-name field isn't an actual stream, // then there's no point fetching topics. // Maybe we shouldn't be allowing this interaction in that case in // the first place? this.setState({ isTopicFocused: true }); }; handleStreamChange = streamName => { const stream = this.props.streamsByName.get(streamName); this.setState({ streamName, streamId: stream ? stream.stream_id : null }); }; handleTopicChange = topic => { this.setState({ topic }); }; handleStreamAutoComplete = (rawStream: string) => { // TODO: What is this for? (write down our assumptions) const streamName = rawStream.split('**')[1]; const stream = this.props.streamsByName.get(streamName); this.setState({ streamName, // TODO the "else" case ought to be impossible: the user chose a // stream in autocomplete, and we couldn't find it by name. streamId: stream ? stream.stream_id : null, isStreamFocused: false, }); }; handleTopicAutoComplete = (topic: string) => { this.setState({ topic }); }; getValidationErrors: string => $ReadOnlyArray<ValidationError> = message => { const { mandatoryTopics } = this.props; const { streamName, streamId, topic } = this.state; const { sharedData } = this.props.route.params; const result = []; if (streamId === null) { result.push('stream-invalid'); } if (streamName.trim() === '') { result.push('stream-empty'); } if (topic.trim() === '' && mandatoryTopics) { result.push('mandatory-topic-empty'); } if (sharedData.type === 'text' && message === '') { result.push('message-empty'); } return result; }; render() { const { sharedData } = this.props.route.params; const { streamName, streamId, topic, isStreamFocused, isTopicFocused } = this.state; const narrow = streamId !== null ? streamNarrow(streamId) : null; const sendTo = { streamName, /* $FlowFixMe[incompatible-cast]: ShareWrapper will only look at this * if getValidationErrors returns empty, so only if streamId is * indeed not null. Should make that logic less indirected and more * transparent. */ streamId: (streamId: number), topic, type: 'stream', }; return ( <ShareWrapper navigation={this.props.navigation} sharedData={sharedData} getValidationErrors={this.getValidationErrors} sendTo={sendTo} > <AnimatedScaleComponent visible={isStreamFocused}> <StreamAutocomplete filter={streamName} onAutocomplete={this.handleStreamAutoComplete} /> </AnimatedScaleComponent> <Input placeholder="Stream" value={streamName} onChangeText={this.handleStreamChange} onFocus={this.focusStream} onChange={this.focusStream} onBlur={this.blurStream} selectTextOnFocus /> <AnimatedScaleComponent visible={isTopicFocused}> <TopicAutocomplete text={topic} onAutocomplete={this.handleTopicAutoComplete} isFocused={isTopicFocused} narrow={narrow} /> </AnimatedScaleComponent> <Input placeholder="Topic" value={topic} onFocus={this.focusTopic} onBlur={this.blurTopic} onChangeText={this.handleTopicChange} editable={streamName !== ''} autoCapitalize="none" /> </ShareWrapper> ); } } const ShareToStream: ComponentType<OuterProps> = connect(state => ({ streamsByName: getStreamsByName(state), auth: getAuth(state), mandatoryTopics: getRealm(state).mandatoryTopics, }))(ShareToStreamInner); export default ShareToStream; ```
/content/code_sandbox/src/sharing/ShareToStream.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,431
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View, Modal } from 'react-native'; import type { ValidationError } from './ShareWrapper'; import type { RouteProp } from '../react-navigation'; import type { SharingNavigationProp } from './SharingScreen'; import type { UserId } from '../types'; import type { SharedData } from './types'; import { createStyleSheet } from '../styles'; import ZulipButton from '../common/ZulipButton'; import ZulipTextIntl from '../common/ZulipTextIntl'; import UserItem from '../users/UserItem'; import ChooseRecipientsScreen from './ChooseRecipientsScreen'; import ShareWrapper from './ShareWrapper'; const styles = createStyleSheet({ usersPreview: { padding: 10, }, chooseButton: { marginTop: 8, marginBottom: 8, width: '50%', alignSelf: 'flex-end', }, }); type Props = $ReadOnly<{| navigation: SharingNavigationProp<'share-to-pm'>, route: RouteProp<'share-to-pm', {| sharedData: SharedData |}>, |}>; type State = $ReadOnly<{| selectedRecipients: $ReadOnlyArray<UserId>, choosingRecipients: boolean, |}>; export default class ShareToPm extends React.PureComponent<Props, State> { state: State = { selectedRecipients: [], choosingRecipients: false, }; handleModalClose: () => void = () => { this.setState({ choosingRecipients: false }); }; handleChooseRecipients: ($ReadOnlyArray<UserId>) => void = selectedRecipients => { this.setState({ selectedRecipients }); this.setState({ choosingRecipients: false }); }; getValidationErrors: string => $ReadOnlyArray<ValidationError> = message => { const { selectedRecipients } = this.state; const { sharedData } = this.props.route.params; const result = []; if (selectedRecipients.length === 0) { result.push('recipients-empty'); } if (sharedData.type === 'text' && message === '') { result.push('message-empty'); } return result; }; renderUsersPreview: () => Node = () => { const { selectedRecipients } = this.state; if (selectedRecipients.length === 0) { return <ZulipTextIntl text="Please choose recipients to share with." />; } const preview = []; selectedRecipients.forEach(userId => { preview.push(<UserItem userId={userId} key={userId} />); }); return preview; }; render(): Node { const { selectedRecipients, choosingRecipients } = this.state; const { sharedData } = this.props.route.params; const sendTo = { selectedRecipients, type: 'pm' }; if (choosingRecipients) { return ( <Modal onRequestClose={this.handleModalClose}> <ChooseRecipientsScreen onComplete={this.handleChooseRecipients} /> </Modal> ); } return ( <ShareWrapper navigation={this.props.navigation} getValidationErrors={this.getValidationErrors} sharedData={sharedData} sendTo={sendTo} > <View style={styles.usersPreview}>{this.renderUsersPreview()}</View> <ZulipButton onPress={() => this.setState({ choosingRecipients: true })} style={styles.chooseButton} text="Choose recipients" /> </ShareWrapper> ); } } ```
/content/code_sandbox/src/sharing/ShareToPm.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
760
```javascript /* @flow strict-local */ import type { DraftsState, PerAccountApplicableAction } from '../types'; import { DRAFT_UPDATE, RESET_ACCOUNT_DATA } from '../actionConstants'; import { NULL_OBJECT } from '../nullObjects'; import { keyFromNarrow } from '../utils/narrow'; const initialState = NULL_OBJECT; const draftUpdate = (state, action) => { const narrowStr = keyFromNarrow(action.narrow); if (action.content.trim().length === 0) { // New content is blank; delete the draft. if (!state[narrowStr]) { return state; } const newState = { ...state }; delete newState[narrowStr]; return newState; } return state[narrowStr] === action.content ? state : { ...state, [narrowStr]: action.content }; }; export default ( state: DraftsState = initialState, // eslint-disable-line default-param-last action: PerAccountApplicableAction, ): DraftsState => { switch (action.type) { case RESET_ACCOUNT_DATA: return initialState; case DRAFT_UPDATE: return draftUpdate(state, action); default: return state; } }; ```
/content/code_sandbox/src/drafts/draftsReducer.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
254
```javascript /* @flow strict-local */ import type { Narrow, PerAccountState } from '../types'; import { keyFromNarrow } from '../utils/narrow'; export const getDraftForNarrow = (state: PerAccountState, narrow: Narrow): string => state.drafts[keyFromNarrow(narrow)] || ''; ```
/content/code_sandbox/src/drafts/draftsSelectors.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
68
```javascript /* @flow strict-local */ import type { Narrow, PerAccountAction } from '../types'; import { DRAFT_UPDATE } from '../actionConstants'; export const draftUpdate = (narrow: Narrow, content: string): PerAccountAction => ({ type: DRAFT_UPDATE, narrow, content, }); ```
/content/code_sandbox/src/drafts/draftsActions.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
65
```javascript /* @flow strict-local */ import React from 'react'; import type { Node, ComponentType } from 'react'; import { FlatList, ImageBackground, ScrollView, View, Text } from 'react-native'; import * as apiConstants from '../api/constants'; import type { Auth, Dispatch, GetText, UserId } from '../types'; import type { SharedData, SharedFile } from './types'; import * as api from '../api'; import * as logging from '../utils/logging'; import { BRAND_COLOR, createStyleSheet } from '../styles'; import Input from '../common/Input'; import ZulipButton from '../common/ZulipButton'; import ComponentWithOverlay from '../common/ComponentWithOverlay'; import { TranslationContext } from '../boot/TranslationProvider'; import { navigateBack, replaceWithChat } from '../nav/navActions'; import { showToast, showErrorAlert } from '../utils/info'; import { getAuth, getOwnUserId } from '../selectors'; import { connect } from '../react-redux'; import { streamNarrow, pmNarrowFromRecipients } from '../utils/narrow'; import { pmKeyRecipientsFromIds } from '../utils/recipient'; import { ensureUnreachable } from '../generics'; import { IconAttachment, IconCancel } from '../common/Icons'; import type { AppNavigationMethods } from '../nav/AppNavigator'; import { ApiError, RequestError } from '../api/apiErrors'; type SendTo = | {| type: 'pm', selectedRecipients: $ReadOnlyArray<UserId> |} // TODO(server-2.0): Drop streamName (#3918). Used below for sending. | {| type: 'stream', streamName: string, streamId: number, topic: string |}; const styles = createStyleSheet({ wrapper: { flex: 1, padding: 10, }, container: { flex: 1, }, imagePreview: { margin: 10, borderRadius: 5, width: 200, height: 200, }, actions: { flexDirection: 'row', }, button: { flex: 1, margin: 8, }, previewText: { color: 'white', textAlign: 'center', backgroundColor: '#000000a0', position: 'absolute', bottom: 0, left: 0, right: 0, }, }); // TODO(?): Could deduplicate with this type in ComposeBox. export type ValidationError = | 'mandatory-topic-empty' | 'stream-empty' | 'stream-invalid' | 'recipients-empty' | 'message-empty'; type OuterProps = $ReadOnly<{| navigation: AppNavigationMethods, children: Node, getValidationErrors: (message: string) => $ReadOnlyArray<ValidationError>, sendTo: SendTo, sharedData: SharedData, |}>; type SelectorProps = $ReadOnly<{| auth: Auth, ownUserId: UserId, |}>; type Props = $ReadOnly<{| ...OuterProps, ...SelectorProps, dispatch: Dispatch, |}>; type State = $ReadOnly<{| message: string, sending: boolean, files: $ReadOnlyArray<SharedFile>, |}>; /** * Wraps Around different sharing screens, * for minimal duplication of code. */ class ShareWrapperInner extends React.PureComponent<Props, State> { static contextType = TranslationContext; context: GetText; state = (() => { const { sharedData } = this.props; return { message: sharedData.type === 'text' ? sharedData.sharedText : '', sending: false, files: sharedData.type === 'text' ? [] : sharedData.files, }; })(); handleMessageChange = (message: string) => { this.setState({ message }); }; /** * Send received shared data as a message. * * Sends the shared data received from a 3rd party app and possibly modified * by the user, to the server, as a message. */ handleSend = async () => { const _ = this.context; const { auth, sendTo, sharedData, getValidationErrors } = this.props; let messageToSend = this.state.message; const validationErrors = getValidationErrors(messageToSend); if (validationErrors.length > 0) { const msg = validationErrors .map(error => { switch (error) { case 'stream-empty': return _('Please specify a stream.'); case 'stream-invalid': return _('Please specify a valid stream.'); case 'mandatory-topic-empty': return _('Please specify a topic.'); case 'recipients-empty': return _('Please choose recipients.'); case 'message-empty': return _('Message is empty.'); default: ensureUnreachable(error); throw new Error(); } }) .join('\n\n'); showErrorAlert(_('Message not sent'), msg); return; } this.setState({ sending: true }); showToast(_('Sending message')); if (sharedData.type === 'file') { const { files } = this.state; for (let i = 0; i < files.length; i++) { const { url, name: fileName } = files[i]; try { const response = await api.uploadFile(auth, url, fileName); messageToSend += `\n[${fileName}](${response.uri})\n`; } catch (errorIllTyped) { const error: mixed = errorIllTyped; // path_to_url if (!(error instanceof Error)) { logging.error('ShareWrapper: Unexpected non-error thrown'); } let msg = undefined; if ( error instanceof RequestError && error.httpStatus === 413 // 413 Payload Too Large: // path_to_url#issuecomment-1092140960 ) { msg = _('The server said the file is too large.'); } else if (error instanceof ApiError) { msg = _('The server said:\n\n{errorMessage}', { errorMessage: error.message }); } else if (error instanceof Error && error.message.length > 0) { msg = error.message; } this.setState({ sending: false }); showErrorAlert(_('Failed to upload file: {fileName}', { fileName }), msg); return; } } } const messageData = sendTo.type === 'pm' ? { content: messageToSend, type: 'private', to: JSON.stringify(sendTo.selectedRecipients), } : { content: messageToSend, type: 'stream', subject: sendTo.topic || apiConstants.kNoTopicTopic, // TODO(server-2.0): switch to numeric stream ID (#3918), not name; // then drop streamName from SendTo to: sendTo.streamName, }; try { await api.sendMessage(auth, messageData); } catch (err) { showToast(_('Failed to send message')); logging.error(err); this.onShareCancelled(sendTo); return; } showToast(_('Message sent')); this.onShareSuccess(sendTo); }; onShareCancelled = sendTo => { // If in the future this callback uses the `sendTo` data, it should get // it from its parameter (just like `onShareSuccess` does) and not from // the props. That's because the props may have changed since the // actual send request we just made. this.props.navigation.dispatch(navigateBack()); }; onShareSuccess = sendTo => { switch (sendTo.type) { case 'pm': { const { selectedRecipients } = sendTo; const { ownUserId } = this.props; const recipients = pmKeyRecipientsFromIds(selectedRecipients, ownUserId); const narrow = pmNarrowFromRecipients(recipients); this.props.navigation.dispatch(replaceWithChat(narrow)); break; } case 'stream': { const { streamId } = sendTo; const narrow = streamNarrow(streamId); this.props.navigation.dispatch(replaceWithChat(narrow)); break; } default: ensureUnreachable(sendTo.type); logging.error('Unknown type encountered in `sendTo`.'); this.onShareCancelled(); } }; deleteItem = toDelete => { const _ = this.context; this.setState(prevState => { const filteredItems = [...prevState.files].filter(item => item.url !== toDelete.url); if (prevState.files.length !== 0 && filteredItems.length === 0) { setTimeout(() => { showToast(_('Share canceled')); this.onShareCancelled(); }, 0); } return { files: filteredItems }; }); }; renderItem = ({ item, index, separators }) => ( <ComponentWithOverlay overlaySize={24} overlayColor="white" overlayPosition="bottom-right" overlay={<IconCancel color="gray" size={24} onPress={() => this.deleteItem(item)} />} > {item.mimeType.startsWith('image/') ? ( <ImageBackground source={{ uri: item.url }} style={styles.imagePreview}> <Text style={styles.previewText}>{item.name}</Text> </ImageBackground> ) : ( <View style={styles.imagePreview}> <IconAttachment size={200} color={BRAND_COLOR} /> <Text style={styles.previewText}>{item.name}</Text> </View> )} </ComponentWithOverlay> ); render() { const { children, getValidationErrors, sharedData } = this.props; const { message, sending } = this.state; return ( <> <ScrollView style={styles.wrapper} keyboardShouldPersistTaps="always" nestedScrollEnabled> <View style={styles.container}> {sharedData.type === 'file' && ( <FlatList data={this.state.files} renderItem={this.renderItem} keyExtractor={i => i.url} horizontal /> )} </View> {children} <Input value={message} placeholder="Message" onChangeText={this.handleMessageChange} multiline /> </ScrollView> <View style={styles.actions}> <ZulipButton onPress={this.onShareCancelled} style={styles.button} secondary text="Cancel" /> <ZulipButton style={styles.button} onPress={this.handleSend} text="Send" progress={sending} disabled={getValidationErrors(message).length > 0} isPressHandledWhenDisabled /> </View> </> ); } } const ShareWrapper: ComponentType<OuterProps> = connect(state => ({ auth: getAuth(state), ownUserId: getOwnUserId(state), }))(ShareWrapperInner); export default ShareWrapper; ```
/content/code_sandbox/src/sharing/ShareWrapper.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
2,334
```javascript /* @flow strict-local */ import deepFreeze from 'deep-freeze'; import { NULL_OBJECT } from '../../nullObjects'; import draftsReducer from '../draftsReducer'; import { DRAFT_UPDATE } from '../../actionConstants'; import { topicNarrow, keyFromNarrow } from '../../utils/narrow'; import * as eg from '../../__tests__/lib/exampleData'; describe('draftsReducer', () => { const testNarrow = topicNarrow(eg.stream.stream_id, 'denmark2'); const testNarrowStr = keyFromNarrow(testNarrow); describe('RESET_ACCOUNT_DATA', () => { const initialState = eg.baseReduxState.drafts; const action1 = { type: DRAFT_UPDATE, content: 'Hello', narrow: testNarrow }; const prevState = draftsReducer(initialState, action1); expect(prevState).not.toEqual(initialState); expect(draftsReducer(prevState, eg.action.reset_account_data)).toEqual(initialState); }); describe('DRAFT_UPDATE', () => { test('add a new draft key drafts', () => { const prevState = NULL_OBJECT; expect( draftsReducer( prevState, deepFreeze({ type: DRAFT_UPDATE, content: 'Hello', narrow: testNarrow }), ), ).toEqual({ [testNarrowStr]: 'Hello' }); }); test('adding the same draft to drafts does not mutate the state', () => { const prevState = deepFreeze({ [testNarrowStr]: 'Hello' }); expect( draftsReducer( prevState, deepFreeze({ type: DRAFT_UPDATE, content: 'Hello', narrow: testNarrow }), ), ).toBe(prevState); }); test('when content is empty remove draft from state', () => { const prevState = deepFreeze({ [testNarrowStr]: 'Hello' }); expect( draftsReducer(prevState, { type: DRAFT_UPDATE, content: '', narrow: testNarrow }), ).toEqual({}); }); test('remove draft when content is white space', () => { const prevState = deepFreeze({ [testNarrowStr]: 'Hello' }); expect( draftsReducer(prevState, { type: DRAFT_UPDATE, content: ' ', narrow: testNarrow }), ).toEqual({}); }); test('do not mutate state if there is nothing to remove', () => { const prevState = NULL_OBJECT; expect( draftsReducer( prevState, deepFreeze({ type: DRAFT_UPDATE, content: '', narrow: testNarrow }), ), ).toBe(prevState); }); }); }); ```
/content/code_sandbox/src/drafts/__tests__/draftsReducer-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
564
```javascript /* @flow strict-local */ import { getDraftForNarrow } from '../draftsSelectors'; import { topicNarrow, keyFromNarrow } from '../../utils/narrow'; import * as eg from '../../__tests__/lib/exampleData'; describe('getDraftForNarrow', () => { test('return content of draft if exists', () => { const narrow = topicNarrow(eg.stream.stream_id, 'topic'); const state = eg.reduxState({ drafts: { [keyFromNarrow(narrow)]: 'content', }, }); const draft = getDraftForNarrow(state, narrow); expect(draft).toEqual('content'); }); test('return empty string if not exists', () => { const narrow = topicNarrow(eg.stream.stream_id, 'topic'); const state = eg.reduxState({ drafts: { [keyFromNarrow(narrow)]: 'content', }, }); const draft = getDraftForNarrow(state, topicNarrow(eg.stream.stream_id, 'topic1')); expect(draft).toEqual(''); }); }); ```
/content/code_sandbox/src/drafts/__tests__/draftsSelectors-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
238
```javascript /* @flow strict-local */ // $FlowFixMe[untyped-import] import Color from 'color'; import type { ColorValue } from 'react-native/Libraries/StyleSheet/StyleSheet'; export const foregroundColorFromBackground = (color: ColorValue): 'black' | 'white' => Color(color).luminosity() > 0.4 ? 'black' : 'white'; export const colorHashFromString = (name: string): string => { let hash = 0; for (let i = 0; i < name.length; i++) { hash = hash * 31 + name.charCodeAt(i); hash %= 0x1000000; } return `#${hash.toString(16).padStart(6, '0')}`; }; ```
/content/code_sandbox/src/utils/color.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
163
```javascript /* @flow strict-local */ export const removeItemsFromArray = ( input: $ReadOnlyArray<number>, itemsToRemove: $ReadOnlyArray<number>, ): $ReadOnlyArray<number> => { const output = input.filter((item: number) => !itemsToRemove.includes(item)); return input.length === output.length ? input : output; }; export function addItemsToArray<T>( input: $ReadOnlyArray<T>, itemsToAdd: $ReadOnlyArray<T>, ): $ReadOnlyArray<T> { const newItems = itemsToAdd.filter(item => !input.includes(item)); return newItems.length > 0 ? [...input, ...itemsToAdd] : input; } export function filterArray<T>( input: $ReadOnlyArray<T>, predicate: T => boolean, ): $ReadOnlyArray<T> { const filteredList = input.filter(predicate); return filteredList.length === input.length ? input : filteredList; } export function replaceItemInArray<T>( input: $ReadOnlyArray<T>, predicate: (item: T) => boolean, replaceFunc: (item?: T) => T, ): $ReadOnlyArray<T> { let replacementHappened = false; const newArray = input.map(x => { if (predicate(x)) { replacementHappened = true; return replaceFunc(x); } return x; }); if (!replacementHappened) { newArray.push(replaceFunc()); } return newArray; } ```
/content/code_sandbox/src/utils/immutability.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
304
```javascript /* @flow strict */ /* eslint-disable ft-flow/type-id-match */ /** * Type of a round-trip-capable JSONable object. * * Note that this is not the same as the type of objects which `JSON.stringify` * will accept, nor even the type of objects which `JSON.stringify` will accept * without returning `undefined`. For example, * * JSON.stringify({f: 2, g: () => 3, h: undefined}) === '{"f":2}' * * which of course will not be equal to the original object after parsing. */ export type JSONable = | null | string | number | boolean | {| +[string]: JSONable |} // [] | $ReadOnlyArray<JSONable>; // [] This should just be `JSONableDict`, but Flow doesn't handle // mutually-recursive types very well. /** * Type of a round-trip-capable JSONable dictionary. * * See documentation of `JSONable` for caveats. */ export type JSONableDict = {| +[string]: JSONable |}; /** * Approximate type of a JSONable value received as input. * * Unlike the definition of `JSONableDict`, this permits the possibility of * `void` elements as dictionary members. This is a workaround for Flow's * by-design soundness hole involving indexer elements: * * ```flow * const obj: {| [string]: string |} = { a: "a" }; * const value: string = obj['b']; * value.trim(); // kaboom! * ``` * * ... that is, Flow will assume **all subscript accesses to indexer-property- * typed values are valid**, and will not mark values extracted therefrom as * potentially undefined. (For references indicating that this is, indeed, by * design, see [0] and [1].) * * Adding `void` as a possible dictionary entry type to JSONable would solve * this problem -- but only at the cost of introducing others: * * For output, it is possible to feed a `void`-containing structure to a * serializing function, even though that structure cannot be reversibly * JSON- serialized. * * When processing input, `Object.values` (and related functions) will yield * a type which contains `void`, even though no value in a just-parsed JSON * object can actually be `undefined`. * * We can mostly avoid these problems by creating a secondary JSONable-like * type, `JSONableInput`, used only for validation and transformation of JSON * input data. * * As JSONable <: JSONableInput, but not vice versa, JSON values should * generally be passed around as `JSONable` until and unless they're actually * being validated; they can then be locally cast to `JSONableInput`. * * - [0] path_to_url#toc-objects-as-maps * - [1] path_to_url */ export type JSONableInput = | null | string | number | boolean | {| +[string]: JSONableInput | void |} | $ReadOnlyArray<JSONableInput>; /** * Type of a dictionary from JSON input. * * See documentation of `JSONable` and `JSONableInput` for caveats. */ export type JSONableInputDict = {| +[string]: JSONableInput | void |}; ```
/content/code_sandbox/src/utils/jsonable.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
732