(core) Adding links to description tooltips

Summary: Column and widget descriptions now support links in text.

Test Plan: Updated

Reviewers: georgegevoian

Reviewed By: georgegevoian

Differential Revision: https://phab.getgrist.com/D3981
This commit is contained in:
Jarosław Sadziński 2023-08-04 13:32:53 +02:00
parent 5dfa9a542c
commit 00b88fd683
12 changed files with 260 additions and 120 deletions

View File

@ -68,6 +68,7 @@ export class Banner extends Disposable {
cssBanner.cls(`-${this._options.style}`),
this._buildContent(),
this._buildButtons(),
testId('element')
);
}

View File

@ -266,7 +266,7 @@ DetailView.prototype.buildFieldDom = function(field, row) {
kd.cssClass(function() { return 'detail_theme_field_' + self.viewSection.themeDef(); }),
dom('div.g_record_detail_label_container',
dom('div.g_record_detail_label', kd.text(field.label)),
kd.scope(field.description, desc => desc ? descriptionInfoTooltip(kd.text(field.description), "colmun") : null)
kd.scope(field.description, desc => desc ? descriptionInfoTooltip(desc, "colmun") : null)
),
dom('div.g_record_detail_value'),
);
@ -299,7 +299,7 @@ DetailView.prototype.buildFieldDom = function(field, row) {
kd.cssClass(function() { return 'detail_theme_field_' + self.viewSection.themeDef(); }),
dom('div.g_record_detail_label_container',
dom('div.g_record_detail_label', kd.text(field.displayLabel)),
kd.scope(field.description, desc => desc ? descriptionInfoTooltip(kd.text(field.description), "column") : null)
kd.scope(field.description, desc => desc ? descriptionInfoTooltip(desc, "column") : null)
),
dom('div.g_record_detail_value',
kd.toggleClass('scissors', isCopyActive),

View File

@ -1105,7 +1105,7 @@ GridView.prototype.buildDom = function() {
if (btn) { btn.click(); }
}),
dom('div.g-column-label',
kd.scope(field.description, desc => desc ? descriptionInfoTooltip(kd.text(field.description), "column") : null),
kd.scope(field.description, desc => desc ? descriptionInfoTooltip(desc, "column") : null),
dom.on('mousedown', ev => isEditingLabel() ? ev.stopPropagation() : true),
// We are using editableLabel here, but we don't use it for editing.
kf.editableLabel(self.isPreview ? field.label : field.displayLabel, ko.observable(false)),

View File

@ -8,6 +8,7 @@
import {prepareForTransition} from 'app/client/ui/transitions';
import {testId, theme, vars} from 'app/client/ui2018/cssVars';
import {icon} from 'app/client/ui2018/icons';
import {makeLinks} from 'app/client/ui2018/links';
import {menuCssClass} from 'app/client/ui2018/menus';
import {dom, DomContents, DomElementArg, DomElementMethod, styled} from 'grainjs';
import Popper from 'popper.js';
@ -138,7 +139,8 @@ export function showTooltip(
// Add the content element.
const content = cssTooltip({role: 'tooltip'}, tipContent(ctl), testId(`tooltip`));
document.body.appendChild(content);
// Prepending instead of appending allows better text selection, as this element is on top.
document.body.prepend(content);
// Create a popper for positioning the tooltip content relative to refElem.
const popperOptions: Popper.PopperOptions = {
@ -203,26 +205,56 @@ export function setHoverTooltip(
// Controller for closing the tooltip, if one is open.
let tipControl: ITooltipControl|undefined;
// A marker, that the tooltip should be closed, but we are waiting for the mouseup event.
const POSTPONED = Symbol();
// Timer to open or close the tooltip, depending on whether tipControl is set.
let timer: ReturnType<typeof setTimeout>|undefined;
let timer: ReturnType<typeof setTimeout>|undefined|typeof POSTPONED;
// To allow user select text, we will monitor if the selection has started in the tooltip (by listening
// to the mousedown event). If it has and mouse goes outside, we will mark that the tooltip should be closed.
// When the selection is over (by listening to mouseup on window), a new close is scheduled with 1.4s, to allow
// user to press Ctrl+C (but only if the marker - POSTPONED - is still set).
let mouseGrabbed = false;
function grabMouse(tip: Element) {
mouseGrabbed = true;
const listener = dom.onElem(window, 'mouseup', () => {
mouseGrabbed = false;
if (timer === POSTPONED) {
scheduleCloseIfOpen(1400);
}
});
dom.autoDisposeElem(tip, listener);
// Disable text selection in any other element except this one. This class sets user-select: none to all
// elements except the tooltip. This helps to avoid accidental selection of text in other elements, once
// the mouse leaves the tooltip.
document.body.classList.add(cssDisableSelectOnAll.className);
dom.onDisposeElem(tip, () => document.body.classList.remove(cssDisableSelectOnAll.className));
}
function clearTimer() {
if (timer) { clearTimeout(timer); timer = undefined; }
if (timer !== POSTPONED) { clearTimeout(timer); }
timer = undefined;
}
function resetTimer(func: () => void, delay: number) {
function resetTimer(func: () => void, delay: number|typeof POSTPONED) {
clearTimer();
timer = setTimeout(func, delay);
timer = delay === POSTPONED ? POSTPONED : setTimeout(func, delay);
}
function scheduleCloseIfOpen() {
function scheduleCloseIfOpen(timeout = closeDelay) {
clearTimer();
if (tipControl) { resetTimer(close, closeDelay); }
if (tipControl) {
resetTimer(close, mouseGrabbed ? POSTPONED : timeout);
}
}
function open() {
clearTimer();
tipControl = showTooltip(refElem, ctl => tipContentFunc({...ctl, close}), options);
dom.onElem(tipControl.getDom(), 'mouseenter', clearTimer);
dom.onElem(tipControl.getDom(), 'mouseleave', scheduleCloseIfOpen);
dom.onDisposeElem(tipControl.getDom(), () => close());
const tipDom = tipControl.getDom();
dom.onElem(tipDom, 'mouseenter', clearTimer);
dom.onElem(tipDom, 'mouseleave', () => scheduleCloseIfOpen());
dom.onElem(tipDom, 'mousedown', grabMouse.bind(null, tipDom));
dom.onDisposeElem(tipDom, () => close());
if (timeoutMs) { resetTimer(close, timeoutMs); }
}
function close() {
@ -247,7 +279,7 @@ export function setHoverTooltip(
}
});
dom.onElem(refElem, 'mouseleave', scheduleCloseIfOpen);
dom.onElem(refElem, 'mouseleave', () => scheduleCloseIfOpen());
if (openOnClick) {
// If requested, re-open on click.
@ -354,30 +386,49 @@ export function withInfoTooltip(
* Renders an description info icon that shows a tooltip with the specified `content` on click.
*/
export function descriptionInfoTooltip(
content: DomContents,
content: string,
testPrefix: string,
...domArgs: DomElementArg[]) {
const body = makeLinks(content);
const options = {
closeDelay: 200,
key: 'columnDescription',
openOnClick: true,
};
const builder = () => cssDescriptionInfoTooltip(
body,
// Used id test to find the origin of the tooltip regardless webdriver implementation (some of them start)
cssTooltipCorner(testId('tooltip-origin')),
testId(`${testPrefix}-info-tooltip-popup`),
{tabIndex: '-1'}
);
return cssDescriptionInfoTooltipButton(
icon('Info', dom.cls("info_toggle_icon")),
testId(`${testPrefix}-info-tooltip`),
dom.on('mousedown', (e) => e.stopPropagation()),
dom.on('click', (e) => e.stopPropagation()),
hoverTooltip(() => cssDescriptionInfoTooltip(content, testId(`${testPrefix}-info-tooltip-popup`)), {
closeDelay: 200,
key: 'columnDescription',
openOnClick: true,
}),
hoverTooltip(builder, options),
dom.cls("info_toggle_icon_wrapper"),
...domArgs,
);
}
const cssTooltipCorner = styled('div', `
position: absolute;
width: 0;
height: 0;
top: 0;
left: 0;
visibility: hidden;
`);
const cssDescriptionInfoTooltip = styled('div', `
position: relative;
white-space: pre-wrap;
text-align: left;
text-overflow: ellipsis;
overflow: hidden;
line-height: 1.4;
max-width: min(500px, calc(100vw - 80px)); /* can't use 100%, 500px and 80px are picked by hand */
`);
@ -412,6 +463,13 @@ const cssTooltip = styled('div', `
padding: 8px 16px;
margin: 4px;
transition: opacity 0.2s;
user-select: auto;
`);
const cssDisableSelectOnAll = styled('div', `
& *:not(.${cssTooltip.className}, .${cssTooltip.className} *) {
user-select: none;
}
`);
const cssTooltipCloseButton = styled('div', `

View File

@ -1,7 +1,9 @@
import {findLinks} from 'app/client/lib/textUtils';
import { sameDocumentUrlState, urlState } from 'app/client/models/gristUrlState';
import { hideInPrintView, theme } from 'app/client/ui2018/cssVars';
import { colors, hideInPrintView, testId, theme } from 'app/client/ui2018/cssVars';
import {cssIconBackground, icon} from 'app/client/ui2018/icons';
import { CellValue } from 'app/plugin/GristData';
import { dom, IDomArgs, Observable, styled } from 'grainjs';
import { dom, DomArg, IDomArgs, Observable, styled } from 'grainjs';
/**
* Styling for a simple <A HREF> link.
@ -49,3 +51,67 @@ export async function onClickHyperLink(ev: MouseEvent, url: CellValue) {
ev.preventDefault();
await urlState().pushUrl(newUrlState);
}
/**
* Generates dom contents out of a text with clickable links.
*/
export function makeLinks(text: string) {
try {
const domElements: DomArg[] = [];
for (const {value, isLink} of findLinks(text)) {
if (isLink) {
// Wrap link with a span to provide hover on and to override wrapping.
domElements.push(cssMaybeWrap(
gristLink(value,
cssIconBackground(
icon("FieldLink", testId('tb-link-icon')),
dom.cls(cssHoverInText.className),
),
),
linkColor(value),
testId("text-link")
));
} else {
domElements.push(value);
}
}
return domElements;
} catch(ex) {
// In case when something went wrong, simply log and return original text, as showing
// links is not that important.
console.warn("makeLinks failed", ex);
return text;
}
}
// For links we want to break all the parts, not only words.
const cssMaybeWrap = styled('span', `
white-space: inherit;
.text_wrapping & {
word-break: break-all;
white-space: pre-wrap;
}
`);
// A gentle transition effect on hover in, and the same effect on hover out with a little delay.
export const cssHoverIn = (parentClass: string) => styled('span', `
--icon-color: var(--grist-actual-cell-color, ${colors.lightGreen});
margin: -1px 2px 2px 0;
border-radius: 3px;
transition-property: background-color;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 150ms;
transition-delay: 90ms;
.${parentClass}:hover & {
--icon-background: ${colors.lightGreen};
--icon-color: white;
transition-duration: 80ms;
transition-delay: 0ms;
}
`);
const cssHoverInText = cssHoverIn(cssMaybeWrap.className);
const linkColor = styled('span', `
color: var(--grist-actual-cell-color, ${colors.lightGreen});;
`);

View File

@ -3,8 +3,8 @@ import { ViewFieldRec } from 'app/client/models/entities/ViewFieldRec';
import { constructUrl } from 'app/client/models/gristUrlState';
import { colors, testId } from 'app/client/ui2018/cssVars';
import { cssIconBackground, icon } from 'app/client/ui2018/icons';
import { gristLink } from 'app/client/ui2018/links';
import { cssHoverIn, NTextBox } from 'app/client/widgets/NTextBox';
import { cssHoverIn, gristLink } from 'app/client/ui2018/links';
import { NTextBox } from 'app/client/widgets/NTextBox';
import { CellValue } from 'app/common/DocActions';
import { Computed, dom, styled } from 'grainjs';

View File

@ -1,15 +1,13 @@
import { fromKoSave } from 'app/client/lib/fromKoSave';
import { findLinks } from 'app/client/lib/textUtils';
import { DataRowModel } from 'app/client/models/DataRowModel';
import { ViewFieldRec } from 'app/client/models/entities/ViewFieldRec';
import { cssRow } from 'app/client/ui/RightPanelStyles';
import { alignmentSelect, cssButtonSelect, makeButtonSelect } from 'app/client/ui2018/buttonSelect';
import { colors, testId } from 'app/client/ui2018/cssVars';
import { cssIconBackground, icon } from 'app/client/ui2018/icons';
import { gristLink } from 'app/client/ui2018/links';
import { testId } from 'app/client/ui2018/cssVars';
import { makeLinks } from 'app/client/ui2018/links';
import { NewAbstractWidget, Options } from 'app/client/widgets/NewAbstractWidget';
import { Computed, dom, DomArg, DomContents, fromKo, Observable, styled } from 'grainjs';
import {makeT} from 'app/client/lib/localization';
import { Computed, dom, DomContents, fromKo, Observable } from 'grainjs';
import { makeT } from 'app/client/lib/localization';
const t = makeT('NTextBox');
@ -69,64 +67,3 @@ export class NTextBox extends NewAbstractWidget {
);
}
}
function makeLinks(text: string) {
try {
const domElements: DomArg[] = [];
for (const {value, isLink} of findLinks(text)) {
if (isLink) {
// Wrap link with a span to provide hover on and to override wrapping.
domElements.push(cssMaybeWrap(
gristLink(value,
cssIconBackground(
icon("FieldLink", testId('tb-link-icon')),
dom.cls(cssHoverInText.className),
),
),
linkColor(value),
testId("text-link")
));
} else {
domElements.push(value);
}
}
return domElements;
} catch(ex) {
// In case when something went wrong, simply log and return original text, as showing
// links is not that important.
console.warn("makeLinks failed", ex);
return text;
}
}
// For links we want to break all the parts, not only words.
const cssMaybeWrap = styled('span', `
white-space: inherit;
.text_wrapping & {
word-break: break-all;
white-space: pre-wrap;
}
`);
// A gentle transition effect on hover in, and the same effect on hover out with a little delay.
export const cssHoverIn = (parentClass: string) => styled('span', `
--icon-color: var(--grist-actual-cell-color, ${colors.lightGreen});
margin: -1px 2px 2px 0;
border-radius: 3px;
transition-property: background-color;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 150ms;
transition-delay: 90ms;
.${parentClass}:hover & {
--icon-background: ${colors.lightGreen};
--icon-color: white;
transition-duration: 80ms;
transition-delay: 0ms;
}
`);
const cssHoverInText = cssHoverIn(cssMaybeWrap.className);
const linkColor = styled('span', `
color: var(--grist-actual-cell-color, ${colors.lightGreen});;
`);

View File

@ -6,3 +6,31 @@ declare namespace Chai {
notIncludeMembers<T>(superset: T[], subset: T[], message?: string): void;
}
}
declare module "selenium-webdriver" {
interface WebDriver {
withActions(cb: (actions: WebActions) => void): Promise<void>;
}
// This is not a complete definition of available methods, but only those that we use for now.
// TODO: find documentation for this interface or update selenium-webdriver.
interface WebActions {
contextClick(el?: WebElement): WebActions;
click(el?: WebElement): WebActions;
press(): WebActions;
move(params: {origin?: WebElement|string, x?: number, y?: number}): WebActions;
keyDown(key: string): WebActions;
keyUp(key: string): WebActions;
dragAndDrop(element: WebElement, target: WebElement): WebActions;
release(): WebActions;
doubleClick(element: WebElement): WebActions;
pause(ms: number): WebActions;
}
}
import "mocha-webdriver";
declare module "mocha-webdriver" {
// It looks like this hack makes tsc see our definition as primary, adding
// the typed version override (of the withActions method) as the default one.
export declare let driver: import("selenium-webdriver").WebDriver;
}

View File

@ -100,6 +100,43 @@ describe('DescriptionColumn', function() {
assert.isFalse(await gu.getColumnHeader({col: 'D'}).isPresent());
});
it('shows links in the column description', async () => {
const revert = await gu.begin();
// Add a column and add a description with a link.
await addColumn();
await clickAddDescription();
await gu.sendKeys('First line');
await gu.sendKeys(Key.SHIFT, Key.ENTER, Key.NULL);
await gu.sendKeys('Second line https://example.com');
await gu.sendKeys(Key.SHIFT, Key.ENTER, Key.NULL);
await gu.sendKeys('Third line');
await pressSave();
const header = await gu.getColumnHeader({col: 'D'});
// Make sure it has a tooltip.
assert.isTrue(await header.find(".test-column-info-tooltip").isDisplayed());
// Click the tooltip.
await header.find(".test-column-info-tooltip").click();
// Make sure we have a link there.
const testTooltip = async () => {
const tooltip = driver.find(".test-tooltip");
assert.equal(await tooltip.find(".test-text-link a").getAttribute('href'), "https://example.com/");
assert.equal(await tooltip.find(".test-text-link").getText(), "https://example.com");
assert.equal(await tooltip.getText(), "First line\nSecond line \nhttps://example.com\nThird line");
};
await testTooltip();
// Convert it to a card view.
await gu.changeWidget('Card');
await openCardColumnTooltip('D');
await testTooltip();
await revert();
});
it('should close popup by enter and escape', async () => {
// Add another column, make sure that enter and escape work.
await addColumn();
@ -387,13 +424,14 @@ describe('DescriptionColumn', function() {
const doc = await mainSession.tempDoc(cleanup, "CardView.grist", { load: true });
const docId = doc.id;
// Make more room for switching between columns.
await gu.toggleSidePanel('left', 'close');
await gu.openColumnPanel();
await addColumnDescription(api, docId, 'B');
// Column description editable in right panel
await driver.find('.test-right-opener').click();
await gu.getCell({ rowNum: 1, col: 'B' }).click();
await driver.find('.test-right-tab-field').click();
assert.equal(await getDescriptionInput().value(), 'This is the column description\nIt is in two lines');
await gu.getCell({ rowNum: 1, col: 'A' }).click();
@ -408,6 +446,7 @@ describe('DescriptionColumn', function() {
await gu.getCell({ rowNum: 1, col: 'B' }).click();
assert.equal(await getDescriptionInput().value(), '');
await gu.toggleSidePanel('left', 'open');
});
it('should show info tooltip only if there is a description', async () => {
@ -428,16 +467,7 @@ describe('DescriptionColumn', function() {
.isPresent()
);
const detailDescribedColumnFirstRow = await gu.getDetailCell('B', 1);
const toggle = await detailDescribedColumnFirstRow
.findClosest(".g_record_detail_el")
.find(".test-column-info-tooltip");
// The toggle to show the description is present if there is a description
assert.isTrue(await toggle.isPresent());
// Open the tooltip
await toggle.click();
await waitForTooltip();
await openCardColumnTooltip('B');
// Check the content of the tooltip
const descriptionTooltip = await driver
@ -561,3 +591,15 @@ async function saveVisible() {
async function cancelVisible() {
return await driver.find(".test-column-title-cancel").isDisplayed();
}
async function openCardColumnTooltip(col: string) {
const detailDescribedColumnFirstRow = await gu.getDetailCell(col, 1);
const toggle = await detailDescribedColumnFirstRow
.findClosest(".g_record_detail_el")
.find(".test-column-info-tooltip");
// The toggle to show the description is present if there is a description
assert.isTrue(await toggle.isPresent());
// Open the tooltip
await toggle.click();
await waitForTooltip();
}

View File

@ -7,14 +7,17 @@ describe('DescriptionWidget', function() {
this.timeout(20000);
const cleanup = setupTestSuite();
it('should support basic edition in right panel', async () => {
before(async () => {
const mainSession = await gu.session().teamSite.login();
await mainSession.tempDoc(cleanup, "CardView.grist", { load: true });
await gu.openWidgetPanel();
});
it('should support basic edition in right panel', async () => {
const newWidgetDesc = "This is the widget description\nIt is in two lines";
await gu.toggleSidePanel('right', 'open');
const rightPanelDescriptionInput = await driver.find('.test-right-panel .test-right-widget-description');
await rightPanelDescriptionInput.click();
await gu.clearInput();
await rightPanelDescriptionInput.sendKeys(newWidgetDesc);
// Click on other input to unselect descriptionInput
await driver.find('.test-right-panel .test-right-widget-title').click();
@ -22,9 +25,6 @@ describe('DescriptionWidget', function() {
});
it('should support basic edition in widget popup', async () => {
const mainSession = await gu.session().teamSite.login();
await mainSession.tempDoc(cleanup, "CardView.grist", { load: true });
const widgetName = "Table";
const newWidgetDescFirstLine = "First line of the description";
const newWidgetDescSecondLine = "Second line of the description";
@ -34,9 +34,6 @@ describe('DescriptionWidget', function() {
});
it('should show info tooltip only if there is a description', async () => {
const mainSession = await gu.session().teamSite.login();
await mainSession.tempDoc(cleanup, "CardView.grist", { load: true });
const newWidgetDesc = "New description for widget Table";
await addWidgetDescription("Table", newWidgetDesc);
@ -46,6 +43,21 @@ describe('DescriptionWidget', function() {
await checkDescValueInWidgetTooltip("Table", newWidgetDesc);
});
it('shows link in a description', async () => {
await addWidgetDescription("Table", "Some text with a https://www.grist.com link");
assert.isFalse(await getWidgetTooltip("Single card").isPresent());
assert.isTrue(await getWidgetTooltip("Table").isPresent());
await getWidgetTooltip("Table").click();
await waitForTooltip();
const descriptionTooltip = await driver
.find('.test-widget-info-tooltip-popup');
assert.equal(await descriptionTooltip.getText(), "Some text with a \nhttps://www.grist.com link");
assert.equal(await descriptionTooltip.find(".test-text-link a").getAttribute('href'), "https://www.grist.com/");
assert.equal(await descriptionTooltip.find(".test-text-link").getText(), "https://www.grist.com");
});
});
async function waitForEditPopup() {
@ -77,6 +89,7 @@ async function addWidgetDescription(widgetName: string, desc: string, descSecond
// Edit the description of the widget inside the popup
await widgetDescInput.click();
await gu.clearInput();
await widgetDescInput.sendKeys(desc);
if (descSecondLine !== "") {
await widgetDescInput.sendKeys(Key.ENTER, descSecondLine);

View File

@ -4359,9 +4359,7 @@ async function getWorkspaceId(api: UserAPIImpl, name: string) {
return workspaces.find((w) => w.name === name)!.id;
}
// TODO: deal with safe port allocation
const webhooksTestPort = 34365;
const webhooksTestPort = Number(process.env.WEBHOOK_TEST_PORT);
async function setupDataDir(dir: string) {
// we'll be serving Hello.grist content for various document ids, so let's make copies of it in

View File

@ -51,11 +51,8 @@ function backupEnvironmentVariables() {
});
}
/*
TODO: this hardcoded port numbers might cause conflicts in parallel tests executions. replace with someone more generic
*/
const webhooksTestPort = 34365;
const webhooksTestProxyPort = 22335;
const webhooksTestPort = Number(process.env.WEBHOOK_TEST_PORT);
const webhooksTestProxyPort = Number(process.env.WEBHOOK_TEST_PROXY_PORT);
describe('Webhooks-Proxy', function () {
// A testDir of the form grist_test_{USER}_{SERVER_NAME}