dispatch/client/js/utils/messageHeight.js

79 lines
1.8 KiB
JavaScript
Raw Normal View History

2016-02-16 21:43:25 +00:00
const lineHeight = 24;
const userListWidth = 200;
const smallScreen = 600;
2017-05-12 08:51:37 +00:00
function findBreakpointsString(text, breakpoints, index) {
for (let i = 0; i < text.length; i++) {
const char = text.charAt(i);
if (char === ' ') {
breakpoints.push({ end: i + index, next: i + 1 + index });
} else if (i !== text.length - 1 && (char === '-' || char === '?')) {
breakpoints.push({ end: i + 1 + index, next: i + 1 + index });
}
}
}
export function findBreakpoints(text) {
const breakpoints = [];
let length = 0;
if (typeof text === 'string') {
findBreakpointsString(text, breakpoints, length);
length = text.length;
} else if (Array.isArray(text)) {
for (let i = 0; i < text.length; i++) {
const node = text[i];
if (typeof node === 'string') {
findBreakpointsString(node, breakpoints, length);
length += node.length;
} else {
findBreakpointsString(node.props.children, breakpoints, length);
length += node.props.children.length;
}
}
}
return [breakpoints, length];
}
2018-04-05 23:46:22 +00:00
export function messageHeight(
message,
wrapWidth,
charWidth,
indent = 0,
windowWidth
) {
2016-02-16 21:43:25 +00:00
let pad = (6 + (message.from ? message.from.length + 1 : 0)) * charWidth;
let height = lineHeight + 8;
if (message.channel && windowWidth > smallScreen) {
wrapWidth -= userListWidth;
2016-02-16 21:43:25 +00:00
}
2018-04-05 23:46:22 +00:00
if (pad + message.length * charWidth < wrapWidth) {
2016-02-16 21:43:25 +00:00
return height;
}
const breaks = message.breakpoints;
2016-02-16 21:43:25 +00:00
let prevBreak = 0;
let prevPos = 0;
for (let i = 0; i < breaks.length; i++) {
2018-04-05 23:46:22 +00:00
if (pad + (breaks[i].end - prevBreak) * charWidth >= wrapWidth) {
prevBreak = prevPos;
pad = indent;
height += lineHeight;
}
2016-02-16 21:43:25 +00:00
prevPos = breaks[i].next;
}
2016-02-16 21:43:25 +00:00
2018-04-05 23:46:22 +00:00
if (pad + (message.length - prevBreak) * charWidth >= wrapWidth) {
height += lineHeight;
2016-02-16 21:43:25 +00:00
}
return height;
}