Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#1044 implement user column type #1045

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions app/client/components/FormRenderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -846,6 +846,10 @@ class RefRenderer extends BaseFieldRenderer {
}
}

class UserRenderer extends TextRenderer {
protected inputType = 'text';
}

const FieldRenderers = {
'Text': TextRenderer,
'Numeric': NumericRenderer,
Expand All @@ -857,6 +861,7 @@ const FieldRenderers = {
'DateTime': DateTimeRenderer,
'Ref': RefRenderer,
'RefList': RefListRenderer,
'User': UserRenderer,
};

const FormRenderers = {
Expand Down
3 changes: 2 additions & 1 deletion app/client/ui/GridViewMenus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ export function getColumnTypes(gristDoc: GristDoc, tableId: string, pure = false
"ChoiceList",
`Ref:${tableId}`,
`RefList:${tableId}`,
"Attachments"];
"Attachments",
"User"];
return typeNames.map(type => ({type, obj: UserType.typeDefs[type.split(':')[0]]}))
.map((ct): {
displayName: string,
Expand Down
2 changes: 2 additions & 0 deletions app/client/ui2018/IconList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export type IconName = "ChartArea" |
"FieldText" |
"FieldTextbox" |
"FieldToggle" |
"FieldUser" |
"LoginStreamline" |
"LoginUnify" |
"LoginVisualize" |
Expand Down Expand Up @@ -188,6 +189,7 @@ export const IconList: IconName[] = ["ChartArea",
"FieldText",
"FieldTextbox",
"FieldToggle",
"FieldUser",
"LoginStreamline",
"LoginUnify",
"LoginVisualize",
Expand Down
32 changes: 32 additions & 0 deletions app/client/widgets/User.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import {NTextBox} from "app/client/widgets/NTextBox";
import {ViewFieldRec} from "app/client/models/entities/ViewFieldRec";
import {DataRowModel} from "app/client/models/DataRowModel";
import {icon} from "app/client/ui2018/icons";
import {theme} from "app/client/ui2018/cssVars";
import {dom, styled} from "grainjs";

/**
* User - The widget for displaying users from team.
*/
export class User extends NTextBox {
constructor(field: ViewFieldRec) {
super(field);
}

public buildDom(row: DataRowModel) {
const value = row.cells[this.field.colId()];

return cssUser(
cssUserIcon('FieldUser'),
dom.domComputed((use) => { return String(use(value)); })
);
}
}

const cssUser = styled('div.field_clip', ``);

const cssUserIcon = styled(icon, `
float: left;
--icon-color: ${theme.lightText};
margin: -1px 2px 2px 0;
`);
181 changes: 181 additions & 0 deletions app/client/widgets/UserEditor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
import {
ACIndexImpl,
ACItem,
ACResults,
buildHighlightedDom,
HighlightFunc,
normalizeText
} from 'app/client/lib/ACIndex';
import {Autocomplete} from 'app/client/lib/autocomplete';
import {theme, vars} from 'app/client/ui2018/cssVars';
import {menuCssClass} from 'app/client/ui2018/menus';
import {icon} from "app/client/ui2018/icons";
import {FieldOptions} from 'app/client/widgets/NewBaseEditor';
import {NTextEditor} from 'app/client/widgets/NTextEditor';
import {makeT} from 'app/client/lib/localization';
import {IToken} from 'app/client/lib/TokenField';
import {AppModel} from "app/client/models/AppModel";
import {UserAccessData} from "app/common/UserAPI";
import {undef} from 'app/common/gutil';
import {dom, Observable, styled} from 'grainjs';

const t = makeT('UserEditor');

export class UserItem implements ACItem, IToken {
public cleanText: string = normalizeText(this.label);
constructor(
public label: string,
public id: number
) {}
}

/**
* A UserEditor offers an autocomplete of choices from the users of team.
*/
export class UserEditor extends NTextEditor {
private _appModel: AppModel;
private _autocomplete?: Autocomplete<UserItem>;
private _dropdownConditionError = Observable.create<string | null>(this, null);
private _userList: UserItem[] = [];

constructor(options: FieldOptions) {
super(options);

this._appModel = options.gristDoc.appModel;

// Decorate the editor to look like a user column value (with a "user" icon).
// But not on readonly mode - here we will reuse default decoration
if (!options.readonly) {
this.cellEditorDiv.classList.add(cssUserEditor.className);
this.cellEditorDiv.appendChild(cssUserEditIcon('FieldUser'));
}

this.textInput.value = undef(options.state, options.editValue, this._idToText());

if (this._autocomplete) {
if (options.editValue === undefined) {
this._autocomplete.search((items) => items.findIndex((item) => item.label === options.cellValue));
} else {
this._autocomplete.search();
}
}
}

public async attach(cellElem: Element) {
super.attach(cellElem);
// don't create autocomplete for readonly mode
if (this.options.readonly) {
return;
}

try {
this._userList = (await this._appModel.api.getUsers()).map((user: UserAccessData) => ({
label: user.name || user.email,
cleanText: normalizeText(user.name || user.email),
id: user.id
}));
} catch (e) {
this._dropdownConditionError?.set(e);
}

this._autocomplete = this.autoDispose(new Autocomplete<UserItem>(this.textInput, {
menuCssClass: `${menuCssClass} ${cssUserList.className} test-autocomplete`,
buildNoItemsMessage: () => {
return dom.domComputed(use => {
const error = use(this._dropdownConditionError);
if (error) {
return t('Error in dropdown condition');
}

return t('No choices matching condition');
});
},
search: this._doSearch.bind(this),
renderItem: this._renderItem.bind(this),
getItemText: (item) => item.label,
onClick: () => this.options.commands.fieldEditSave(),
}));
}

public getCellValue() {
const selectedItem = this._autocomplete && this._autocomplete.getSelectedItem();

if (selectedItem) {
// Selected from the autocomplete dropdown.
return selectedItem.label;
} else if (normalizeText(this.textInput.value) === this._idToText()) {
// Unchanged from what's already in the cell.
return this.options.cellValue;
}

return super.getCellValue();
}

private _idToText() {
const value = this.options.cellValue;

if (typeof value === 'number') {
return this._userList.find((user) => value === user.id)?.label || '';
}

return String(value || '');
}

private async _doSearch(text: string): Promise<ACResults<UserItem>> {
const items = new ACIndexImpl(this._userList);

return items.search(text);
}

private _renderItem(item: UserItem, highlightFunc: HighlightFunc) {
return cssUserItem(
buildHighlightedDom(item.label, highlightFunc, cssMatchText)
);
}
}

const cssUserEditor = styled('div', `
& > .celleditor_text_editor, & > .celleditor_content_measure {
padding-left: 18px;
}
`);

const cssUserEditIcon = styled(icon, `
background-color: ${theme.lightText};
position: absolute;
top: 0;
left: 0;
margin: 3px 3px 0 3px;
`);

// Set z-index to be higher than the 1000 set for .cell_editor.
const cssUserList = styled('div', `
z-index: 1001;
overflow-y: auto;
padding: 8px 0 0 0;
--weaseljs-menu-item-padding: 8px 16px;
`);

const cssUserItem = styled('li', `
display: block;
font-family: ${vars.fontFamily};
white-space: pre;
overflow: hidden;
text-overflow: ellipsis;
outline: none;
padding: var(--weaseljs-menu-item-padding, 8px 24px);
cursor: pointer;
color: ${theme.menuItemFg};

&.selected {
background-color: ${theme.menuItemSelectedBg};
color: ${theme.menuItemSelectedFg};
}
`);

const cssMatchText = styled('span', `
color: ${theme.autocompleteMatchText};
.selected > & {
color: ${theme.autocompleteSelectedMatchText};
}
`);
16 changes: 16 additions & 0 deletions app/client/widgets/UserType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,5 +295,21 @@ export const typeDefs: any = {
}
},
default: 'Attachments'
},
User: {
label: 'User',
icon: 'FieldUser',
widgets: {
User: {
cons: 'User',
editCons: 'UserEditor',
icon: 'FieldUser',
options: {
alignment: 'left',
wrap: undefined
}
}
},
default: 'User'
}
};
4 changes: 4 additions & 0 deletions app/client/widgets/UserTypeImpl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import {ReferenceList} from 'app/client/widgets/ReferenceList';
import {ReferenceListEditor} from 'app/client/widgets/ReferenceListEditor';
import {Spinner} from 'app/client/widgets/Spinner';
import {ToggleCheckBox, ToggleSwitch} from 'app/client/widgets/Toggle';
import {User} from 'app/client/widgets/User';
import {UserEditor} from 'app/client/widgets/UserEditor';
import {getWidgetConfiguration} from 'app/client/widgets/UserType';
import {GristType} from 'app/plugin/GristData';

Expand Down Expand Up @@ -54,6 +56,8 @@ export const nameToWidget = {
'AttachmentsWidget': AttachmentsWidget,
'AttachmentsEditor': AttachmentsEditor,
'DateTimeEditor': DateTimeEditor,
'User': User,
'UserEditor': UserEditor
};


Expand Down
5 changes: 5 additions & 0 deletions app/common/UserAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,7 @@ export interface UserAPI {
updateWorkspacePermissions(workspaceId: number, delta: PermissionDelta): Promise<void>;
updateDocPermissions(docId: string, delta: PermissionDelta): Promise<void>;
getOrgAccess(orgId: number|string): Promise<PermissionData>;
getUsers(): Promise<UserAccessData[]>;
getWorkspaceAccess(workspaceId: number): Promise<PermissionData>;
getDocAccess(docId: string): Promise<PermissionData>;
pinDoc(docId: string): Promise<void>;
Expand Down Expand Up @@ -720,6 +721,10 @@ export class UserAPIImpl extends BaseAPI implements UserAPI {
return this.requestJson(`${this._url}/api/orgs/${orgId}/access`, { method: 'GET' });
}

public async getUsers(): Promise<UserAccessData[]> {
return this.requestJson(`${this._url}/api/users`, { method: 'GET' });
}

public async getWorkspaceAccess(workspaceId: number): Promise<PermissionData> {
return this.requestJson(`${this._url}/api/workspaces/${workspaceId}/access`, { method: 'GET' });
}
Expand Down
2 changes: 2 additions & 0 deletions app/common/gristTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ const _defaultValues: {[key in GristType]: [CellValue, string]} = {
'Ref': [ 0, "0" ],
'RefList': [ null, "NULL" ],
'Text': [ '', "''" ],
'User': [ '', "''" ],
};


Expand Down Expand Up @@ -210,6 +211,7 @@ const rightType: {[key in GristType]: (value: CellValue) => boolean} = {
RefList: isListOrNull,
Choice: isString,
ChoiceList: isListOrNull,
User: isString,
};

export function isRightType(type: string): undefined | ((value: CellValue, options?: any) => boolean) {
Expand Down
8 changes: 8 additions & 0 deletions app/gen-server/ApiServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -574,6 +574,14 @@ export class ApiServer {
});
}));

// GET /api/users
// Get all users.
this._app.get('/api/users', expressWrap(async (req, res) => {
const users = await this._dbManager.getUsers();

return sendReply(req, res, users);
}));
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if that would not be a security issue, considering that it would expose the list of every users of an instance (their name and their email), no matter what access to their information the requester have.

Copy link
Contributor Author

@florentinap florentinap Jun 14, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In my use case, I control all users in the instance, so there is no problem. You know more use cases, so you know if there is one that listing all users might be a security issue. Do you think it would be better to list only users who have access to the current site?


// DELETE /users/:uid
// Delete the specified user, their personal organization, removing them from all groups.
// Not available to the anonymous user.
Expand Down
Loading
Loading