hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
listlengths
5
5
{ "id": 10, "code_window": [ " >\n", " Variables\n", " </a>\n", " {this.props.idInEditor && (\n", " <span>\n", " <Icon\n", " name=\"angle-right\"\n", " aria-label={selectors.pages.Dashboard.Settings.Variables.Edit.General.modeLabelEdit}\n", " />\n", " Edit\n", " </span>\n", " )}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " <Icon name=\"angle-right\" />\n" ], "file_path": "public/app/features/variables/editor/VariableEditorContainer.tsx", "type": "replace", "edit_start_line_idx": 87 }
import { MetricsConfiguration } from '../../../types'; import { isMetricAggregationWithField, isPipelineAggregationWithMultipleBucketPaths, MetricAggregation, PipelineMetricAggregationType, } from './aggregations'; import { defaultPipelineVariable, generatePipelineVariableName, } from './SettingsEditor/BucketScriptSettingsEditor/utils'; export const metricAggregationConfig: MetricsConfiguration = { count: { label: 'Count', requiresField: false, isPipelineAgg: false, supportsMissing: false, supportsMultipleBucketPaths: false, hasSettings: false, hasMeta: false, supportsInlineScript: false, defaults: {}, }, avg: { label: 'Average', requiresField: true, supportsInlineScript: true, supportsMissing: true, isPipelineAgg: false, supportsMultipleBucketPaths: false, hasSettings: true, hasMeta: false, defaults: {}, }, sum: { label: 'Sum', requiresField: true, supportsInlineScript: true, supportsMissing: true, isPipelineAgg: false, supportsMultipleBucketPaths: false, hasSettings: true, hasMeta: false, defaults: {}, }, max: { label: 'Max', requiresField: true, supportsInlineScript: true, supportsMissing: true, isPipelineAgg: false, supportsMultipleBucketPaths: false, hasSettings: true, hasMeta: false, defaults: {}, }, min: { label: 'Min', requiresField: true, supportsInlineScript: true, supportsMissing: true, isPipelineAgg: false, supportsMultipleBucketPaths: false, hasSettings: true, hasMeta: false, defaults: {}, }, extended_stats: { label: 'Extended Stats', requiresField: true, supportsMissing: true, supportsInlineScript: true, isPipelineAgg: false, supportsMultipleBucketPaths: false, hasSettings: true, hasMeta: true, defaults: { meta: { std_deviation_bounds_lower: true, std_deviation_bounds_upper: true, }, }, }, percentiles: { label: 'Percentiles', requiresField: true, supportsMissing: true, supportsInlineScript: true, isPipelineAgg: false, supportsMultipleBucketPaths: false, hasSettings: true, hasMeta: false, defaults: { settings: { percents: ['25', '50', '75', '95', '99'], }, }, }, cardinality: { label: 'Unique Count', requiresField: true, supportsMissing: true, isPipelineAgg: false, supportsMultipleBucketPaths: false, hasSettings: true, supportsInlineScript: false, hasMeta: false, defaults: {}, }, moving_avg: { label: 'Moving Average', requiresField: true, isPipelineAgg: true, versionRange: '>=2.0.0', supportsMissing: false, supportsMultipleBucketPaths: false, hasSettings: true, supportsInlineScript: false, hasMeta: false, defaults: { settings: { model: 'simple', window: '5', }, }, }, moving_fn: { // TODO: Check this label: 'Moving Function', requiresField: true, isPipelineAgg: true, supportsMultipleBucketPaths: false, supportsInlineScript: false, supportsMissing: false, hasMeta: false, hasSettings: true, versionRange: '>=7.0.0', defaults: {}, }, derivative: { label: 'Derivative', requiresField: true, isPipelineAgg: true, versionRange: '>=2.0.0', supportsMissing: false, supportsMultipleBucketPaths: false, hasSettings: true, supportsInlineScript: false, hasMeta: false, defaults: {}, }, serial_diff: { label: 'Serial Difference', requiresField: true, isPipelineAgg: true, versionRange: '>=2.0.0', supportsMissing: false, supportsMultipleBucketPaths: false, hasSettings: true, supportsInlineScript: false, hasMeta: false, defaults: { settings: { lag: '1', }, }, }, cumulative_sum: { label: 'Cumulative Sum', requiresField: true, isPipelineAgg: true, versionRange: '>=2.0.0', supportsMissing: false, supportsMultipleBucketPaths: false, hasSettings: true, supportsInlineScript: false, hasMeta: false, defaults: {}, }, bucket_script: { label: 'Bucket Script', requiresField: false, isPipelineAgg: true, supportsMissing: false, supportsMultipleBucketPaths: true, versionRange: '>=2.0.0', hasSettings: true, supportsInlineScript: false, hasMeta: false, defaults: { pipelineVariables: [defaultPipelineVariable(generatePipelineVariableName([]))], }, }, raw_document: { label: 'Raw Document (legacy)', requiresField: false, isSingleMetric: true, isPipelineAgg: false, supportsMissing: false, supportsMultipleBucketPaths: false, hasSettings: true, supportsInlineScript: false, hasMeta: false, defaults: { settings: { size: '500', }, }, }, raw_data: { label: 'Raw Data', requiresField: false, isSingleMetric: true, isPipelineAgg: false, supportsMissing: false, supportsMultipleBucketPaths: false, hasSettings: true, supportsInlineScript: false, hasMeta: false, defaults: { settings: { size: '500', }, }, }, logs: { label: 'Logs', requiresField: false, isPipelineAgg: false, supportsMissing: false, supportsMultipleBucketPaths: false, hasSettings: true, isSingleMetric: true, supportsInlineScript: false, hasMeta: false, defaults: { settings: { limit: '500', }, }, }, top_metrics: { label: 'Top Metrics', xpack: true, requiresField: false, isPipelineAgg: false, supportsMissing: false, supportsMultipleBucketPaths: false, hasSettings: true, supportsInlineScript: false, versionRange: '>=7.7.0', hasMeta: false, defaults: { settings: { order: 'desc', }, }, }, rate: { label: 'Rate', xpack: true, versionRange: '>=7.10.0', requiresField: true, isPipelineAgg: false, supportsMissing: false, supportsMultipleBucketPaths: false, hasSettings: true, supportsInlineScript: true, hasMeta: false, defaults: {}, }, }; interface PipelineOption { label: string; default?: string | number | boolean; } type PipelineOptions = { [K in PipelineMetricAggregationType]: PipelineOption[]; }; export const pipelineOptions: PipelineOptions = { moving_avg: [ { label: 'window', default: 5 }, { label: 'model', default: 'simple' }, { label: 'predict' }, { label: 'minimize', default: false }, ], moving_fn: [{ label: 'window', default: 5 }, { label: 'script' }], derivative: [{ label: 'unit' }], serial_diff: [{ label: 'lag' }], cumulative_sum: [{ label: 'format' }], bucket_script: [], }; /** * Given a metric `MetricA` and an array of metrics, returns all children of `MetricA`. * `MetricB` is considered a child of `MetricA` if `MetricA` is referenced by `MetricB` in it's `field` attribute * (`MetricA.id === MetricB.field`) or in it's pipeline aggregation variables (for bucket_scripts). * @param metric * @param metrics */ export const getChildren = (metric: MetricAggregation, metrics: MetricAggregation[]): MetricAggregation[] => { const children = metrics.filter((m) => { // TODO: Check this. if (isPipelineAggregationWithMultipleBucketPaths(m)) { return m.pipelineVariables?.some((pv) => pv.pipelineAgg === metric.id); } return isMetricAggregationWithField(m) && metric.id === m.field; }); return [...children, ...children.flatMap((child) => getChildren(child, metrics))]; };
public/app/plugins/datasource/elasticsearch/components/QueryEditor/MetricAggregationsEditor/utils.ts
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0008921475382521749, 0.00019426282960921526, 0.00016239368414971977, 0.00017218988796230406, 0.00012539394083432853 ]
{ "id": 10, "code_window": [ " >\n", " Variables\n", " </a>\n", " {this.props.idInEditor && (\n", " <span>\n", " <Icon\n", " name=\"angle-right\"\n", " aria-label={selectors.pages.Dashboard.Settings.Variables.Edit.General.modeLabelEdit}\n", " />\n", " Edit\n", " </span>\n", " )}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " <Icon name=\"angle-right\" />\n" ], "file_path": "public/app/features/variables/editor/VariableEditorContainer.tsx", "type": "replace", "edit_start_line_idx": 87 }
import React, { createRef } from 'react'; import uPlot, { AlignedData, Options } from 'uplot'; import { DEFAULT_PLOT_CONFIG, pluginLog } from './utils'; import { PlotProps } from './types'; function sameDims(prevProps: PlotProps, nextProps: PlotProps) { return nextProps.width === prevProps.width && nextProps.height === prevProps.height; } function sameData(prevProps: PlotProps, nextProps: PlotProps) { return nextProps.data === prevProps.data; } function sameConfig(prevProps: PlotProps, nextProps: PlotProps) { return nextProps.config === prevProps.config; } function sameTimeRange(prevProps: PlotProps, nextProps: PlotProps) { let prevTime = prevProps.timeRange; let nextTime = nextProps.timeRange; return ( prevTime === nextTime || (nextTime.from.valueOf() === prevTime.from.valueOf() && nextTime.to.valueOf() === prevTime.to.valueOf()) ); } type UPlotChartState = { plot: uPlot | null; }; /** * @internal * uPlot abstraction responsible for plot initialisation, setup and refresh * Receives a data frame that is x-axis aligned, as of https://github.com/leeoniya/uPlot/tree/master/docs#data-format * Exposes context for uPlot instance access */ export class UPlotChart extends React.Component<PlotProps, UPlotChartState> { plotContainer = createRef<HTMLDivElement>(); plotCanvasBBox = createRef<DOMRect>(); constructor(props: PlotProps) { super(props); this.state = { plot: null, }; } reinitPlot() { let { width, height, plotRef } = this.props; this.state.plot?.destroy(); if (width === 0 && height === 0) { return; } this.props.config.addHook('setSize', (u) => { const canvas = u.over; if (!canvas) { return; } }); const config: Options = { ...DEFAULT_PLOT_CONFIG, width: this.props.width, height: this.props.height, ms: 1 as 1, ...this.props.config.getConfig(), }; pluginLog('UPlot', false, 'Reinitializing plot', config); const plot = new uPlot(config, this.props.data as AlignedData, this.plotContainer!.current!); if (plotRef) { plotRef(plot); } this.setState({ plot }); } componentDidMount() { this.reinitPlot(); } componentWillUnmount() { this.state.plot?.destroy(); } componentDidUpdate(prevProps: PlotProps) { let { plot } = this.state; if (!sameDims(prevProps, this.props)) { plot?.setSize({ width: this.props.width, height: this.props.height, }); } else if (!sameConfig(prevProps, this.props)) { this.reinitPlot(); } else if (!sameData(prevProps, this.props)) { plot?.setData(this.props.data as AlignedData); // this is a uPlot cache-busting hack for bar charts in case x axis labels changed // since the x scale's "range" doesnt change, the axis size doesnt get recomputed, which is where the tick labels are regenerated & cached // the more expensive, more proper/thorough way to do this is to force all axes to recalc: plot?.redraw(false, true); if (plot && typeof this.props.data[0]?.[0] === 'string') { //@ts-ignore plot.axes[0]._values = this.props.data[0]; } } else if (!sameTimeRange(prevProps, this.props)) { plot?.setScale('x', { min: this.props.timeRange.from.valueOf(), max: this.props.timeRange.to.valueOf(), }); } } render() { return ( <div style={{ position: 'relative' }}> <div ref={this.plotContainer} data-testid="uplot-main-div" /> {this.props.children} </div> ); } }
packages/grafana-ui/src/components/uPlot/Plot.tsx
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0003584432997740805, 0.00021610557450912893, 0.00016516352479811758, 0.00020563059661071748, 0.000057590132200857624 ]
{ "id": 11, "code_window": [ " width,\n", " labelWidth,\n", "}: PropsWithChildren<VariableSelectFieldProps<any>>): ReactElement {\n", " const styles = useStyles(getStyles);\n", "\n", " return (\n", " <>\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const inputId = `variable-select-input-${name}`;\n" ], "file_path": "public/app/features/variables/editor/VariableSelectField.tsx", "type": "add", "edit_start_line_idx": 27 }
import { Components } from './components'; /** * Selectors grouped/defined in Pages * * @alpha */ export const Pages = { Login: { url: '/login', username: 'Username input field', password: 'Password input field', submit: 'Login button', skip: 'Skip change password button', }, Home: { url: '/', }, DataSource: { name: 'Data source settings page name input field', delete: 'Data source settings page Delete button', readOnly: 'Data source settings page read only message', saveAndTest: 'Data source settings page Save and Test button', alert: 'Data source settings page Alert', }, DataSources: { url: '/datasources', dataSources: (dataSourceName: string) => `Data source list item ${dataSourceName}`, }, AddDataSource: { url: '/datasources/new', dataSourcePlugins: (pluginName: string) => `Data source plugin item ${pluginName}`, }, ConfirmModal: { delete: 'Confirm Modal Danger Button', }, AddDashboard: { url: '/dashboard/new', addNewPanel: 'Add new panel', addNewRow: 'Add new row', addNewPanelLibrary: 'Add new panel from panel library', }, Dashboard: { url: (uid: string) => `/d/${uid}`, DashNav: { nav: 'Dashboard navigation', }, SubMenu: { submenu: 'Dashboard submenu', submenuItem: 'data-testid template variable', submenuItemLabels: (item: string) => `data-testid Dashboard template variables submenu Label ${item}`, submenuItemValueDropDownValueLinkTexts: (item: string) => `data-testid Dashboard template variables Variable Value DropDown value link text ${item}`, submenuItemValueDropDownDropDown: 'Variable options', submenuItemValueDropDownOptionTexts: (item: string) => `data-testid Dashboard template variables Variable Value DropDown option text ${item}`, }, Settings: { General: { deleteDashBoard: 'Dashboard settings page delete dashboard button', sectionItems: (item: string) => `Dashboard settings section item ${item}`, saveDashBoard: 'Dashboard settings aside actions Save button', saveAsDashBoard: 'Dashboard settings aside actions Save As button', timezone: 'Time zone picker select container', title: 'Dashboard settings page title', }, Annotations: { List: { addAnnotationCTA: Components.CallToActionCard.button('Add annotation query'), }, Settings: { name: 'Annotations settings name input', }, }, Variables: { List: { addVariableCTA: Components.CallToActionCard.button('Add variable'), newButton: 'Variable editor New variable button', table: 'Variable editor Table', tableRowNameFields: (variableName: string) => `Variable editor Table Name field ${variableName}`, tableRowDefinitionFields: (variableName: string) => `Variable editor Table Definition field ${variableName}`, tableRowArrowUpButtons: (variableName: string) => `Variable editor Table ArrowUp button ${variableName}`, tableRowArrowDownButtons: (variableName: string) => `Variable editor Table ArrowDown button ${variableName}`, tableRowDuplicateButtons: (variableName: string) => `Variable editor Table Duplicate button ${variableName}`, tableRowRemoveButtons: (variableName: string) => `Variable editor Table Remove button ${variableName}`, }, Edit: { General: { headerLink: 'Variable editor Header link', modeLabelNew: 'Variable editor Header mode New', modeLabelEdit: 'Variable editor Header mode Edit', generalNameInput: 'Variable editor Form Name field', generalTypeSelect: 'Variable editor Form Type select', generalLabelInput: 'Variable editor Form Label field', generalHideSelect: 'Variable editor Form Hide select', selectionOptionsMultiSwitch: 'Variable editor Form Multi switch', selectionOptionsIncludeAllSwitch: 'Variable editor Form IncludeAll switch', selectionOptionsCustomAllInput: 'Variable editor Form IncludeAll field', previewOfValuesOption: 'Variable editor Preview of Values option', submitButton: 'Variable editor Submit button', }, QueryVariable: { queryOptionsDataSourceSelect: Components.DataSourcePicker.container, queryOptionsRefreshSelect: 'Variable editor Form Query Refresh select', queryOptionsRegExInput: 'Variable editor Form Query RegEx field', queryOptionsSortSelect: 'Variable editor Form Query Sort select', queryOptionsQueryInput: 'Variable editor Form Default Variable Query Editor textarea', valueGroupsTagsEnabledSwitch: 'Variable editor Form Query UseTags switch', valueGroupsTagsTagsQueryInput: 'Variable editor Form Query TagsQuery field', valueGroupsTagsTagsValuesQueryInput: 'Variable editor Form Query TagsValuesQuery field', }, ConstantVariable: { constantOptionsQueryInput: 'Variable editor Form Constant Query field', }, TextBoxVariable: { textBoxOptionsQueryInput: 'Variable editor Form TextBox Query field', }, }, }, }, }, Dashboards: { url: '/dashboards', dashboards: (title: string) => `Dashboard search item ${title}`, }, SaveDashboardAsModal: { newName: 'Save dashboard title field', save: 'Save dashboard button', }, SaveDashboardModal: { save: 'Dashboard settings Save Dashboard Modal Save button', saveVariables: 'Dashboard settings Save Dashboard Modal Save variables checkbox', saveTimerange: 'Dashboard settings Save Dashboard Modal Save timerange checkbox', }, SharePanelModal: { linkToRenderedImage: 'Link to rendered image', }, Explore: { url: '/explore', General: { container: 'data-testid Explore', graph: 'Explore Graph', table: 'Explore Table', scrollBar: () => '.scrollbar-view', }, Toolbar: { navBar: () => '.explore-toolbar', }, }, SoloPanel: { url: (page: string) => `/d-solo/${page}`, }, PluginsList: { page: 'Plugins list page', list: 'Plugins list', listItem: 'Plugins list item', signatureErrorNotice: 'Unsigned plugins notice', }, PluginPage: { page: 'Plugin page', signatureInfo: 'Plugin signature info', disabledInfo: 'Plugin disabled info', }, PlaylistForm: { name: 'Playlist name', interval: 'Playlist interval', itemRow: 'Playlist item row', itemIdType: 'Playlist item dashboard by ID type', itemTagType: 'Playlist item dashboard by Tag type', itemMoveUp: 'Move playlist item order up', itemMoveDown: 'Move playlist item order down', itemDelete: 'Delete playlist item', }, };
packages/grafana-e2e-selectors/src/selectors/pages.ts
1
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00017459658556617796, 0.00017141968419309705, 0.00016605414566583931, 0.00017184406169690192, 0.000002673661583685316 ]
{ "id": 11, "code_window": [ " width,\n", " labelWidth,\n", "}: PropsWithChildren<VariableSelectFieldProps<any>>): ReactElement {\n", " const styles = useStyles(getStyles);\n", "\n", " return (\n", " <>\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const inputId = `variable-select-input-${name}`;\n" ], "file_path": "public/app/features/variables/editor/VariableSelectField.tsx", "type": "add", "edit_start_line_idx": 27 }
package middleware import ( "path/filepath" "strings" "testing" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/infra/remotecache" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/auth" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/web" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestRecoveryMiddleware(t *testing.T) { t.Run("Given an API route that panics", func(t *testing.T) { apiURL := "/api/whatever" recoveryScenario(t, "recovery middleware should return JSON", apiURL, func(t *testing.T, sc *scenarioContext) { sc.handlerFunc = panicHandler sc.fakeReq("GET", apiURL).exec() sc.req.Header.Set("content-type", "application/json") assert.Equal(t, 500, sc.resp.Code) assert.Equal(t, "Internal Server Error - Check the Grafana server logs for the detailed error message.", sc.respJson["message"]) assert.True(t, strings.HasPrefix(sc.respJson["error"].(string), "Server Error")) }) }) t.Run("Given a non-API route that panics", func(t *testing.T) { apiURL := "/whatever" recoveryScenario(t, "recovery middleware should return html", apiURL, func(t *testing.T, sc *scenarioContext) { sc.handlerFunc = panicHandler sc.fakeReq("GET", apiURL).exec() assert.Equal(t, 500, sc.resp.Code) assert.Equal(t, "text/html; charset=UTF-8", sc.resp.Header().Get("content-type")) assert.Contains(t, sc.resp.Body.String(), "<title>Grafana - Error</title>") }) }) } func panicHandler(c *models.ReqContext) { panic("Handler has panicked") } func recoveryScenario(t *testing.T, desc string, url string, fn scenarioFunc) { t.Run(desc, func(t *testing.T) { defer bus.ClearBusHandlers() cfg := setting.NewCfg() cfg.ErrTemplateName = "error-template" sc := &scenarioContext{ t: t, url: url, cfg: cfg, } viewsPath, err := filepath.Abs("../../public/views") require.NoError(t, err) sc.m = web.New() sc.m.Use(Recovery(cfg)) sc.m.Use(AddDefaultResponseHeaders(cfg)) sc.m.UseMiddleware(web.Renderer(viewsPath, "[[", "]]")) sc.userAuthTokenService = auth.NewFakeUserAuthTokenService() sc.remoteCacheService = remotecache.NewFakeStore(t) contextHandler := getContextHandler(t, nil) sc.m.Use(contextHandler.Middleware) // mock out gc goroutine sc.m.Use(OrgRedirect(cfg)) sc.defaultHandler = func(c *models.ReqContext) { sc.context = c if sc.handlerFunc != nil { sc.handlerFunc(sc.context) } } sc.m.Get(url, sc.defaultHandler) fn(t, sc) }) }
pkg/middleware/recovery_test.go
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00017513531201984733, 0.00017152316286228597, 0.0001693033700576052, 0.00017178368580061942, 0.0000020289592157496372 ]
{ "id": 11, "code_window": [ " width,\n", " labelWidth,\n", "}: PropsWithChildren<VariableSelectFieldProps<any>>): ReactElement {\n", " const styles = useStyles(getStyles);\n", "\n", " return (\n", " <>\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const inputId = `variable-select-input-${name}`;\n" ], "file_path": "public/app/features/variables/editor/VariableSelectField.tsx", "type": "add", "edit_start_line_idx": 27 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Render should render component 1`] = ` <VerticalGroup> <FieldSet label="Team settings" > <Form defaultValues={ Object { "avatarUrl": "some/url/", "email": "[email protected]", "id": 1, "memberCount": 1, "name": "test", "permission": 0, } } onSubmit={[Function]} > <Component /> </Form> </FieldSet> <SharedPreferences resourceUri="teams/1" /> </VerticalGroup> `;
public/app/features/teams/__snapshots__/TeamSettings.test.tsx.snap
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0001745911140460521, 0.00017208435747306794, 0.0001697394618531689, 0.00017192248196806759, 0.0000019839833385049133 ]
{ "id": 11, "code_window": [ " width,\n", " labelWidth,\n", "}: PropsWithChildren<VariableSelectFieldProps<any>>): ReactElement {\n", " const styles = useStyles(getStyles);\n", "\n", " return (\n", " <>\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const inputId = `variable-select-input-${name}`;\n" ], "file_path": "public/app/features/variables/editor/VariableSelectField.tsx", "type": "add", "edit_start_line_idx": 27 }
import { Matcher, render, waitFor } from '@testing-library/react'; import { Provider } from 'react-redux'; import { BackendSrv, locationService, setBackendSrv, setDataSourceSrv } from '@grafana/runtime'; import { configureStore } from 'app/store/configureStore'; import RuleEditor from './RuleEditor'; import { Route, Router } from 'react-router-dom'; import React from 'react'; import { byLabelText, byRole, byTestId, byText } from 'testing-library-selector'; import { selectOptionInTest } from '@grafana/ui'; import { contextSrv } from 'app/core/services/context_srv'; import { mockDataSource, MockDataSourceSrv } from './mocks'; import userEvent from '@testing-library/user-event'; import { DataSourceInstanceSettings } from '@grafana/data'; import { typeAsJestMock } from 'test/helpers/typeAsJestMock'; import { getAllDataSources } from './utils/config'; import { fetchRulerRules, fetchRulerRulesGroup, fetchRulerRulesNamespace, setRulerRuleGroup } from './api/ruler'; import { DataSourceType, GRAFANA_RULES_SOURCE_NAME } from './utils/datasource'; import { DashboardSearchHit } from 'app/features/search/types'; import { getDefaultQueries } from './utils/rule-form'; import { ExpressionEditorProps } from './components/rule-editor/ExpressionEditor'; import * as api from 'app/features/manage-dashboards/state/actions'; import { GrafanaAlertStateDecision } from 'app/types/unified-alerting-dto'; jest.mock('./components/rule-editor/ExpressionEditor', () => ({ // eslint-disable-next-line react/display-name ExpressionEditor: ({ value, onChange }: ExpressionEditorProps) => ( <input value={value} data-testid="expr" onChange={(e) => onChange(e.target.value)} /> ), })); jest.mock('./api/ruler'); jest.mock('./utils/config'); // there's no angular scope in test and things go terribly wrong when trying to render the query editor row. // lets just skip it jest.mock('app/features/query/components/QueryEditorRow', () => ({ // eslint-disable-next-line react/display-name QueryEditorRow: () => <p>hi</p>, })); const mocks = { getAllDataSources: typeAsJestMock(getAllDataSources), api: { fetchRulerRulesGroup: typeAsJestMock(fetchRulerRulesGroup), setRulerRuleGroup: typeAsJestMock(setRulerRuleGroup), fetchRulerRulesNamespace: typeAsJestMock(fetchRulerRulesNamespace), fetchRulerRules: typeAsJestMock(fetchRulerRules), }, }; function renderRuleEditor(identifier?: string) { const store = configureStore(); locationService.push(identifier ? `/alerting/${identifier}/edit` : `/alerting/new`); return render( <Provider store={store}> <Router history={locationService.getHistory()}> <Route path={['/alerting/new', '/alerting/:id/edit']} component={RuleEditor} /> </Router> </Provider> ); } const ui = { inputs: { name: byLabelText('Rule name'), alertType: byTestId('alert-type-picker'), dataSource: byTestId('datasource-picker'), folder: byTestId('folder-picker'), namespace: byTestId('namespace-picker'), group: byTestId('group-picker'), annotationKey: (idx: number) => byTestId(`annotation-key-${idx}`), annotationValue: (idx: number) => byTestId(`annotation-value-${idx}`), labelKey: (idx: number) => byTestId(`label-key-${idx}`), labelValue: (idx: number) => byTestId(`label-value-${idx}`), expr: byTestId('expr'), }, buttons: { save: byRole('button', { name: 'Save' }), addAnnotation: byRole('button', { name: /Add info/ }), addLabel: byRole('button', { name: /Add label/ }), }, }; describe('RuleEditor', () => { beforeEach(() => { jest.resetAllMocks(); contextSrv.isEditor = true; }); it('can create a new cloud alert', async () => { const dataSources = { default: mockDataSource( { type: 'prometheus', name: 'Prom', isDefault: true, }, { alerting: true } ), }; setDataSourceSrv(new MockDataSourceSrv(dataSources)); mocks.getAllDataSources.mockReturnValue(Object.values(dataSources)); mocks.api.setRulerRuleGroup.mockResolvedValue(); mocks.api.fetchRulerRulesNamespace.mockResolvedValue([]); mocks.api.fetchRulerRulesGroup.mockResolvedValue({ name: 'group2', rules: [], }); mocks.api.fetchRulerRules.mockResolvedValue({ namespace1: [ { name: 'group1', rules: [], }, ], namespace2: [ { name: 'group2', rules: [], }, ], }); await renderRuleEditor(); await userEvent.type(await ui.inputs.name.find(), 'my great new rule'); await clickSelectOption(ui.inputs.alertType.get(), /Cortex\/Loki managed alert/); const dataSourceSelect = ui.inputs.dataSource.get(); userEvent.click(byRole('textbox').get(dataSourceSelect)); await clickSelectOption(dataSourceSelect, 'Prom (default)'); await waitFor(() => expect(mocks.api.fetchRulerRules).toHaveBeenCalled()); await clickSelectOption(ui.inputs.namespace.get(), 'namespace2'); await clickSelectOption(ui.inputs.group.get(), 'group2'); await userEvent.type(ui.inputs.expr.get(), 'up == 1'); await userEvent.type(ui.inputs.annotationValue(0).get(), 'some summary'); await userEvent.type(ui.inputs.annotationValue(1).get(), 'some description'); userEvent.click(ui.buttons.addLabel.get()); await userEvent.type(ui.inputs.labelKey(0).get(), 'severity'); await userEvent.type(ui.inputs.labelValue(0).get(), 'warn'); await userEvent.type(ui.inputs.labelKey(1).get(), 'team'); await userEvent.type(ui.inputs.labelValue(1).get(), 'the a-team'); // save and check what was sent to backend userEvent.click(ui.buttons.save.get()); await waitFor(() => expect(mocks.api.setRulerRuleGroup).toHaveBeenCalled()); expect(mocks.api.setRulerRuleGroup).toHaveBeenCalledWith('Prom', 'namespace2', { name: 'group2', rules: [ { alert: 'my great new rule', annotations: { description: 'some description', summary: 'some summary' }, labels: { severity: 'warn', team: 'the a-team' }, expr: 'up == 1', for: '1m', }, ], }); }); it('can create new grafana managed alert', async () => { const searchFolderMock = jest.spyOn(api, 'searchFolders').mockResolvedValue([ { title: 'Folder A', id: 1, }, { title: 'Folder B', id: 2, }, ] as DashboardSearchHit[]); const dataSources = { default: mockDataSource({ type: 'prometheus', name: 'Prom', isDefault: true, }), }; setDataSourceSrv(new MockDataSourceSrv(dataSources)); mocks.api.setRulerRuleGroup.mockResolvedValue(); mocks.api.fetchRulerRulesNamespace.mockResolvedValue([]); // fill out the form await renderRuleEditor(); userEvent.type(await ui.inputs.name.find(), 'my great new rule'); await clickSelectOption(ui.inputs.alertType.get(), /Classic Grafana alerts based on thresholds/); const folderInput = await ui.inputs.folder.find(); await waitFor(() => expect(searchFolderMock).toHaveBeenCalled()); await clickSelectOption(folderInput, 'Folder A'); await userEvent.type(ui.inputs.annotationValue(0).get(), 'some summary'); await userEvent.type(ui.inputs.annotationValue(1).get(), 'some description'); userEvent.click(ui.buttons.addLabel.get()); await userEvent.type(ui.inputs.labelKey(0).get(), 'severity'); await userEvent.type(ui.inputs.labelValue(0).get(), 'warn'); await userEvent.type(ui.inputs.labelKey(1).get(), 'team'); await userEvent.type(ui.inputs.labelValue(1).get(), 'the a-team'); // save and check what was sent to backend userEvent.click(ui.buttons.save.get()); await waitFor(() => expect(mocks.api.setRulerRuleGroup).toHaveBeenCalled()); expect(mocks.api.setRulerRuleGroup).toHaveBeenCalledWith(GRAFANA_RULES_SOURCE_NAME, 'Folder A', { interval: '1m', name: 'my great new rule', rules: [ { annotations: { description: 'some description', summary: 'some summary' }, labels: { severity: 'warn', team: 'the a-team' }, for: '5m', grafana_alert: { condition: 'B', data: getDefaultQueries(), exec_err_state: 'Alerting', no_data_state: 'NoData', title: 'my great new rule', }, }, ], }); }); it('can create a new cloud recording rule', async () => { const dataSources = { default: mockDataSource( { type: 'prometheus', name: 'Prom', isDefault: true, }, { alerting: true } ), }; setDataSourceSrv(new MockDataSourceSrv(dataSources)); mocks.getAllDataSources.mockReturnValue(Object.values(dataSources)); mocks.api.setRulerRuleGroup.mockResolvedValue(); mocks.api.fetchRulerRulesNamespace.mockResolvedValue([]); mocks.api.fetchRulerRulesGroup.mockResolvedValue({ name: 'group2', rules: [], }); mocks.api.fetchRulerRules.mockResolvedValue({ namespace1: [ { name: 'group1', rules: [], }, ], namespace2: [ { name: 'group2', rules: [], }, ], }); await renderRuleEditor(); await userEvent.type(await ui.inputs.name.find(), 'my great new recording rule'); await clickSelectOption(ui.inputs.alertType.get(), /Cortex\/Loki managed recording rule/); const dataSourceSelect = ui.inputs.dataSource.get(); userEvent.click(byRole('textbox').get(dataSourceSelect)); await clickSelectOption(dataSourceSelect, 'Prom (default)'); await waitFor(() => expect(mocks.api.fetchRulerRules).toHaveBeenCalled()); await clickSelectOption(ui.inputs.namespace.get(), 'namespace2'); await clickSelectOption(ui.inputs.group.get(), 'group2'); await userEvent.type(ui.inputs.expr.get(), 'up == 1'); userEvent.click(ui.buttons.addLabel.get()); await userEvent.type(ui.inputs.labelKey(1).get(), 'team'); await userEvent.type(ui.inputs.labelValue(1).get(), 'the a-team'); // try to save, find out that recording rule name is invalid userEvent.click(ui.buttons.save.get()); expect( await byText( 'Recording rule name must be valid metric name. It may only contain letters, numbers, and colons. It may not contain whitespace.' ).find() ).toBeInTheDocument(); expect(mocks.api.setRulerRuleGroup).not.toBeCalled(); // fix name and re-submit await userEvent.type(await ui.inputs.name.find(), '{selectall}{del}my:great:new:recording:rule'); userEvent.click(ui.buttons.save.get()); // save and check what was sent to backend userEvent.click(ui.buttons.save.get()); await waitFor(() => expect(mocks.api.setRulerRuleGroup).toHaveBeenCalled()); expect(mocks.api.setRulerRuleGroup).toHaveBeenCalledWith('Prom', 'namespace2', { name: 'group2', rules: [ { record: 'my:great:new:recording:rule', labels: { team: 'the a-team' }, expr: 'up == 1', }, ], }); }); it('can edit grafana managed rule', async () => { const uid = 'FOOBAR123'; const folder = { title: 'Folder A', uid: 'abcd', id: 1, }; const searchFolderMock = jest.spyOn(api, 'searchFolders').mockResolvedValue([folder] as DashboardSearchHit[]); const getFolderByUid = jest.fn().mockResolvedValue({ ...folder, canSave: true, }); const dataSources = { default: mockDataSource({ type: 'prometheus', name: 'Prom', isDefault: true, }), }; const backendSrv = ({ getFolderByUid, } as any) as BackendSrv; setBackendSrv(backendSrv); setDataSourceSrv(new MockDataSourceSrv(dataSources)); mocks.api.setRulerRuleGroup.mockResolvedValue(); mocks.api.fetchRulerRulesNamespace.mockResolvedValue([]); mocks.api.fetchRulerRules.mockResolvedValue({ [folder.title]: [ { interval: '1m', name: 'my great new rule', rules: [ { annotations: { description: 'some description', summary: 'some summary' }, labels: { severity: 'warn', team: 'the a-team' }, for: '5m', grafana_alert: { uid, namespace_uid: 'abcd', namespace_id: 1, condition: 'B', data: getDefaultQueries(), exec_err_state: GrafanaAlertStateDecision.Alerting, no_data_state: GrafanaAlertStateDecision.NoData, title: 'my great new rule', }, }, ], }, ], }); await renderRuleEditor(uid); await waitFor(() => expect(searchFolderMock).toHaveBeenCalled()); // check that it's filled in const nameInput = await ui.inputs.name.find(); expect(nameInput).toHaveValue('my great new rule'); expect(ui.inputs.folder.get()).toHaveTextContent(new RegExp(folder.title)); expect(ui.inputs.annotationValue(0).get()).toHaveValue('some description'); expect(ui.inputs.annotationValue(1).get()).toHaveValue('some summary'); // add an annotation await clickSelectOption(ui.inputs.annotationKey(2).get(), /Add new/); await userEvent.type(byRole('textbox').get(ui.inputs.annotationKey(2).get()), 'custom'); await userEvent.type(ui.inputs.annotationValue(2).get(), 'value'); //add a label await userEvent.type(ui.inputs.labelKey(2).get(), 'custom'); await userEvent.type(ui.inputs.labelValue(2).get(), 'value'); // save and check what was sent to backend userEvent.click(ui.buttons.save.get()); await waitFor(() => expect(mocks.api.setRulerRuleGroup).toHaveBeenCalled()); expect(mocks.api.setRulerRuleGroup).toHaveBeenCalledWith(GRAFANA_RULES_SOURCE_NAME, 'Folder A', { interval: '1m', name: 'my great new rule', rules: [ { annotations: { description: 'some description', summary: 'some summary', custom: 'value' }, labels: { severity: 'warn', team: 'the a-team', custom: 'value' }, for: '5m', grafana_alert: { uid, condition: 'B', data: getDefaultQueries(), exec_err_state: 'Alerting', no_data_state: 'NoData', title: 'my great new rule', }, }, ], }); }); it('for cloud alerts, should only allow to select editable rules sources', async () => { const dataSources: Record<string, DataSourceInstanceSettings<any>> = { // can edit rules loki: mockDataSource( { type: DataSourceType.Loki, name: 'loki with ruler', }, { alerting: true } ), loki_disabled: mockDataSource( { type: DataSourceType.Loki, name: 'loki disabled for alerting', jsonData: { manageAlerts: false, }, }, { alerting: true } ), // can edit rules prom: mockDataSource( { type: DataSourceType.Prometheus, name: 'cortex with ruler', }, { alerting: true } ), // cannot edit rules loki_local_rule_store: mockDataSource( { type: DataSourceType.Loki, name: 'loki with local rule store', }, { alerting: true } ), // cannot edit rules prom_no_ruler_api: mockDataSource( { type: DataSourceType.Loki, name: 'cortex without ruler api', }, { alerting: true } ), // not a supported datasource type splunk: mockDataSource( { type: 'splunk', name: 'splunk', }, { alerting: true } ), }; mocks.api.fetchRulerRulesGroup.mockImplementation(async (dataSourceName: string) => { if (dataSourceName === 'loki with ruler' || dataSourceName === 'cortex with ruler') { return null; } if (dataSourceName === 'loki with local rule store') { throw { status: 400, data: { message: 'GetRuleGroup unsupported in rule local store', }, }; } if (dataSourceName === 'cortex without ruler api') { throw new Error('404 from rules config endpoint. Perhaps ruler API is not enabled?'); } return null; }); setDataSourceSrv(new MockDataSourceSrv(dataSources)); mocks.getAllDataSources.mockReturnValue(Object.values(dataSources)); // render rule editor, select cortex/loki managed alerts await renderRuleEditor(); await ui.inputs.name.find(); await clickSelectOption(ui.inputs.alertType.get(), /Cortex\/Loki managed alert/); // wait for ui theck each datasource if it supports rule editing await waitFor(() => expect(mocks.api.fetchRulerRulesGroup).toHaveBeenCalledTimes(4)); // check that only rules sources that have ruler available are there const dataSourceSelect = ui.inputs.dataSource.get(); userEvent.click(byRole('textbox').get(dataSourceSelect)); expect(await byText('loki with ruler').query()).toBeInTheDocument(); expect(byText('cortex with ruler').query()).toBeInTheDocument(); expect(byText('loki with local rule store').query()).not.toBeInTheDocument(); expect(byText('prom without ruler api').query()).not.toBeInTheDocument(); expect(byText('splunk').query()).not.toBeInTheDocument(); expect(byText('loki disabled for alerting').query()).not.toBeInTheDocument(); }); }); const clickSelectOption = async (selectElement: HTMLElement, optionText: Matcher): Promise<void> => { userEvent.click(byRole('textbox').get(selectElement)); await selectOptionInTest(selectElement, optionText as string); };
public/app/features/alerting/unified/RuleEditor.test.tsx
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.000176030007423833, 0.00017231931269634515, 0.00016791079542599618, 0.00017269107047468424, 0.0000019659196368593257 ]
{ "id": 12, "code_window": [ "\n", " return (\n", " <>\n", " <InlineFormLabel width={labelWidth ?? 6} tooltip={tooltip}>\n", " {name}\n", " </InlineFormLabel>\n", " <div aria-label={ariaLabel}>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <InlineFormLabel width={labelWidth ?? 6} tooltip={tooltip} htmlFor={inputId}>\n" ], "file_path": "public/app/features/variables/editor/VariableSelectField.tsx", "type": "replace", "edit_start_line_idx": 30 }
import React, { useState } from 'react'; import { Checkbox, CollapsableSection, ColorValueEditor, Field, HorizontalGroup, Input } from '@grafana/ui'; import { DashboardModel } from '../../state/DashboardModel'; import { AnnotationQuery, DataSourceInstanceSettings } from '@grafana/data'; import { getDataSourceSrv, DataSourcePicker } from '@grafana/runtime'; import { useAsync } from 'react-use'; import StandardAnnotationQueryEditor from 'app/features/annotations/components/StandardAnnotationQueryEditor'; import { AngularEditorLoader } from './AngularEditorLoader'; import { selectors } from '@grafana/e2e-selectors'; export const newAnnotation: AnnotationQuery = { name: 'New annotation', enable: true, datasource: null, iconColor: 'red', }; type Props = { editIdx: number; dashboard: DashboardModel; }; export const AnnotationSettingsEdit: React.FC<Props> = ({ editIdx, dashboard }) => { const [annotation, setAnnotation] = useState(editIdx !== null ? dashboard.annotations.list[editIdx] : newAnnotation); const { value: ds } = useAsync(() => { return getDataSourceSrv().get(annotation.datasource); }, [annotation.datasource]); const onUpdate = (annotation: AnnotationQuery) => { const list = [...dashboard.annotations.list]; list.splice(editIdx, 1, annotation); setAnnotation(annotation); dashboard.annotations.list = list; }; const onNameChange = (ev: React.FocusEvent<HTMLInputElement>) => { onUpdate({ ...annotation, name: ev.currentTarget.value, }); }; const onDataSourceChange = (ds: DataSourceInstanceSettings) => { onUpdate({ ...annotation, datasource: ds.name, }); }; const onChange = (ev: React.FocusEvent<HTMLInputElement>) => { const target = ev.currentTarget; onUpdate({ ...annotation, [target.name]: target.type === 'checkbox' ? target.checked : target.value, }); }; const onColorChange = (color: string) => { onUpdate({ ...annotation, iconColor: color, }); }; const isNewAnnotation = annotation.name === newAnnotation.name; return ( <div> <Field label="Name"> <Input aria-label={selectors.pages.Dashboard.Settings.Annotations.Settings.name} name="name" id="name" autoFocus={isNewAnnotation} value={annotation.name} onChange={onNameChange} width={50} /> </Field> <Field label="Data source"> <DataSourcePicker width={50} annotations variables current={annotation.datasource} onChange={onDataSourceChange} /> </Field> <Field label="Enabled" description="When enabled the annotation query is issued every dashboard refresh"> <Checkbox name="enable" id="enable" value={annotation.enable} onChange={onChange} /> </Field> <Field label="Hidden" description="Annotation queries can be toggled on or off at the top of the dashboard. With this option checked this toggle will be hidden." > <Checkbox name="hide" id="hide" value={annotation.hide} onChange={onChange} /> </Field> <Field label="Color" description="Color to use for the annotation event markers"> <HorizontalGroup> <ColorValueEditor value={annotation?.iconColor} onChange={onColorChange} /> </HorizontalGroup> </Field> <CollapsableSection isOpen={true} label="Query"> {ds?.annotations && ( <StandardAnnotationQueryEditor datasource={ds} annotation={annotation} onChange={onUpdate} /> )} {ds && !ds.annotations && <AngularEditorLoader datasource={ds} annotation={annotation} onChange={onUpdate} />} </CollapsableSection> </div> ); }; AnnotationSettingsEdit.displayName = 'AnnotationSettingsEdit';
public/app/features/dashboard/components/AnnotationSettings/AnnotationSettingsEdit.tsx
1
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00017429669969715178, 0.0001703704911051318, 0.00016523897647857666, 0.0001714598765829578, 0.000003607050757636898 ]
{ "id": 12, "code_window": [ "\n", " return (\n", " <>\n", " <InlineFormLabel width={labelWidth ?? 6} tooltip={tooltip}>\n", " {name}\n", " </InlineFormLabel>\n", " <div aria-label={ariaLabel}>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <InlineFormLabel width={labelWidth ?? 6} tooltip={tooltip} htmlFor={inputId}>\n" ], "file_path": "public/app/features/variables/editor/VariableSelectField.tsx", "type": "replace", "edit_start_line_idx": 30 }
[grafana] name=grafana baseurl=https://packages.grafana.com/enterprise/rpm repo_gpgcheck=1 enabled=1 gpgcheck=1 gpgkey=https://packages.grafana.com/gpg.key sslverify=1 sslcacert=/etc/pki/tls/certs/ca-bundle.crt
scripts/verify-repo-update/rpm-ee-stable.list
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00017108030442614108, 0.00017108030442614108, 0.00017108030442614108, 0.00017108030442614108, 0 ]
{ "id": 12, "code_window": [ "\n", " return (\n", " <>\n", " <InlineFormLabel width={labelWidth ?? 6} tooltip={tooltip}>\n", " {name}\n", " </InlineFormLabel>\n", " <div aria-label={ariaLabel}>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <InlineFormLabel width={labelWidth ?? 6} tooltip={tooltip} htmlFor={inputId}>\n" ], "file_path": "public/app/features/variables/editor/VariableSelectField.tsx", "type": "replace", "edit_start_line_idx": 30 }
import { XYCanvas } from './XYCanvas'; import { Marker } from './Marker'; import { EventsCanvas } from './EventsCanvas'; export { XYCanvas, Marker, EventsCanvas };
packages/grafana-ui/src/components/uPlot/geometries/index.ts
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00017748416576068848, 0.00017748416576068848, 0.00017748416576068848, 0.00017748416576068848, 0 ]
{ "id": 12, "code_window": [ "\n", " return (\n", " <>\n", " <InlineFormLabel width={labelWidth ?? 6} tooltip={tooltip}>\n", " {name}\n", " </InlineFormLabel>\n", " <div aria-label={ariaLabel}>\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <InlineFormLabel width={labelWidth ?? 6} tooltip={tooltip} htmlFor={inputId}>\n" ], "file_path": "public/app/features/variables/editor/VariableSelectField.tsx", "type": "replace", "edit_start_line_idx": 30 }
# Services A Grafana _service_ encapsulates and exposes application logic to the rest of the application, through a set of related operations. Grafana uses [Wire](https://github.com/google/wire), which is a code generation tool that automates connecting components using [dependency injection](https://en.wikipedia.org/wiki/Dependency_injection). Dependencies between components are represented in Wire as function parameters, encouraging explicit initialization instead of global variables. Even though the services in Grafana do different things, they share a number of patterns. To better understand how a service works, let's build one from scratch! Before a service can start communicating with the rest of Grafana, it needs to be registered with Wire, see `ProvideService` factory function/method in the service example below and how it's being referenced in the wire.go example below. When Wire is run it will inspect the parameters of `ProvideService` and make sure that all it's dependencies has been wired up and initialized properly. **Service example:** ```go package example // Service service is the service responsible for X, Y and Z. type Service struct { logger log.Logger cfg *setting.Cfg sqlStore *sqlstore.SQLStore } // ProvideService provides Service as dependency for other services. func ProvideService(cfg *setting.Cfg, sqlStore *sqlstore.SQLStore) (*Service, error) { s := &Service{ logger: log.New("service"), cfg: cfg, sqlStore: sqlStore, } if s.IsDisabled() { // skip certain initialization logic return s, nil } if err := s.init(); err != nil { return nil, err } return s, nil } func (s *Service) init() error { // additional initialization logic... return nil } // IsDisabled returns true if the service is disabled. // // Satisfies the registry.CanBeDisabled interface which will guarantee // that Run() is not called if the service is disabled. func (s *Service) IsDisabled() bool { return !s.cfg.IsServiceEnabled() } // Run runs the service in the background. // // Satisfies the registry.BackgroundService interface which will // guarantee that the service can be registered as a background service. func (s *Service) Run(ctx context.Context) error { // background service logic... <-ctx.Done() return ctx.Err() } ``` [wire.go](/pkg/server/wire.go) ```go // +build wireinject package server import ( "github.com/google/wire" "github.com/grafana/grafana/pkg/example" "github.com/grafana/grafana/pkg/services/sqlstore" ) var wireBasicSet = wire.NewSet( example.ProvideService, ) var wireSet = wire.NewSet( wireBasicSet, sqlstore.ProvideService, ) var wireTestSet = wire.NewSet( wireBasicSet, ) func Initialize(cla setting.CommandLineArgs, opts Options, apiOpts api.ServerOptions) (*Server, error) { wire.Build(wireExtsSet) return &Server{}, nil } func InitializeForTest(cla setting.CommandLineArgs, opts Options, apiOpts api.ServerOptions, sqlStore *sqlstore.SQLStore) (*Server, error) { wire.Build(wireExtsTestSet) return &Server{}, nil } ``` ## Background services A background service is a service that runs in the background of the lifecycle between Grafana starts up and shutdown. If you want a service to be run in the background your Service should satisfy the `registry.BackgroundService` interface and add it as argument to the [ProvideBackgroundServiceRegistry](/pkg/server/backgroundsvcs/background_services.go) function and add it as argument to `NewBackgroundServiceRegistry` to register it as a background service. You can see an example implementation above of the Run method. ## Disabled services If you want to guarantee that a background service is not run by Grafana when certain criteria is met/service is disabled your service should satisfy the `registry.CanBeDisabled` interface. When the service.IsDisabled method return false Grafana would not call the service.Run method. If you want to run certain initialization code if service is disabled or not, you need to handle this in the service factory method. You can see an example implementation above of the IsDisabled method and custom initialization code when service is disabled. ## Run Wire / generate code When running `make run` it will call `make gen-go` on the first run. `gen-go` in turn will call the wire binary and generate the code in [wire_gen.go](/pkg/server/wire_gen.go). The wire binary is installed using [bingo](https://github.com/bwplotka/bingo) which will make sure to download and install all the tools needed, including the Wire binary at using a specific version. ## OSS vs Enterprise Grafana OSS and Grafana Enterprise shares code and dependencies. Grafana Enterprise might need to override/extend certain OSS services. There's a [wireexts_oss.go](/pkg/server/wireexts_oss.go) that has the `wireinject` and `oss` build tags as requirements. Here services that might have other implementations, e.g. Grafana Enterprise, can be registered. Similarly, there's a wireexts_enterprise.go file in the Enterprise source code repository where other service implementations can be overridden/be registered. To extend oss background service create a specific background interface for that type and inject that type to [ProvideBackgroundServiceRegistry](/pkg/server/backgroundsvcs/background_services.go) instead of the concrete type. Then add a wire binding for that interface in [wireexts_oss.go](/pkg/server/wireexts_oss.go) and in the enterprise wireexts file. ## Methods Any public method of a service should take `context.Context` as its first argument. If the method calls the bus, other services or the database the context should be propagated, if possible.
contribute/architecture/backend/services.md
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0001740985462674871, 0.0001671718928264454, 0.00016158848302438855, 0.0001665082818362862, 0.000003861273853544844 ]
{ "id": 13, "code_window": [ " {name}\n", " </InlineFormLabel>\n", " <div aria-label={ariaLabel}>\n", " <Select\n", " menuShouldPortal\n", " onChange={onChange}\n", " value={value}\n", " width={width ?? 25}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " inputId={inputId}\n" ], "file_path": "public/app/features/variables/editor/VariableSelectField.tsx", "type": "add", "edit_start_line_idx": 35 }
import React, { PropsWithChildren, ReactElement } from 'react'; import { InlineFormLabel, Select, useStyles } from '@grafana/ui'; import { GrafanaTheme, SelectableValue } from '@grafana/data'; import { css } from '@emotion/css'; interface VariableSelectFieldProps<T> { name: string; value: SelectableValue<T>; options: Array<SelectableValue<T>>; onChange: (option: SelectableValue<T>) => void; tooltip?: string; ariaLabel?: string; width?: number; labelWidth?: number; } export function VariableSelectField({ name, value, options, tooltip, onChange, ariaLabel, width, labelWidth, }: PropsWithChildren<VariableSelectFieldProps<any>>): ReactElement { const styles = useStyles(getStyles); return ( <> <InlineFormLabel width={labelWidth ?? 6} tooltip={tooltip}> {name} </InlineFormLabel> <div aria-label={ariaLabel}> <Select menuShouldPortal onChange={onChange} value={value} width={width ?? 25} options={options} className={styles.selectContainer} /> </div> </> ); } function getStyles(theme: GrafanaTheme) { return { selectContainer: css` margin-right: ${theme.spacing.xs}; `, }; }
public/app/features/variables/editor/VariableSelectField.tsx
1
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.9922913908958435, 0.1673445850610733, 0.00016557729395572096, 0.0013806055067107081, 0.3689391016960144 ]
{ "id": 13, "code_window": [ " {name}\n", " </InlineFormLabel>\n", " <div aria-label={ariaLabel}>\n", " <Select\n", " menuShouldPortal\n", " onChange={onChange}\n", " value={value}\n", " width={width ?? 25}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " inputId={inputId}\n" ], "file_path": "public/app/features/variables/editor/VariableSelectField.tsx", "type": "add", "edit_start_line_idx": 35 }
package pipeline import ( "context" "errors" "fmt" "os" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana-plugin-sdk-go/data" "github.com/grafana/grafana-plugin-sdk-go/live" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/exporters/jaeger" "go.opentelemetry.io/otel/sdk/resource" tracesdk "go.opentelemetry.io/otel/sdk/trace" semconv "go.opentelemetry.io/otel/semconv/v1.4.0" "go.opentelemetry.io/otel/trace" ) const ( service = "grafana" environment = "dev" id = 1 ) // tracerProvider returns an OpenTelemetry TracerProvider configured to use // the Jaeger exporter that will send spans to the provided url. The returned // TracerProvider will also use a Resource configured with all the information // about the application. func tracerProvider(url string) (*tracesdk.TracerProvider, error) { // Create the Jaeger exporter exp, err := jaeger.New(jaeger.WithCollectorEndpoint(jaeger.WithEndpoint(url))) if err != nil { return nil, err } tp := tracesdk.NewTracerProvider( // Always be sure to batch in production. tracesdk.WithBatcher(exp), // Record information about this application in an Resource. tracesdk.WithResource(resource.NewWithAttributes( semconv.SchemaURL, semconv.ServiceNameKey.String(service), attribute.String("environment", environment), attribute.Int64("ID", id), )), ) return tp, nil } // ChannelData is a wrapper over raw data with additional channel information. // Channel is used for rule routing, if the channel is empty then data processing // stops. If channel is not empty then data processing will be redirected to a // corresponding channel rule. type ChannelData struct { Channel string Data []byte } // ChannelFrame is a wrapper over data.Frame with additional channel information. // Channel is used for rule routing, if the channel is empty then frame processing // will try to take current rule FrameProcessor and FrameOutputter. If channel is not empty // then frame processing will be redirected to a corresponding channel rule. type ChannelFrame struct { Channel string `json:"channel"` Frame *data.Frame `json:"frame"` } // Vars has some helpful things pipeline entities could use. type Vars struct { OrgID int64 Channel string Scope string Namespace string Path string } // DataOutputter can output incoming data before conversion to frames. type DataOutputter interface { Type() string OutputData(ctx context.Context, vars Vars, data []byte) ([]*ChannelData, error) } // Converter converts raw bytes to slice of ChannelFrame. Each element // of resulting slice will be then individually processed and outputted // according configured channel rules. type Converter interface { Type() string Convert(ctx context.Context, vars Vars, body []byte) ([]*ChannelFrame, error) } // FrameProcessor can modify data.Frame in a custom way before it will be outputted. type FrameProcessor interface { Type() string ProcessFrame(ctx context.Context, vars Vars, frame *data.Frame) (*data.Frame, error) } // FrameOutputter outputs data.Frame to a custom destination. Or simply // do nothing if some conditions not met. type FrameOutputter interface { Type() string OutputFrame(ctx context.Context, vars Vars, frame *data.Frame) ([]*ChannelFrame, error) } // Subscriber can handle channel subscribe events. type Subscriber interface { Type() string Subscribe(ctx context.Context, vars Vars) (models.SubscribeReply, backend.SubscribeStreamStatus, error) } // PublishAuthChecker checks whether current user can publish to a channel. type PublishAuthChecker interface { CanPublish(ctx context.Context, u *models.SignedInUser) (bool, error) } // SubscribeAuthChecker checks whether current user can subscribe to a channel. type SubscribeAuthChecker interface { CanSubscribe(ctx context.Context, u *models.SignedInUser) (bool, error) } // LiveChannelRule is an in-memory representation of each specific rule, with Converter, FrameProcessor // and FrameOutputter to be executed by Pipeline. type LiveChannelRule struct { OrgId int64 Pattern string PublishAuth PublishAuthChecker SubscribeAuth SubscribeAuthChecker Subscribers []Subscriber DataOutputters []DataOutputter Converter Converter FrameProcessors []FrameProcessor FrameOutputters []FrameOutputter } // Label ... type Label struct { Name string `json:"name"` Value string `json:"value"` // Can be JSONPath or Goja script. } // Field description. type Field struct { Name string `json:"name"` Type data.FieldType `json:"type"` Value string `json:"value"` // Can be JSONPath or Goja script. Labels []Label `json:"labels,omitempty"` Config *data.FieldConfig `json:"config,omitempty"` } type ChannelRuleGetter interface { Get(orgID int64, channel string) (*LiveChannelRule, bool, error) } // Pipeline allows processing custom input data according to user-defined rules. // This includes: // * transforming custom input to data.Frame objects // * do some processing on these frames // * output resulting frames to various destinations. type Pipeline struct { ruleGetter ChannelRuleGetter tracer trace.Tracer } // New creates new Pipeline. func New(ruleGetter ChannelRuleGetter) (*Pipeline, error) { p := &Pipeline{ ruleGetter: ruleGetter, } if os.Getenv("GF_LIVE_PIPELINE_TRACE") != "" { // Traces for development only at the moment. // Start local Jaeger and then run Grafana with GF_LIVE_PIPELINE_TRACE: // docker run --rm -it --name jaeger -e COLLECTOR_ZIPKIN_HOST_PORT=:9411 -p 5775:5775/udp -p 6831:6831/udp -p 6832:6832/udp -p 5778:5778 -p 16686:16686 -p 14268:14268 -p 14250:14250 -p 9411:9411 jaegertracing/all-in-one:1.26 // Then visit http://localhost:16686/ where Jaeger UI is served. tp, err := tracerProvider("http://localhost:14268/api/traces") if err != nil { return nil, err } tracer := tp.Tracer("gf.live.pipeline") p.tracer = tracer } if os.Getenv("GF_LIVE_PIPELINE_DEV") != "" { go postTestData() // TODO: temporary for development, remove before merge. } return p, nil } func (p *Pipeline) Get(orgID int64, channel string) (*LiveChannelRule, bool, error) { return p.ruleGetter.Get(orgID, channel) } func (p *Pipeline) ProcessInput(ctx context.Context, orgID int64, channelID string, body []byte) (bool, error) { var span trace.Span if p.tracer != nil { ctx, span = p.tracer.Start(ctx, "live.pipeline.process_input") span.SetAttributes( attribute.Int64("orgId", orgID), attribute.String("channel", channelID), attribute.String("body", string(body)), ) defer span.End() } ok, err := p.processInput(ctx, orgID, channelID, body, nil) if err != nil { if p.tracer != nil && span != nil { span.SetStatus(codes.Error, err.Error()) } return ok, err } return ok, err } func (p *Pipeline) processInput(ctx context.Context, orgID int64, channelID string, body []byte, visitedChannels map[string]struct{}) (bool, error) { var span trace.Span if p.tracer != nil { ctx, span = p.tracer.Start(ctx, "live.pipeline.process_input_"+channelID) span.SetAttributes( attribute.Int64("orgId", orgID), attribute.String("channel", channelID), attribute.String("body", string(body)), ) defer span.End() } rule, ok, err := p.ruleGetter.Get(orgID, channelID) if err != nil { return false, err } if !ok { return false, nil } if visitedChannels == nil { visitedChannels = map[string]struct{}{} } if len(rule.DataOutputters) > 0 { channelDataList := []*ChannelData{{Channel: channelID, Data: body}} err = p.processChannelDataList(ctx, orgID, channelID, channelDataList, visitedChannels) if err != nil { return false, err } } if rule.Converter == nil { return false, nil } channelFrames, err := p.DataToChannelFrames(ctx, *rule, orgID, channelID, body) if err != nil { return false, err } err = p.processChannelFrames(ctx, orgID, channelID, channelFrames, nil) if err != nil { return false, fmt.Errorf("error processing frame: %w", err) } return true, nil } func (p *Pipeline) DataToChannelFrames(ctx context.Context, rule LiveChannelRule, orgID int64, channelID string, body []byte) ([]*ChannelFrame, error) { var span trace.Span if p.tracer != nil { ctx, span = p.tracer.Start(ctx, "live.pipeline.convert_"+rule.Converter.Type()) span.SetAttributes( attribute.Int64("orgId", orgID), attribute.String("channel", channelID), ) defer span.End() } channel, err := live.ParseChannel(channelID) if err != nil { logger.Error("Error parsing channel", "error", err, "channel", channelID) return nil, err } vars := Vars{ OrgID: orgID, Channel: channelID, Scope: channel.Scope, Namespace: channel.Namespace, Path: channel.Path, } frames, err := rule.Converter.Convert(ctx, vars, body) if err != nil { logger.Error("Error converting data", "error", err) return nil, err } return frames, nil } var errChannelRecursion = errors.New("channel recursion") func (p *Pipeline) processChannelDataList(ctx context.Context, orgID int64, channelID string, channelDataList []*ChannelData, visitedChannels map[string]struct{}) error { for _, channelData := range channelDataList { var nextChannel = channelID if channelData.Channel != "" { nextChannel = channelData.Channel } if _, ok := visitedChannels[nextChannel]; ok { return fmt.Errorf("%w: %s", errChannelRecursion, nextChannel) } visitedChannels[nextChannel] = struct{}{} newChannelDataList, err := p.processData(ctx, orgID, nextChannel, channelData.Data) if err != nil { return err } if len(newChannelDataList) > 0 { for _, cd := range newChannelDataList { _, err := p.processInput(ctx, orgID, cd.Channel, cd.Data, visitedChannels) if err != nil { return err } } } } return nil } func (p *Pipeline) processChannelFrames(ctx context.Context, orgID int64, channelID string, channelFrames []*ChannelFrame, visitedChannels map[string]struct{}) error { if visitedChannels == nil { visitedChannels = map[string]struct{}{} } for _, channelFrame := range channelFrames { var processorChannel = channelID if channelFrame.Channel != "" { processorChannel = channelFrame.Channel } if _, ok := visitedChannels[processorChannel]; ok { return fmt.Errorf("%w: %s", errChannelRecursion, processorChannel) } visitedChannels[processorChannel] = struct{}{} frames, err := p.processFrame(ctx, orgID, processorChannel, channelFrame.Frame) if err != nil { return err } if len(frames) > 0 { err := p.processChannelFrames(ctx, orgID, processorChannel, frames, visitedChannels) if err != nil { return err } } } return nil } func (p *Pipeline) processFrame(ctx context.Context, orgID int64, channelID string, frame *data.Frame) ([]*ChannelFrame, error) { var span trace.Span if p.tracer != nil { table, err := frame.StringTable(32, 32) if err != nil { return nil, err } ctx, span = p.tracer.Start(ctx, "live.pipeline.process_frame_"+channelID) span.SetAttributes( attribute.Int64("orgId", orgID), attribute.String("channel", channelID), attribute.String("frame", table), ) defer span.End() } rule, ruleOk, err := p.ruleGetter.Get(orgID, channelID) if err != nil { logger.Error("Error getting rule", "error", err) return nil, err } if !ruleOk { logger.Debug("Rule not found", "channel", channelID) return nil, err } ch, err := live.ParseChannel(channelID) if err != nil { logger.Error("Error parsing channel", "error", err, "channel", channelID) return nil, err } vars := Vars{ OrgID: orgID, Channel: channelID, Scope: ch.Scope, Namespace: ch.Namespace, Path: ch.Path, } if len(rule.FrameProcessors) > 0 { for _, proc := range rule.FrameProcessors { frame, err = p.execProcessor(ctx, proc, vars, frame) if err != nil { logger.Error("Error processing frame", "error", err) return nil, err } if frame == nil { return nil, nil } } } if len(rule.FrameOutputters) > 0 { var resultingFrames []*ChannelFrame for _, out := range rule.FrameOutputters { frames, err := p.processFrameOutput(ctx, out, vars, frame) if err != nil { logger.Error("Error outputting frame", "error", err) return nil, err } resultingFrames = append(resultingFrames, frames...) } return resultingFrames, nil } return nil, nil } func (p *Pipeline) execProcessor(ctx context.Context, proc FrameProcessor, vars Vars, frame *data.Frame) (*data.Frame, error) { var span trace.Span if p.tracer != nil { ctx, span = p.tracer.Start(ctx, "live.pipeline.apply_processor_"+proc.Type()) table, err := frame.StringTable(32, 32) if err != nil { return nil, err } span.SetAttributes( attribute.Int64("orgId", vars.OrgID), attribute.String("channel", vars.Channel), attribute.String("frame", table), attribute.String("processor", proc.Type()), ) // Note: we can also visualize resulting frame here. defer span.End() } return proc.ProcessFrame(ctx, vars, frame) } func (p *Pipeline) processFrameOutput(ctx context.Context, out FrameOutputter, vars Vars, frame *data.Frame) ([]*ChannelFrame, error) { var span trace.Span if p.tracer != nil { ctx, span = p.tracer.Start(ctx, "live.pipeline.frame_output_"+out.Type()) table, err := frame.StringTable(32, 32) if err != nil { return nil, err } span.SetAttributes( attribute.Int64("orgId", vars.OrgID), attribute.String("channel", vars.Channel), attribute.String("frame", table), attribute.String("output", out.Type()), ) defer span.End() } return out.OutputFrame(ctx, vars, frame) } func (p *Pipeline) processData(ctx context.Context, orgID int64, channelID string, data []byte) ([]*ChannelData, error) { var span trace.Span if p.tracer != nil { ctx, span = p.tracer.Start(ctx, "live.pipeline.process_data_"+channelID) span.SetAttributes( attribute.Int64("orgId", orgID), attribute.String("channel", channelID), attribute.String("data", string(data)), ) defer span.End() } rule, ruleOk, err := p.ruleGetter.Get(orgID, channelID) if err != nil { logger.Error("Error getting rule", "error", err) return nil, err } if !ruleOk { logger.Debug("Rule not found", "channel", channelID) return nil, err } ch, err := live.ParseChannel(channelID) if err != nil { logger.Error("Error parsing channel", "error", err, "channel", channelID) return nil, err } vars := Vars{ OrgID: orgID, Channel: channelID, Scope: ch.Scope, Namespace: ch.Namespace, Path: ch.Path, } if len(rule.DataOutputters) > 0 { var resultingChannelDataList []*ChannelData for _, out := range rule.DataOutputters { channelDataList, err := p.processDataOutput(ctx, out, vars, data) if err != nil { logger.Error("Error outputting frame", "error", err) return nil, err } resultingChannelDataList = append(resultingChannelDataList, channelDataList...) } return resultingChannelDataList, nil } return nil, nil } func (p *Pipeline) processDataOutput(ctx context.Context, out DataOutputter, vars Vars, data []byte) ([]*ChannelData, error) { var span trace.Span if p.tracer != nil { ctx, span = p.tracer.Start(ctx, "live.pipeline.data_output_"+out.Type()) span.SetAttributes( attribute.Int64("orgId", vars.OrgID), attribute.String("channel", vars.Channel), attribute.String("data", string(data)), attribute.String("output", out.Type()), ) defer span.End() } return out.OutputData(ctx, vars, data) }
pkg/services/live/pipeline/pipeline.go
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0003626607358455658, 0.0001764660992193967, 0.00016224540013354272, 0.00017188157653436065, 0.000028872662369394675 ]
{ "id": 13, "code_window": [ " {name}\n", " </InlineFormLabel>\n", " <div aria-label={ariaLabel}>\n", " <Select\n", " menuShouldPortal\n", " onChange={onChange}\n", " value={value}\n", " width={width ?? 25}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " inputId={inputId}\n" ], "file_path": "public/app/features/variables/editor/VariableSelectField.tsx", "type": "add", "edit_start_line_idx": 35 }
<?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 19.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="64px" height="64px" viewBox="-479 353 64 64" style="enable-background:new -479 353 64 64;" xml:space="preserve"> <style type="text/css"> .st0{fill:#52545C;} </style> <path class="st0" d="M-415.1,384c-0.4-0.7-9.5-16.6-31.6-16.6c0,0-0.1,0-0.1,0c0,0,0,0,0,0c0,0-0.1,0-0.1,0 c-22,0.1-31.3,15.9-31.6,16.6c-0.3,0.6-0.3,1.3,0,1.9c0.4,0.7,9.6,16.5,31.6,16.6c0,0,0.1,0,0.1,0c0,0,0,0,0,0c0,0,0.1,0,0.1,0 c22.2,0,31.2-16,31.6-16.6C-414.8,385.3-414.8,384.6-415.1,384z M-446.9,399.3c-7.9,0-14.3-6.4-14.3-14.3c0-7.9,6.4-14.3,14.3-14.3 c7.9,0,14.3,6.4,14.3,14.3C-432.6,392.9-439,399.3-446.9,399.3z"/> <g> <path class="st0" d="M-446.9,378.3c-0.9,0-1.8,0.2-2.6,0.5c1.2,0.4,2,1.5,2,2.9c0,1.7-1.4,3-3,3c-1.2,0-2.2-0.7-2.7-1.7 c-0.2,0.6-0.3,1.3-0.3,2c0,3.7,3,6.7,6.7,6.7c3.7,0,6.7-3,6.7-6.7S-443.2,378.3-446.9,378.3z"/> </g> </svg>
public/img/icons_light_theme/icon_viewer.svg
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00016537753981538117, 0.0001650132762733847, 0.00016464902728330344, 0.0001650132762733847, 3.6425626603886485e-7 ]
{ "id": 13, "code_window": [ " {name}\n", " </InlineFormLabel>\n", " <div aria-label={ariaLabel}>\n", " <Select\n", " menuShouldPortal\n", " onChange={onChange}\n", " value={value}\n", " width={width ?? 25}\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " inputId={inputId}\n" ], "file_path": "public/app/features/variables/editor/VariableSelectField.tsx", "type": "add", "edit_start_line_idx": 35 }
export function monkeyPatchInjectorWithPreAssignedBindings(injector: any) { injector.oldInvoke = injector.invoke; injector.invoke = (fn: any, self: any, locals: any, serviceName: any) => { const parentScope = locals?.$scope?.$parent; if (parentScope) { // PanelCtrl if (parentScope.panel) { self.panel = parentScope.panel; } // Panels & dashboard SettingsCtrl if (parentScope.dashboard) { self.dashboard = parentScope.dashboard; } // Query editors if (parentScope.ctrl?.target) { self.panelCtrl = parentScope.ctrl; self.datasource = parentScope.ctrl.datasource; self.target = parentScope.ctrl.target; } // Data source ConfigCtrl if (parentScope.ctrl?.datasourceMeta) { self.meta = parentScope.ctrl.datasourceMeta; self.current = parentScope.ctrl.current; } // Data source AnnotationsQueryCtrl if (parentScope.ctrl?.currentAnnotation) { self.annotation = parentScope.ctrl.currentAnnotation; self.datasource = parentScope.ctrl.currentDatasource; } // App config ctrl if (parentScope.isAppConfigCtrl) { self.appEditCtrl = parentScope.ctrl; self.appModel = parentScope.ctrl.model; } // App page ctrl if (parentScope.$parent?.$parent?.ctrl?.appModel) { self.appModel = parentScope.$parent?.$parent?.ctrl?.appModel; } } return injector.oldInvoke(fn, self, locals, serviceName); }; }
public/app/core/injectorMonkeyPatch.ts
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00018917063425760716, 0.00017446799029130489, 0.00016867832164280117, 0.00017216996639035642, 0.000006818752808612771 ]
{ "id": 14, "code_window": [ " <VerticalGroup spacing=\"lg\">\n", " <VerticalGroup spacing=\"none\">\n", " <InlineFieldRow>\n", " <InlineField label=\"Data source\" labelWidth={20}>\n", " <DataSourcePicker\n", " current={this.props.variable.datasource}\n", " onChange={this.onDataSourceChange}\n", " variables={true}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <InlineField label=\"Data source\" labelWidth={20} htmlFor=\"data-source-picker\">\n" ], "file_path": "public/app/features/variables/query/QueryVariableEditor.tsx", "type": "replace", "edit_start_line_idx": 163 }
import React, { PureComponent } from 'react'; import { css } from 'emotion'; import { connect, ConnectedProps } from 'react-redux'; import { locationService } from '@grafana/runtime'; import { selectors } from '@grafana/e2e-selectors'; import { CustomScrollbar, ScrollbarPosition, stylesFactory, Themeable2, withTheme2 } from '@grafana/ui'; import { createErrorNotification } from 'app/core/copy/appNotification'; import { Branding } from 'app/core/components/Branding/Branding'; import { DashboardGrid } from '../dashgrid/DashboardGrid'; import { DashNav } from '../components/DashNav'; import { DashboardSettings } from '../components/DashboardSettings'; import { PanelEditor } from '../components/PanelEditor/PanelEditor'; import { initDashboard } from '../state/initDashboard'; import { notifyApp } from 'app/core/actions'; import { KioskMode, StoreState } from 'app/types'; import { PanelModel } from 'app/features/dashboard/state'; import { PanelInspector } from '../components/Inspector/PanelInspector'; import { SubMenu } from '../components/SubMenu/SubMenu'; import { cleanUpDashboardAndVariables } from '../state/actions'; import { cancelVariables, templateVarsChangedInUrl } from '../../variables/state/actions'; import { findTemplateVarChanges } from '../../variables/utils'; import { dashboardWatcher } from 'app/features/live/dashboard/dashboardWatcher'; import { GrafanaRouteComponentProps } from 'app/core/navigation/types'; import { getTimeSrv } from '../services/TimeSrv'; import { getKioskMode } from 'app/core/navigation/kiosk'; import { GrafanaTheme2, TimeRange, UrlQueryValue } from '@grafana/data'; import { DashboardLoading } from '../components/DashboardLoading/DashboardLoading'; import { DashboardFailed } from '../components/DashboardLoading/DashboardFailed'; import { DashboardPrompt } from '../components/DashboardPrompt/DashboardPrompt'; import classnames from 'classnames'; import { PanelEditExitedEvent } from 'app/types/events'; import { liveTimer } from '../dashgrid/liveTimer'; export interface DashboardPageRouteParams { uid?: string; type?: string; slug?: string; } type DashboardPageRouteSearchParams = { tab?: string; folderId?: string; editPanel?: string; viewPanel?: string; editview?: string; inspect?: string; kiosk?: UrlQueryValue; from?: string; to?: string; refresh?: string; }; export const mapStateToProps = (state: StoreState) => ({ initPhase: state.dashboard.initPhase, isInitSlow: state.dashboard.isInitSlow, initError: state.dashboard.initError, dashboard: state.dashboard.getModel(), }); const mapDispatchToProps = { initDashboard, cleanUpDashboardAndVariables, notifyApp, cancelVariables, templateVarsChangedInUrl, }; const connector = connect(mapStateToProps, mapDispatchToProps); export type Props = Themeable2 & GrafanaRouteComponentProps<DashboardPageRouteParams, DashboardPageRouteSearchParams> & ConnectedProps<typeof connector>; export interface State { editPanel: PanelModel | null; viewPanel: PanelModel | null; scrollTop: number; updateScrollTop?: number; rememberScrollTop: number; showLoadingState: boolean; panelNotFound: boolean; editPanelAccessDenied: boolean; } export class UnthemedDashboardPage extends PureComponent<Props, State> { private forceRouteReloadCounter = 0; state: State = this.getCleanState(); getCleanState(): State { return { editPanel: null, viewPanel: null, showLoadingState: false, scrollTop: 0, rememberScrollTop: 0, panelNotFound: false, editPanelAccessDenied: false, }; } componentDidMount() { this.initDashboard(); this.forceRouteReloadCounter = (this.props.history.location.state as any)?.routeReloadCounter || 0; } componentWillUnmount() { this.closeDashboard(); } closeDashboard() { this.props.cleanUpDashboardAndVariables(); this.setState(this.getCleanState()); } initDashboard() { const { dashboard, match, queryParams } = this.props; if (dashboard) { this.closeDashboard(); } this.props.initDashboard({ urlSlug: match.params.slug, urlUid: match.params.uid, urlType: match.params.type, urlFolderId: queryParams.folderId, routeName: this.props.route.routeName, fixUrl: true, }); // small delay to start live updates setTimeout(this.updateLiveTimer, 250); } componentDidUpdate(prevProps: Props, prevState: State) { const { dashboard, match, templateVarsChangedInUrl } = this.props; const routeReloadCounter = (this.props.history.location.state as any)?.routeReloadCounter; if (!dashboard) { return; } // if we just got dashboard update title if (prevProps.dashboard !== dashboard) { document.title = dashboard.title + ' - ' + Branding.AppTitle; } if ( prevProps.match.params.uid !== match.params.uid || (routeReloadCounter !== undefined && this.forceRouteReloadCounter !== routeReloadCounter) ) { this.initDashboard(); this.forceRouteReloadCounter = routeReloadCounter; return; } if (prevProps.location.search !== this.props.location.search) { const prevUrlParams = prevProps.queryParams; const urlParams = this.props.queryParams; if (urlParams?.from !== prevUrlParams?.from || urlParams?.to !== prevUrlParams?.to) { getTimeSrv().updateTimeRangeFromUrl(); this.updateLiveTimer(); } if (!prevUrlParams?.refresh && urlParams?.refresh) { getTimeSrv().setAutoRefresh(urlParams.refresh); } const templateVarChanges = findTemplateVarChanges(this.props.queryParams, prevProps.queryParams); if (templateVarChanges) { templateVarsChangedInUrl(templateVarChanges); } } // entering edit mode if (this.state.editPanel && !prevState.editPanel) { dashboardWatcher.setEditingState(true); } // leaving edit mode if (!this.state.editPanel && prevState.editPanel) { dashboardWatcher.setEditingState(false); // Some panels need kicked when leaving edit mode this.props.dashboard?.events.publish(new PanelEditExitedEvent(prevState.editPanel.id)); } if (this.state.editPanelAccessDenied) { this.props.notifyApp(createErrorNotification('Permission to edit panel denied')); locationService.partial({ editPanel: null }); } if (this.state.panelNotFound) { this.props.notifyApp(createErrorNotification(`Panel not found`)); locationService.partial({ editPanel: null, viewPanel: null }); } } updateLiveTimer = () => { let tr: TimeRange | undefined = undefined; if (this.props.dashboard?.liveNow) { tr = getTimeSrv().timeRange(); } liveTimer.setLiveTimeRange(tr); }; static getDerivedStateFromProps(props: Props, state: State) { const { dashboard, queryParams } = props; const urlEditPanelId = queryParams.editPanel; const urlViewPanelId = queryParams.viewPanel; if (!dashboard) { return state; } // Entering edit mode if (!state.editPanel && urlEditPanelId) { const panel = dashboard.getPanelByUrlId(urlEditPanelId); if (!panel) { return { ...state, panelNotFound: true }; } if (dashboard.canEditPanel(panel)) { return { ...state, editPanel: panel }; } else { return { ...state, editPanelAccessDenied: true }; } } // Leaving edit mode else if (state.editPanel && !urlEditPanelId) { return { ...state, editPanel: null }; } // Entering view mode if (!state.viewPanel && urlViewPanelId) { const panel = dashboard.getPanelByUrlId(urlViewPanelId); if (!panel) { return { ...state, panelNotFound: urlEditPanelId }; } // This mutable state feels wrong to have in getDerivedStateFromProps // Should move this state out of dashboard in the future dashboard.initViewPanel(panel); return { ...state, viewPanel: panel, rememberScrollTop: state.scrollTop, updateScrollTop: 0, }; } // Leaving view mode else if (state.viewPanel && !urlViewPanelId) { // This mutable state feels wrong to have in getDerivedStateFromProps // Should move this state out of dashboard in the future dashboard.exitViewPanel(state.viewPanel); return { ...state, viewPanel: null, updateScrollTop: state.rememberScrollTop }; } // if we removed url edit state, clear any panel not found state if (state.panelNotFound || (state.editPanelAccessDenied && !urlEditPanelId)) { return { ...state, panelNotFound: false, editPanelAccessDenied: false }; } return state; } setScrollTop = ({ scrollTop }: ScrollbarPosition): void => { this.setState({ scrollTop, updateScrollTop: undefined }); }; onAddPanel = () => { const { dashboard } = this.props; if (!dashboard) { return; } // Return if the "Add panel" exists already if (dashboard.panels.length > 0 && dashboard.panels[0].type === 'add-panel') { return; } dashboard.addPanel({ type: 'add-panel', gridPos: { x: 0, y: 0, w: 12, h: 8 }, title: 'Panel Title', }); // scroll to top after adding panel this.setState({ updateScrollTop: 0 }); }; getInspectPanel() { const { dashboard, queryParams } = this.props; const inspectPanelId = queryParams.inspect; if (!dashboard || !inspectPanelId) { return null; } const inspectPanel = dashboard.getPanelById(parseInt(inspectPanelId, 10)); // cannot inspect panels plugin is not already loaded if (!inspectPanel) { return null; } return inspectPanel; } render() { const { dashboard, isInitSlow, initError, queryParams, theme } = this.props; const { editPanel, viewPanel, scrollTop, updateScrollTop } = this.state; const kioskMode = getKioskMode(queryParams.kiosk); const styles = getStyles(theme, kioskMode); if (!dashboard) { if (isInitSlow) { return <DashboardLoading initPhase={this.props.initPhase} />; } return null; } // Only trigger render when the scroll has moved by 25 const approximateScrollTop = Math.round(scrollTop / 25) * 25; const inspectPanel = this.getInspectPanel(); const containerClassNames = classnames(styles.dashboardContainer, { 'panel-in-fullscreen': viewPanel, }); return ( <div className={containerClassNames}> {kioskMode !== KioskMode.Full && ( <header aria-label={selectors.pages.Dashboard.DashNav.nav}> <DashNav dashboard={dashboard} title={dashboard.title} folderTitle={dashboard.meta.folderTitle} isFullscreen={!!viewPanel} onAddPanel={this.onAddPanel} kioskMode={kioskMode} hideTimePicker={dashboard.timepicker.hidden} /> </header> )} <DashboardPrompt dashboard={dashboard} /> <div className={styles.dashboardScroll}> <CustomScrollbar autoHeightMin="100%" setScrollTop={this.setScrollTop} scrollTop={updateScrollTop} hideHorizontalTrack={true} updateAfterMountMs={500} > <div className={styles.dashboardContent}> {initError && <DashboardFailed />} {!editPanel && kioskMode === KioskMode.Off && ( <section aria-label={selectors.pages.Dashboard.SubMenu.submenu}> <SubMenu dashboard={dashboard} annotations={dashboard.annotations.list} links={dashboard.links} /> </section> )} <DashboardGrid dashboard={dashboard} viewPanel={viewPanel} editPanel={editPanel} scrollTop={approximateScrollTop} /> </div> </CustomScrollbar> </div> {inspectPanel && <PanelInspector dashboard={dashboard} panel={inspectPanel} />} {editPanel && <PanelEditor dashboard={dashboard} sourcePanel={editPanel} tab={this.props.queryParams.tab} />} {queryParams.editview && <DashboardSettings dashboard={dashboard} editview={queryParams.editview} />} </div> ); } } /* * Styles */ export const getStyles = stylesFactory((theme: GrafanaTheme2, kioskMode) => { const contentPadding = kioskMode !== KioskMode.Full ? theme.spacing(0, 2, 2) : theme.spacing(2); return { dashboardContainer: css` width: 100%; height: 100%; display: flex; flex: 1 1 0; flex-direction: column; min-height: 0; `, dashboardScroll: css` width: 100%; flex-grow: 1; min-height: 0; display: flex; `, dashboardContent: css` padding: ${contentPadding}; flex-basis: 100%; flex-grow: 1; `, }; }); export const DashboardPage = withTheme2(UnthemedDashboardPage); DashboardPage.displayName = 'DashboardPage'; export default connector(DashboardPage);
public/app/features/dashboard/containers/DashboardPage.tsx
1
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0006842560833320022, 0.0001994450722122565, 0.0001639474940020591, 0.00017470035527367145, 0.00008284318028017879 ]
{ "id": 14, "code_window": [ " <VerticalGroup spacing=\"lg\">\n", " <VerticalGroup spacing=\"none\">\n", " <InlineFieldRow>\n", " <InlineField label=\"Data source\" labelWidth={20}>\n", " <DataSourcePicker\n", " current={this.props.variable.datasource}\n", " onChange={this.onDataSourceChange}\n", " variables={true}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <InlineField label=\"Data source\" labelWidth={20} htmlFor=\"data-source-picker\">\n" ], "file_path": "public/app/features/variables/query/QueryVariableEditor.tsx", "type": "replace", "edit_start_line_idx": 163 }
import { ArrayVector, createTheme, FieldType, toDataFrame } from '@grafana/data'; import { findNextStateIndex, prepareTimelineFields } from './utils'; const theme = createTheme(); describe('prepare timeline graph', () => { it('errors with no time fields', () => { const frames = [ toDataFrame({ fields: [ { name: 'a', values: [1, 2, 3] }, { name: 'b', values: ['a', 'b', 'c'] }, ], }), ]; const info = prepareTimelineFields(frames, true, theme); expect(info.warn).toEqual('Data does not have a time field'); }); it('requires a number, string, or boolean value', () => { const frames = [ toDataFrame({ fields: [ { name: 'a', type: FieldType.time, values: [1, 2, 3] }, { name: 'b', type: FieldType.other, values: [{}, {}, {}] }, ], }), ]; const info = prepareTimelineFields(frames, true, theme); expect(info.warn).toEqual('No graphable fields'); }); it('will merge duplicate values', () => { const frames = [ toDataFrame({ fields: [ { name: 'a', type: FieldType.time, values: [1, 2, 3, 4, 5, 6, 7] }, { name: 'b', values: [1, 1, undefined, 1, 2, 2, null, 2, 3] }, ], }), ]; const info = prepareTimelineFields(frames, true, theme); expect(info.warn).toBeUndefined(); const out = info.frames![0]; const field = out.fields.find((f) => f.name === 'b'); expect(field?.values.toArray()).toMatchInlineSnapshot(` Array [ 1, undefined, undefined, undefined, 2, undefined, null, 2, 3, ] `); }); }); describe('findNextStateIndex', () => { it('handles leading datapoint index', () => { const field = { name: 'time', type: FieldType.number, values: new ArrayVector([1, undefined, undefined, 2, undefined, undefined]), } as any; const result = findNextStateIndex(field, 0); expect(result).toEqual(3); }); it('handles trailing datapoint index', () => { const field = { name: 'time', type: FieldType.number, values: new ArrayVector([1, undefined, undefined, 2, undefined, 3]), } as any; const result = findNextStateIndex(field, 5); expect(result).toEqual(null); }); it('handles trailing undefined', () => { const field = { name: 'time', type: FieldType.number, values: new ArrayVector([1, undefined, undefined, 2, undefined, 3, undefined]), } as any; const result = findNextStateIndex(field, 5); expect(result).toEqual(null); }); it('handles datapoint index inside range', () => { const field = { name: 'time', type: FieldType.number, values: new ArrayVector([ 1, undefined, undefined, 3, undefined, undefined, undefined, undefined, 2, undefined, undefined, ]), } as any; const result = findNextStateIndex(field, 3); expect(result).toEqual(8); }); describe('single data points', () => { const field = { name: 'time', type: FieldType.number, values: new ArrayVector([1, 3, 2]), } as any; test('leading', () => { const result = findNextStateIndex(field, 0); expect(result).toEqual(1); }); test('trailing', () => { const result = findNextStateIndex(field, 2); expect(result).toEqual(null); }); test('inside', () => { const result = findNextStateIndex(field, 1); expect(result).toEqual(2); }); }); });
public/app/plugins/panel/state-timeline/utils.test.ts
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.0001787182263797149, 0.0001730693329591304, 0.00016351568046957254, 0.0001737682323437184, 0.0000037945740132272476 ]
{ "id": 14, "code_window": [ " <VerticalGroup spacing=\"lg\">\n", " <VerticalGroup spacing=\"none\">\n", " <InlineFieldRow>\n", " <InlineField label=\"Data source\" labelWidth={20}>\n", " <DataSourcePicker\n", " current={this.props.variable.datasource}\n", " onChange={this.onDataSourceChange}\n", " variables={true}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <InlineField label=\"Data source\" labelWidth={20} htmlFor=\"data-source-picker\">\n" ], "file_path": "public/app/features/variables/query/QueryVariableEditor.tsx", "type": "replace", "edit_start_line_idx": 163 }
import React from 'react'; import { QueryEditorHelpProps } from '@grafana/data'; import { PromQuery } from '../types'; const CHEAT_SHEET_ITEMS = [ { title: 'Request Rate', expression: 'rate(http_request_total[5m])', label: 'Given an HTTP request counter, this query calculates the per-second average request rate over the last 5 minutes.', }, { title: '95th Percentile of Request Latencies', expression: 'histogram_quantile(0.95, sum(rate(prometheus_http_request_duration_seconds_bucket[5m])) by (le))', label: 'Calculates the 95th percentile of HTTP request rate over 5 minute windows.', }, { title: 'Alerts Firing', expression: 'sort_desc(sum(sum_over_time(ALERTS{alertstate="firing"}[24h])) by (alertname))', label: 'Sums up the alerts that have been firing over the last 24 hours.', }, { title: 'Step', label: 'Defines the graph resolution using a duration format (15s, 1m, 3h, ...). Small steps create high-resolution graphs but can be slow over larger time ranges. Using a longer step lowers the resolution and smooths the graph by producing fewer datapoints. If no step is given the resolution is calculated automatically.', }, ]; const PromCheatSheet = (props: QueryEditorHelpProps<PromQuery>) => ( <div> <h2>PromQL Cheat Sheet</h2> {CHEAT_SHEET_ITEMS.map((item, index) => ( <div className="cheat-sheet-item" key={index}> <div className="cheat-sheet-item__title">{item.title}</div> {item.expression ? ( <div className="cheat-sheet-item__example" onClick={(e) => props.onClickExample({ refId: 'A', expr: item.expression })} > <code>{item.expression}</code> </div> ) : null} <div className="cheat-sheet-item__label">{item.label}</div> </div> ))} </div> ); export default PromCheatSheet;
public/app/plugins/datasource/prometheus/components/PromCheatSheet.tsx
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00017597764963284135, 0.00017145974561572075, 0.00016693698125891387, 0.0001722169981803745, 0.0000034676954783208203 ]
{ "id": 14, "code_window": [ " <VerticalGroup spacing=\"lg\">\n", " <VerticalGroup spacing=\"none\">\n", " <InlineFieldRow>\n", " <InlineField label=\"Data source\" labelWidth={20}>\n", " <DataSourcePicker\n", " current={this.props.variable.datasource}\n", " onChange={this.onDataSourceChange}\n", " variables={true}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " <InlineField label=\"Data source\" labelWidth={20} htmlFor=\"data-source-picker\">\n" ], "file_path": "public/app/features/variables/query/QueryVariableEditor.tsx", "type": "replace", "edit_start_line_idx": 163 }
{ "annotations": { "list": [ { "builtIn": 1, "datasource": "-- Grafana --", "enable": true, "hide": true, "iconColor": "rgba(0, 211, 255, 1)", "name": "Annotations & Alerts", "type": "dashboard" } ] }, "editable": true, "gnetId": null, "graphTooltip": 0, "id": 7501, "links": [], "panels": [ { "datasource": "gdev-testdata", "gridPos": { "h": 7, "w": 24, "x": 0, "y": 0 }, "id": 2, "links": [], "options": { "displayMode": "lcd", "fieldOptions": { "calcs": ["mean"], "defaults": { "max": 100, "min": 0, "unit": "decgbytes" }, "mappings": [], "override": {}, "thresholds": [ { "color": "green", "index": 0, "value": null }, { "color": "orange", "index": 1, "value": 60 }, { "color": "red", "index": 2, "value": 80 } ], "values": false }, "orientation": "vertical" }, "targets": [ { "alias": "sda1", "refId": "A", "scenarioId": "random_walk" }, { "alias": "sda2", "refId": "B", "scenarioId": "random_walk" }, { "alias": "sda3", "refId": "C", "scenarioId": "random_walk" }, { "alias": "sda4", "refId": "D", "scenarioId": "random_walk" }, { "alias": "sda5", "refId": "E", "scenarioId": "random_walk" }, { "alias": "sda6", "refId": "F", "scenarioId": "random_walk" }, { "alias": "sda7", "refId": "G", "scenarioId": "random_walk" }, { "alias": "sda8", "refId": "H", "scenarioId": "random_walk" }, { "alias": "sda9", "refId": "I", "scenarioId": "random_walk" }, { "alias": "sda10", "refId": "J", "scenarioId": "random_walk" }, { "alias": "sda11", "refId": "K", "scenarioId": "random_walk" }, { "alias": "sda12", "refId": "L", "scenarioId": "random_walk" }, { "alias": "sda13", "refId": "M", "scenarioId": "random_walk" }, { "alias": "sda14", "refId": "N", "scenarioId": "random_walk" }, { "alias": "sda15", "refId": "O", "scenarioId": "random_walk" }, { "alias": "sda16", "refId": "P", "scenarioId": "random_walk" } ], "timeFrom": null, "timeShift": null, "title": "", "transparent": true, "type": "bargauge" }, { "datasource": "gdev-testdata", "gridPos": { "h": 10, "w": 16, "x": 0, "y": 7 }, "id": 4, "links": [], "options": { "displayMode": "gradient", "fieldOptions": { "calcs": ["mean"], "defaults": { "decimals": null, "max": 100, "min": 0, "unit": "celsius" }, "mappings": [], "override": {}, "thresholds": [ { "color": "blue", "index": 0, "value": null }, { "color": "green", "index": 1, "value": 20 }, { "color": "orange", "index": 2, "value": 40 }, { "color": "red", "index": 3, "value": 80 } ], "values": false }, "orientation": "horizontal" }, "pluginVersion": "6.2.0-pre", "targets": [ { "alias": "Inside", "refId": "H", "scenarioId": "csv_metric_values", "stringInput": "100,100,100" }, { "alias": "Outhouse", "refId": "A", "scenarioId": "random_walk" }, { "alias": "Area B", "refId": "B", "scenarioId": "random_walk" }, { "alias": "Basement", "refId": "C", "scenarioId": "random_walk" }, { "alias": "Garage", "refId": "D", "scenarioId": "random_walk" } ], "timeFrom": null, "timeShift": null, "title": "Gradient mode", "type": "bargauge" }, { "datasource": "gdev-testdata", "gridPos": { "h": 10, "w": 6, "x": 16, "y": 7 }, "id": 6, "links": [], "options": { "displayMode": "basic", "fieldOptions": { "calcs": ["mean"], "defaults": { "decimals": null, "max": 100, "min": 0, "unit": "watt" }, "mappings": [], "override": {}, "thresholds": [ { "color": "blue", "index": 0, "value": null }, { "color": "green", "index": 1, "value": 42.5 }, { "color": "orange", "index": 2, "value": 80 }, { "color": "red", "index": 3, "value": 90 } ], "values": false }, "orientation": "horizontal" }, "pluginVersion": "6.2.0-pre", "targets": [ { "refId": "H", "scenarioId": "csv_metric_values", "stringInput": "100,100,100" }, { "refId": "A", "scenarioId": "random_walk" }, { "refId": "J", "scenarioId": "random_walk" }, { "refId": "K", "scenarioId": "random_walk" }, { "refId": "L", "scenarioId": "random_walk" }, { "refId": "M", "scenarioId": "random_walk" }, { "refId": "N", "scenarioId": "random_walk" }, { "refId": "O", "scenarioId": "random_walk" }, { "refId": "P", "scenarioId": "random_walk" }, { "refId": "Q", "scenarioId": "random_walk" } ], "timeFrom": null, "timeShift": null, "title": "Basic", "type": "bargauge" }, { "datasource": "gdev-testdata", "gridPos": { "h": 22, "w": 2, "x": 22, "y": 7 }, "id": 8, "links": [], "options": { "displayMode": "lcd", "fieldOptions": { "calcs": ["mean"], "defaults": { "max": 100, "min": 0 }, "mappings": [], "override": {}, "thresholds": [ { "color": "red", "index": 0, "value": null }, { "color": "red", "index": 1, "value": 90 } ], "values": false }, "orientation": "vertical" }, "targets": [ { "refId": "A", "scenarioId": "random_walk" } ], "timeFrom": null, "timeShift": null, "title": "Completion", "type": "bargauge" }, { "datasource": "gdev-testdata", "gridPos": { "h": 12, "w": 22, "x": 0, "y": 17 }, "id": 10, "links": [], "options": { "displayMode": "gradient", "fieldOptions": { "calcs": ["mean"], "defaults": { "max": 100, "min": 0, "unit": "decgbytes" }, "mappings": [], "override": {}, "thresholds": [ { "color": "blue", "index": 0, "value": null }, { "color": "green", "index": 1, "value": 30 }, { "color": "orange", "index": 2, "value": 60 }, { "color": "red", "index": 3, "value": 80 } ], "values": false }, "orientation": "vertical" }, "targets": [ { "alias": "sda1", "refId": "A", "scenarioId": "random_walk" }, { "alias": "sda2", "refId": "B", "scenarioId": "random_walk" }, { "alias": "sda3", "refId": "C", "scenarioId": "random_walk" }, { "alias": "sda4", "refId": "D", "scenarioId": "random_walk" }, { "alias": "sda5", "refId": "E", "scenarioId": "random_walk" }, { "alias": "sda6", "refId": "F", "scenarioId": "random_walk" }, { "alias": "sda7", "refId": "G", "scenarioId": "random_walk" }, { "alias": "sda8", "refId": "H", "scenarioId": "random_walk" }, { "alias": "sda9", "refId": "I", "scenarioId": "random_walk" }, { "alias": "sda10", "refId": "J", "scenarioId": "random_walk" }, { "alias": "sda11", "refId": "K", "scenarioId": "random_walk" }, { "alias": "sda12", "refId": "L", "scenarioId": "random_walk" }, { "alias": "sda13", "refId": "M", "scenarioId": "random_walk" }, { "alias": "sda14", "refId": "N", "scenarioId": "random_walk" }, { "alias": "sda15", "refId": "O", "scenarioId": "random_walk" }, { "alias": "sda16", "refId": "P", "scenarioId": "random_walk" } ], "timeFrom": null, "timeShift": null, "title": "", "type": "bargauge" }, { "datasource": "gdev-testdata", "gridPos": { "h": 8, "w": 24, "x": 0, "y": 29 }, "id": 11, "links": [], "options": { "displayMode": "basic", "fieldOptions": { "calcs": ["mean"], "defaults": { "max": 100, "min": 0, "unit": "decgbytes" }, "mappings": [], "override": {}, "thresholds": [ { "color": "blue", "index": 0, "value": null }, { "color": "green", "index": 1, "value": 30 }, { "color": "orange", "index": 2, "value": 60 }, { "color": "red", "index": 3, "value": 80 } ], "values": false }, "orientation": "vertical" }, "targets": [ { "alias": "sda1", "refId": "A", "scenarioId": "random_walk" }, { "alias": "sda2", "refId": "B", "scenarioId": "random_walk" }, { "alias": "sda3", "refId": "C", "scenarioId": "random_walk" }, { "alias": "sda4", "refId": "D", "scenarioId": "random_walk" }, { "alias": "sda5", "refId": "E", "scenarioId": "random_walk" }, { "alias": "sda6", "refId": "F", "scenarioId": "random_walk" }, { "alias": "sda7", "refId": "G", "scenarioId": "random_walk" }, { "alias": "sda8", "refId": "H", "scenarioId": "random_walk" }, { "alias": "sda9", "refId": "I", "scenarioId": "random_walk" }, { "alias": "sda10", "refId": "J", "scenarioId": "random_walk" }, { "alias": "sda11", "refId": "K", "scenarioId": "random_walk" }, { "alias": "sda12", "refId": "L", "scenarioId": "random_walk" }, { "alias": "sda13", "refId": "M", "scenarioId": "random_walk" }, { "alias": "sda14", "refId": "N", "scenarioId": "random_walk" }, { "alias": "sda15", "refId": "O", "scenarioId": "random_walk" }, { "alias": "sda16", "refId": "P", "scenarioId": "random_walk" } ], "timeFrom": null, "timeShift": null, "title": "", "type": "bargauge" } ], "refresh": "10s", "schemaVersion": 18, "style": "dark", "tags": ["gdev", "demo"], "templating": { "list": [] }, "time": { "from": "now-6h", "to": "now" }, "timepicker": { "refresh_intervals": ["2s", "5s", "10s", "30s", "1m", "5m", "15m", "30m", "1h", "2h", "1d"], "time_options": ["5m", "15m", "1h", "6h", "12h", "24h", "2d", "7d", "30d"] }, "timezone": "", "title": "Bar Gauge Demo", "uid": "vmie2cmWz", "version": 3 }
devenv/dev-dashboards/panel-bargauge/bar_gauge_demo.json
0
https://github.com/grafana/grafana/commit/a512dcf1bb0eba8bf3a3f512e868c85cb59fb571
[ 0.00017637306882534176, 0.00017282408953178674, 0.00016475017764605582, 0.0001732514938339591, 0.0000020356303593871417 ]
{ "id": 0, "code_window": [ "import { ViewTypes, isCreatedOrLastModifiedByCol, isSystemColumn } from 'nocodb-sdk'\n", "import type { ColumnType, GridColumnReqType, GridColumnType, MapType, TableType, ViewType } from 'nocodb-sdk'\n", "import type { ComputedRef, Ref } from 'vue'\n", "import { computed, ref, storeToRefs, useBase, useNuxtApp, useRoles, useUndoRedo, watch } from '#imports'\n", "import type { Field } from '#imports'\n", "\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { ViewTypes, isCreatedOrLastModifiedByCol, isMMSystemCol, isSystemColumn } from 'nocodb-sdk'\n" ], "file_path": "packages/nc-gui/composables/useViewColumns.ts", "type": "replace", "edit_start_line_idx": 0 }
import { ColumnReqType, ColumnType } from './Api'; enum UITypes { ID = 'ID', LinkToAnotherRecord = 'LinkToAnotherRecord', ForeignKey = 'ForeignKey', Lookup = 'Lookup', SingleLineText = 'SingleLineText', LongText = 'LongText', Attachment = 'Attachment', Checkbox = 'Checkbox', MultiSelect = 'MultiSelect', SingleSelect = 'SingleSelect', Collaborator = 'Collaborator', Date = 'Date', Year = 'Year', Time = 'Time', PhoneNumber = 'PhoneNumber', GeoData = 'GeoData', Email = 'Email', URL = 'URL', Number = 'Number', Decimal = 'Decimal', Currency = 'Currency', Percent = 'Percent', Duration = 'Duration', Rating = 'Rating', Formula = 'Formula', Rollup = 'Rollup', Count = 'Count', DateTime = 'DateTime', CreatedTime = 'CreatedTime', LastModifiedTime = 'LastModifiedTime', AutoNumber = 'AutoNumber', Geometry = 'Geometry', JSON = 'JSON', SpecificDBType = 'SpecificDBType', Barcode = 'Barcode', QrCode = 'QrCode', Button = 'Button', Links = 'Links', User = 'User', CreatedBy = 'CreatedBy', LastModifiedBy = 'LastModifiedBy', } export const UITypesName = { [UITypes.ID]: 'ID', [UITypes.LinkToAnotherRecord]: 'Link to another record', [UITypes.ForeignKey]: 'Foreign key', [UITypes.Lookup]: 'Lookup', [UITypes.SingleLineText]: 'Single line text', [UITypes.LongText]: 'Long text', RichText: 'Rich text', [UITypes.Attachment]: 'Attachment', [UITypes.Checkbox]: 'Checkbox', [UITypes.MultiSelect]: 'Multi select', [UITypes.SingleSelect]: 'Single select', [UITypes.Collaborator]: 'Collaborator', [UITypes.Date]: 'Date', [UITypes.Year]: 'Year', [UITypes.Time]: 'Time', [UITypes.PhoneNumber]: 'Phone number', [UITypes.GeoData]: 'Geo data', [UITypes.Email]: 'Email', [UITypes.URL]: 'URL', [UITypes.Number]: 'Number', [UITypes.Decimal]: 'Decimal', [UITypes.Currency]: 'Currency', [UITypes.Percent]: 'Percent', [UITypes.Duration]: 'Duration', [UITypes.Rating]: 'Rating', [UITypes.Formula]: 'Formula', [UITypes.Rollup]: 'Rollup', [UITypes.Count]: 'Count', [UITypes.DateTime]: 'Date time', [UITypes.CreatedTime]: 'Created time', [UITypes.LastModifiedTime]: 'Last modified time', [UITypes.AutoNumber]: 'Auto number', [UITypes.Geometry]: 'Geometry', [UITypes.JSON]: 'JSON', [UITypes.SpecificDBType]: 'Specific DB type', [UITypes.Barcode]: 'Barcode', [UITypes.QrCode]: 'Qr code', [UITypes.Button]: 'Button', [UITypes.Links]: 'Links', [UITypes.User]: 'User', [UITypes.CreatedBy]: 'Created by', [UITypes.LastModifiedBy]: 'Last modified by', }; export const numericUITypes = [ UITypes.Duration, UITypes.Currency, UITypes.Percent, UITypes.Number, UITypes.Decimal, UITypes.Rating, UITypes.Rollup, UITypes.Year, UITypes.Links, ]; export function isNumericCol( col: | UITypes | { readonly uidt: UITypes | string } | ColumnReqType | ColumnType ) { return numericUITypes.includes( <UITypes>(typeof col === 'object' ? col?.uidt : col) ); } export function isVirtualCol( col: | UITypes | { readonly uidt: UITypes | string } | ColumnReqType | ColumnType ) { return [ // Shouldn't be treated as virtual column (Issue with SQL View column data display) // UITypes.SpecificDBType, UITypes.LinkToAnotherRecord, UITypes.Formula, UITypes.QrCode, UITypes.Barcode, UITypes.Rollup, UITypes.Lookup, UITypes.Links, UITypes.CreatedTime, UITypes.LastModifiedTime, UITypes.CreatedBy, UITypes.LastModifiedBy, // UITypes.Count, ].includes(<UITypes>(typeof col === 'object' ? col?.uidt : col)); } export function isCreatedOrLastModifiedTimeCol( col: | UITypes | { readonly uidt: UITypes | string } | ColumnReqType | ColumnType ) { return [UITypes.CreatedTime, UITypes.LastModifiedTime].includes( <UITypes>(typeof col === 'object' ? col?.uidt : col) ); } export function isCreatedOrLastModifiedByCol( col: | UITypes | { readonly uidt: UITypes | string } | ColumnReqType | ColumnType ) { return [UITypes.CreatedBy, UITypes.LastModifiedBy].includes( <UITypes>(typeof col === 'object' ? col?.uidt : col) ); } export function isLinksOrLTAR( colOrUidt: ColumnType | { uidt: UITypes | string } | UITypes | string ) { return [UITypes.LinkToAnotherRecord, UITypes.Links].includes( <UITypes>(typeof colOrUidt === 'object' ? colOrUidt?.uidt : colOrUidt) ); } export default UITypes;
packages/nocodb-sdk/src/lib/UITypes.ts
1
https://github.com/nocodb/nocodb/commit/bd6115eb5eb53d7d1d30a351bbfb234b2adffe8e
[ 0.0285196453332901, 0.002769025042653084, 0.00016764171596150845, 0.0001766577479429543, 0.006752380169928074 ]
{ "id": 0, "code_window": [ "import { ViewTypes, isCreatedOrLastModifiedByCol, isSystemColumn } from 'nocodb-sdk'\n", "import type { ColumnType, GridColumnReqType, GridColumnType, MapType, TableType, ViewType } from 'nocodb-sdk'\n", "import type { ComputedRef, Ref } from 'vue'\n", "import { computed, ref, storeToRefs, useBase, useNuxtApp, useRoles, useUndoRedo, watch } from '#imports'\n", "import type { Field } from '#imports'\n", "\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { ViewTypes, isCreatedOrLastModifiedByCol, isMMSystemCol, isSystemColumn } from 'nocodb-sdk'\n" ], "file_path": "packages/nc-gui/composables/useViewColumns.ts", "type": "replace", "edit_start_line_idx": 0 }
{ "dashboards": { "create_new_dashboard_project": "Create New Interface", "connect_data_sources": "Connect data sources", "alert": "Alert", "alert-message": "No databases have been connected. Connect database bases to build interfaces. Skip this step and add databases from the base home page later.", "select_database_projects_that_you_want_to_link_to_this_dashboard_projects": "Select Database Bases that you want to link to this Interface.", "create_interface": "Create interface", "project_name": "Base Name", "connect": "Connect", "buttonActionTypes": { "open_external_url": "Open external link", "delete_record": "Delete record", "update_record": "Update record", "open_layout": "Open layout" }, "widgets": { "static_text": "Text", "chart": "Chart", "table": "Table", "image": "Image", "map": "Map", "button": "Button", "number": "Number", "bar_chart": "Bar Chart", "line_chart": "Line Chart", "area_chart": "Area Chart", "pie_chart": "Pie Chart", "donut_chart": "Donut Chart", "scatter_plot": "Scatter Plot", "bubble_chart": "Bubble Chart", "radar_chart": "Radar Chart", "polar_area_chart": "Polar Area Chart", "radial_bar_chart": "Radial Bar Chart", "heatmap_chart": "Heatmap Chart", "treemap_chart": "Treemap Chart", "box_plot_chart": "Box Plot Chart", "candlestick_chart": "Candlestick Chart" } }, "general": { "quit": "Quit", "home": "首頁", "load": "載入", "open": "開啟", "close": "關閉", "yes": "是", "no": "否", "ok": "確認", "back": "Back", "and": "和", "or": "或", "add": "新增", "edit": "編輯", "link": "Link", "links": "Links", "remove": "移除", "import": "Import", "logout": "Log Out", "empty": "Empty", "changeIcon": "Change Icon", "save": "儲存", "available": "Available", "abort": "Abort", "saving": "Saving", "cancel": "取消", "null": "Null", "escape": "Escape", "hex": "Hex", "clear": "Clear", "slack": "Slack", "comment": "Comment", "microsoftTeams": "Microsoft Teams", "discord": "Discord", "matterMost": "Mattermost", "twilio": "Twilio", "whatsappTwilio": "WhatsApp Twilio", "quote": "Quote", "submit": "提交", "create": "建立", "createEntity": "Create {entity}", "creating": "Creating", "creatingEntity": "Creating {entity}", "details": "Details", "skip": "Skip", "code": "Code", "duplicate": "複製", "duplicating": "Duplicating", "activate": "Activate", "action": "Action", "insert": "插入", "delete": "刪除", "deleteEntity": "Delete {entity}", "bulkInsert": "Bulk Insert", "bulkDelete": "Bulk Delete", "bulkUpdate": "Bulk Update", "deleting": "Deleting", "update": "更新", "rename": "重新命名", "reload": "重新載入", "reset": "重設", "install": "安裝", "show": "顯示", "access": "Access", "visibility": "Visibility", "hide": "隱藏", "deprecated": "Deprecated", "showAll": "顯示所有", "hideAll": "全部隱藏", "notFound": "Not found", "showMore": "顯示更多", "showOptions": "顯示選項", "hideOptions": "隱藏選項", "showMenu": "顯示選單", "hideMenu": "隱藏選單", "addAll": "全部新增", "removeAll": "全部移除", "signUp": "註冊", "signIn": "登入", "signOut": "登出", "required": "必填", "enableScanner": "啟用掃描器來填充", "preferred": "首選", "mandatory": "強制的", "loading": "載入中...", "title": "標題", "upload": "上傳", "download": "下載", "default": "預設", "base": "Source", "datasource": "Data Source", "more": "更多", "less": "較少", "event": "事件", "condition": "條件", "after": "後", "before": "前", "search": "搜尋", "searchIn": "Search In", "notification": "通知", "reference": "參考", "function": "功能", "confirm": "確認", "generate": "生成", "copy": "複製", "are": "are", "misc": "其他設定", "lock": "鎖定", "unlock": "解鎖", "credentials": "憑證", "help": "幫助", "questions": "問題", "reachOut": "在這裡聯絡我們", "betaNote": "此功能目前是 Beta 測試版", "moreInfo": "更多資訊能在這裡找到", "logs": "日誌", "groupingField": "分組欄位", "insertAfter": "插入在後", "insertBefore": "插入在前", "insertAbove": "Insert above", "insertBelow": "Insert below", "hideField": "隱藏欄位", "sortAsc": "升序排序", "sortDesc": "降序排序", "move": "Move", "geoDataField": "地理資料欄位", "type": "Type", "name": "Name", "changes": "Changes", "new": "New", "old": "Old", "data": "Data", "source": "Source", "destination": "Destination", "active": "Active", "inactive": "Inactive", "linked": "linked", "finish": "Finish", "min": "Min", "max": "Max", "avg": "Avg", "sum": "Sum", "count": "Count", "countDistinct": "Count Distinct", "sumDistinct": "Sum Distinct", "avgDistinct": "Avg Distinct", "join": "Join", "options": "Options", "primaryValue": "Primary Value", "useSurveyMode": "Use Survey Mode", "shift": "Shift", "enter": "Enter", "seconds": "Seconds", "paste": "Paste", "restore": "Restore" }, "objects": { "workspace": "Workspace", "workspaces": "Workspaces", "project": "項目", "projects": "項目", "table": "表格", "tables": "表格", "field": "欄位", "fields": "欄位", "column": "列", "columns": "列", "page": "頁", "pages": "頁", "record": "記錄", "records": "記錄", "webhook": "Webhook", "webhooks": "Webhook", "view": "檢視", "views": "所有檢視", "sidebar": "Sidebar", "viewType": { "grid": "網格", "gallery": "相簿", "form": "表單", "kanban": "看板", "calendar": "日曆", "map": "地圖" }, "user": "使用者", "users": "使用者", "role": "角色", "roles": "角色", "developer": "Developer", "roleType": { "owner": "所有者", "creator": "建立者", "editor": "編輯者", "commenter": "評論者", "viewer": "檢視者", "noaccess": "No Access", "superAdmin": "Super Admin", "orgLevelCreator": "組織層級建立者", "orgLevelViewer": "組織層級檢視者" }, "sqlVIew": "SQL 檢視", "rowHeight": "Record Height", "heightClass": { "short": "Short", "medium": "Medium", "tall": "Tall", "extra": "Extra" }, "externalDb": "External Database" }, "datatype": { "ID": "ID", "ForeignKey": "外键", "SingleLineText": "單行文本", "LongText": "長文本", "Attachment": "附件", "Checkbox": "核取方塊", "MultiSelect": "多選", "SingleSelect": "單選", "Collaborator": "協作者", "Date": "日期", "Year": "年", "Time": "時間", "PhoneNumber": "電話號碼", "Email": "電子郵件", "URL": "網址", "Number": "數字", "Decimal": "十進制", "Currency": "貨幣", "Percent": "百分比", "Duration": "期間", "GeoData": "地理資料", "Rating": "評分", "Formula": "公式", "Rollup": "匯總", "Count": "計數", "Lookup": "查閱", "DateTime": "日期時間", "CreatedTime": "創建時間", "LastModifiedTime": "最後修改時間", "AutoNumber": "自動編號", "Barcode": "條碼", "Button": "按鈕", "Password": "密碼", "relationProperties": { "noAction": "沒有任何行動", "cascade": "級聯", "restrict": "嚴格", "setNull": "設置 null", "setDefault": "設為預設" } }, "filterOperation": { "isEqual": "等於", "isNotEqual": "不等於", "isLike": "包含", "isNot like": "不包含", "isEmpty": "內容為空", "isNotEmpty": "内容不為空", "isNull": "內容為 Null", "isNotNull": "內容不為 Null" }, "title": { "docs": "Docs", "forum": "Forum", "parameter": "Parameter", "headers": "Headers", "parameterName": "Parameter Name", "currencyLocale": "Currency Locale", "currencyCode": "Currency Code", "searchMembers": "Search Members", "noMembersFound": "No members found", "dateJoined": "Date Joined", "tokenName": "Token name", "inDesktop": "in Desktop", "rowData": "Record data", "creator": "Creator", "qrCode": "QR Code", "termsOfService": "Terms of Service", "updateSelectedRows": "Update Selected Records", "noFiltersAdded": "No filters added", "editCards": "Edit Cards", "noFieldsFound": "No fields found", "displayValue": "Display Value", "expand": "Expand", "hideAll": "Hide all", "hideSystemFields": "Hide system fields", "removeFile": "Remove File", "hasMany": "Has Many", "manyToMany": "Many to Many", "virtualRelation": "Virtual Relation", "linkMore": "Link More", "linkMoreRecords": "Link more records", "downloadFile": "Download File", "renameTable": "Rename Table", "renamingTable": "Renaming Table", "renamingWs": "Renaming Workspace", "renameWs": "Rename Workspace", "deleteWs": "Delete Workspace", "deletingWs": "Deleting Workspace", "copyAuthToken": "Copy Auth Token", "copiedAuthToken": "Copied Auth Token", "copyInviteToken": "Copy Invite Token", "showSidebar": "Show Sidebar", "hideSidebar": "Hide Sidebar", "creatingTable": "Creating Table", "erdView": "實體關係圖", "newBase": "New Data Source", "newProj": "建立新專案", "createBase": "Create Base", "myProject": "我的專案", "formTitle": "表格標題", "collaborative": "Collaborative", "locked": "Locked", "personal": "Personal", "appStore": "應用程式商店", "teamAndAuth": "團隊和認證", "rolesUserMgmt": "角色和使用者管理", "userMgmt": "使用者管理", "apiTokens": "API Tokens", "apiTokenMgmt": "API 權杖管理", "rolesMgmt": "角色管理", "projMeta": "專案中繼資料", "metaMgmt": "中繼資料管理", "metadata": "中繼資料", "exportImportMeta": "匯出/匯入中繼資料", "uiACL": "UI 存取控制", "metaOperations": "中繼資料操作", "audit": "稽核", "auditLogs": "稽核記錄", "sqlMigrations": "SQL 遷移", "dbCredentials": "資料庫憑證", "advancedParameters": "SSL 及進階參數", "headCreateProject": "建立新專案|NocoDB", "headLogin": "登入|NocoDB", "resetPassword": "重設密碼", "teamAndSettings": "團隊 & 設定", "apiDocs": "API 說明文件", "importFromAirtable": "從 Airtable 匯入", "generateToken": "產生 Token", "APIsAndSupport": "APIs及支援", "helpCenter": "幫助中心", "noLabels": "No Labels", "swaggerDocumentation": "Swagger 文件", "quickImportFrom": "快速匯入從", "quickImport": "快速匯入", "quickImportAirtable": "Quick Import - Airtable", "quickImportCSV": "Quick Import - CSV", "quickImportExcel": "Quick Import - Excel", "quickImportJSON": "Quick Import - JSON", "jsonEditor": "JSON Editor", "comingSoon": "Coming Soon", "advancedSettings": "進階設定", "codeSnippet": "程式碼片段", "keyboardShortcut": "鍵盤快捷鍵", "generateRandomName": "生成隨機名稱", "findRowByScanningCode": "Find row by scanning a QR or Barcode", "tokenManagement": "Token Management", "addNewToken": "Add new token", "accountSettings": "Account Settings", "resetPasswordMenu": "Reset Password", "tokens": "Tokens", "userManagement": "User Management", "accountManagement": "Account management", "licence": "Licence", "allowAllMimeTypes": "Allow All Mime Types", "defaultView": "Default View", "relations": "Relations", "switchLanguage": "Switch Language", "renameFile": "Rename File", "links": { "noAction": "No Action", "cascade": "Cascade", "restrict": "Restrict", "setNull": "Set NULL", "setDefault": "Set Default" } }, "labels": { "heading1": "Heading 1", "heading2": "Heading 2", "heading3": "Heading 3", "bold": "Bold", "italic": "Italic", "underline": "Underline", "strike": "Strike", "taskList": "Task List", "bulletList": "Bullet List", "numberedList": "Numbered List", "downloadData": "Download Data", "blockQuote": "Block Quote", "noToken": "No Token", "tokenLimit": "Only one token per user is allowed", "duplicateAttachment": "File with name {filename} already attached", "viewIdColon": "VIEW ID: {viewId}", "toAddress": "To Address", "subject": "Subject", "body": "Body", "commaSeparatedMobileNumber": "Comma separated Mobile #", "headerName": "Header Name", "icon": "Icon", "max": "Max", "enableRichText": "Enable Rich Text", "idColon": "Id:", "copiedRecordURL": "Copied Record URL", "copyRecordURL": "Copy Record URL", "duplicateRecord": "Duplicate record", "binaryEncodingFormat": "Binary encoding format", "syntax": "Syntax", "examples": "Examples", "durationInfo": "A duration of time in minutes or seconds (e.g. 1:23).", "addHeader": "Add Header", "enterDefaultUrlOptional": "Enter default URL (Optional)", "negative": "Negative", "discard": "Discard", "default": "Default", "defaultNumberPercent": "Default Number (%)", "durationFormat": "Duration Format", "dateFormat": "Date Format", "timeFormat": "Time Format", "singularLabel": "Singular Label", "pluralLabel": "Plural Label", "optional": "(Optional)", "clickToMake": "Click to make", "visibleForRole": "visible for role:", "inUI": "in UI Dashboard", "projectSettings": "Base Settings", "clickToHide": "Click to hide", "clickToDownload": "Click to download", "forRole": "for role", "clickToCopyViewID": "Click to copy View ID", "viewMode": "View Mode", "searchUsers": "Search Users", "superAdmin": "Super Admin", "allTables": "All Tables", "members": "Members", "dataSources": "Data Sources", "connectDataSource": "Connect a Data Source", "searchProjects": "Search Bases", "createdBy": "創建人", "viewingAttachmentsOf": "Viewing Attachments of", "readOnly": "Readonly", "dropHere": "Drop here", "createdOn": "Created On", "notifyVia": "通知方式", "projName": "項目名", "profile": "Profile", "accountDetails": "Account Details", "controlAppearance": "Control your Appearance.", "accountEmailID": "Account Email ID", "backToWorkspace": "Back to Workspace", "untitledToken": "Untitled token", "tableName": "表名稱", "dashboardName": "Dashboard name", "createView": "Create a View", "creatingView": "Creating View", "duplicateView": "Duplicate View", "duplicateGridView": "Duplicate Grid View", "createGridView": "Create Grid View", "duplicateGalleryView": "Duplicate Gallery View", "createGalleryView": "Create Gallery View", "duplicateFormView": "Duplicate Form View", "createFormView": "Create Form View", "duplicateKanbanView": "Duplicate Kanban View", "createKanbanView": "Create Kanban View", "viewName": "檢視名稱", "viewLink": "查看鏈接", "columnName": "列名稱", "columnToScanFor": "Column to scan", "columnType": "列類型", "roleName": "角色名稱", "roleDescription": "角色描述", "databaseType": "資料庫中的類型", "lengthValue": "長度/值", "dbType": "資料庫類型", "sqliteFile": "SQLite 檔案", "hostAddress": "主機位址", "port": "連線埠號碼", "username": "使用者名稱", "password": "密碼", "schemaName": "Schema 名稱", "database": "資料庫", "action": "行動", "actions": "行動", "operation": "操作", "operationSub": "子操作", "operationType": "操作類型", "operationSubType": "操作子類型", "description": "描述", "authentication": "驗證", "token": "權杖", "where": "在哪裡", "cache": "緩存", "chat": "聊天", "showOrHide": "Show or Hide", "airtable": "Airtable", "csv": "CSV", "csvFile": "CSV File", "json": "JSON", "jsonFile": "JSON File", "excel": "Excel", "microsoftExcel": "Microsoft Excel", "email": "電子郵件", "storage": "貯存", "uiAcl": "UI-ACL", "models": "楷模", "syncState": "同步狀態", "created": "已建立", "sqlOutput": "SQL 輸出", "addOption": "新增選項", "interfaceColor": "Interface Color", "qrCodeValueColumn": "Column with QR code value", "barcodeValueColumn": "Column with Barcode value", "barcodeFormat": "條碼格式", "qrCodeValueTooLong": "QR碼字元過多", "barcodeValueTooLong": "條碼字元過多", "currentLocation": "目前位置", "lng": "經度", "lat": "緯度", "aggregateFunction": "匯總功能", "dbCreateIfNotExists": "資料庫:不存在則建立", "clientKey": "用戶端金鑰", "clientCert": "用戶端憑證", "serverCA": "伺服器 CA", "requriedCa": "必填 - CA", "requriedIdentity": "必填 - IDENTITY", "inflection": { "tableName": "修改 - 表名", "columnName": "屈折 - 欄位名稱" }, "community": { "starUs1": "在 Github 上", "starUs2": "幫我們按讚", "bookDemo": "預訂免費 Demo", "getAnswered": "解惑您的問題", "joinDiscord": "加入 Discord", "joinCommunity": "加入 NocoDB 社群", "joinReddit": "加入 /r/NocoDB", "followNocodb": "追蹤 NocoDB", "communityTranslated": "(Community Translated)" }, "twitter": "Twitter", "docReference": "文件參考文獻", "selectUserRole": "選擇使用者角色", "childTable": "子表", "childColumn": "子欄", "childField": "Child field", "joinCloudForFree": "Join Cloud for Free", "linkToAnotherRecord": "連結到另一個紀錄", "links": "Links", "onUpdate": "更新時", "onDelete": "刪除時", "account": "帳號", "language": "語言", "primaryColor": "主色調", "accentColor": "強調色", "customTheme": "自訂主題", "requestDataSource": "提供您需要的資料源?", "apiKey": "API 金鑰", "personalAccessToken": "Personal Access Token", "sharedBaseUrl": "Shared Base URL", "importData": "匯入資料", "importSecondaryViews": "匯入次要檢視", "importRollupColumns": "Import Rollup Columns", "importLookupColumns": "Import Lookup Columns", "importAttachmentColumns": "Import Attachment Columns", "importFormulaColumns": "Import Formula Columns", "importUsers": "Import Users (by email)", "noData": "沒有資料", "goToDashboard": "前往儀表板", "importing": "匯入中", "formatJson": "Format JSON", "autoSelectFieldTypes": "Auto-Select Field Types", "firstRowAsHeaders": "Use First Record as Headers", "flattenNested": "展平嵌套", "downloadAllowed": "允許下載", "weAreHiring": "我們正在招聘中!", "primaryKey": "主鍵", "hasMany": "有很多的", "belongsTo": "屬於", "manyToMany": "有多對多關聯", "extraConnectionParameters": "額外連線參數", "commentsOnly": "僅評論", "documentation": "說明文件", "subscribeNewsletter": "訂閱我們的每週新聞", "signUpWithProvider": "Sign up with {provider}", "signInWithProvider": "Sign in with {provider}", "agreeToTos": "通過註冊,表示您同意遵守服務條款", "welcomeToNc": "歡迎來到 NocoDB!", "inviteOnlySignup": "只接受使用邀請連結進行註冊", "nextRow": "Next Row", "prevRow": "Previous Row", "addRowGrid": "Manually add data in grid view", "addRowForm": "Enter record data through a form", "noAccess": "No access", "restApis": "Rest APIs", "apis": "APIs", "includeData": "Include Data", "includeView": "Include View", "includeWebhook": "Include Webhook", "zoomInToViewColumns": "Zoom in to view columns", "embedInSite": "Embed this view in your site", "titleRequired": "title is required.", "sourceNameRequired": "Source name is required", "changeWsName": "Change Workspace Name", "pressEnter": "Press Enter", "newFormLoaded": "New form will be loaded after", "webhook": "Webhook", "multiField": { "newField": "New field", "saveChanges": "Save changes", "updatedField": "Updated field", "deletedField": "Deleted field", "incompleteConfiguration": "Incomplete configuration", "selectField": "Select a field", "selectFieldLabel": "Make changes to field properties by selecting a field from the list" } }, "activity": { "openInANewTab": "Open in a new tab", "copyIFrameCode": "Copy IFrame code", "onCondition": "On Condition", "bulkDownload": "Bulk Download", "attachFile": "Attach File", "viewAttachment": "View Attachments", "attachmentDrop": "Click or drop a file into cell", "addFiles": "Add File(s)", "hideInUI": "Hide in UI", "addBase": "Add Base", "addParameter": "Add Parameter", "submitAnotherForm": "Submit Another Form", "dragAndDropFieldsHereToAdd": "Drag and drop fields here to add", "editSource": "Edit Data Source", "enterText": "Enter text", "okEditBase": "Ok & Edit Base", "showInUI": "Show in UI", "outOfSync": "Out of sync", "newSource": "New Data Source", "newWebhook": "New Webhook", "enablePublicAccess": "Enable Public Access", "doYouWantToSaveTheChanges": "Do you want to save the changes ?", "editingAccess": "Editing access", "enabledPublicViewing": "Enable Public Viewing", "restrictAccessWithPassword": "Restrict access with password", "manageProjectAccess": "Manage Base Access", "allowDownload": "Allow Download", "surveyMode": "Survey Mode", "rtlOrientation": "RTL Orientation", "useTheme": "Use Theme", "copyLink": "Copy Link", "copiedLink": "Link Copied", "copyInviteLink": "Copy invite link", "copiedInviteLink": "Copied invite link", "copyUrl": "複製網址", "moreColors": "More Colors", "moveProject": "Move Base", "createProject": "建立專案", "importProject": "匯入專案", "searchProject": "搜尋專案", "editProject": "編輯專案", "stopProject": "停止專案", "startProject": "啟動專案", "restartProject": "重啟專案", "deleteProject": "刪除專案", "refreshProject": "重新整理專案", "saveProject": "儲存專案", "saveAndQuit": "Save & Quit", "deleteKanbanStack": "刪除此類別?", "createProjectExtended": { "extDB": "創建連接 <br>從外部資料庫", "excel": "從 Excel 建立專案", "template": "從模板建立專案" }, "OkSaveProject": "確認並儲存專案", "upgrade": { "available": "升級可用", "releaseNote": "發行說明", "howTo": "如何升級?" }, "translate": "幫助翻譯", "account": { "authToken": "複製驗證權杖", "authTokenCopied": "Copied Auth Token", "swagger": "Swagger: REST APIs", "projInfo": "複製專案資訊", "themes": "主題" }, "sort": "種類", "addSort": "新增排序選項", "filter": "篩選", "addFilter": "添加過濾器", "share": "分享", "groupBy": "Group By", "addSubGroup": "Add subgroup", "shareBase": { "label": "Share Base", "disable": "停用共享資料庫", "enable": "任何有連結的人", "link": "共享資料庫連結" }, "invite": "邀請", "inviteMore": "邀請更多", "inviteTeam": "邀請團隊", "inviteUser": "邀請使用者", "inviteToken": "邀請權杖", "linkedRecords": "Linked Records", "addNewLink": "Add New Link", "newUser": "新使用者", "editUser": "編輯使用者", "deleteUser": "從專案中刪除使用者", "resendInvite": "重新發送邀請電子郵件", "copyInviteURL": "複製邀請連結", "copyPasswordResetURL": "複製重設密碼連結", "newRole": "新角色", "reloadRoles": "重新載入角色", "nextPage": "下一頁", "prevPage": "上一頁", "nextRecord": "下一筆紀錄", "previousRecord": "上一筆紀錄", "copyApiURL": "複製 API 網址", "createTable": "Create New Table", "createDashboard": "Create Dashboard", "createWorkspace": "Create Workspace", "refreshTable": "刷新表", "renameTable": "重命名表", "renameLayout": "Layout Rename", "deleteTable": "刪除表", "addField": "新增欄位到此表", "setDisplay": "設置為顯示值", "addRow": "新增行", "saveRow": "儲存行", "saveAndExit": "儲存並結束", "saveAndStay": "儲存並停留", "insertRow": "插入新行", "duplicateRow": "Duplicate Row", "deleteRow": "刪除行", "deleteRows": "Delete records", "predictColumns": "Predict Fields", "predictFormulas": "Predict Formulas", "deleteSelectedRow": "刪除所選行", "importExcel": "匯入 Excel", "importCSV": "匯入 CSV", "downloadCSV": "下載為 CSV", "downloadExcel": "下載為 XLSX", "uploadCSV": "上傳 CSV", "import": "匯入", "importMetadata": "匯入中繼資料", "exportMetadata": "匯出中繼資料", "clearMetadata": "清除中繼資料", "exportToFile": "匯出為檔案", "changePwd": "更改密碼", "createView": "建立檢視", "shareView": "分享檢視", "findRowByCodeScan": "Find row by scan", "fillByCodeScan": "通過掃描填充", "listSharedView": "共享檢視列表", "ListView": "檢視清單", "copyView": "複製檢視", "renameView": "重新命名檢視", "uploadData": "Upload Data", "deleteView": "刪除檢視", "createGrid": "創建網格檢視", "createGallery": "創建相簿檢視", "createCalendar": "創建日曆檢視", "createKanban": "創建看板檢視", "createForm": "創建表單檢視", "showSystemFields": "顯示系統欄位", "openTab": "開啟新分頁", "iFrame": "複製嵌入式 HTML 程式碼", "addWebhook": "新增 Webhook", "enableWebhook": "啟用 Webhook", "testWebhook": "測試 Webhook", "copyWebhook": "複製 Webhook", "deleteWebhook": "刪除 Webhook", "newToken": "新增權杖", "exportZip": "匯出 ZIP", "importZip": "匯入 ZIP", "metaSync": "立即同步", "settings": "設定", "previewAs": "預覽方式", "resetReview": "重設預覽", "testDbConn": "測試資料庫連線", "removeDbFromEnv": "從環境移除資料庫", "editConnJson": "編輯連線 JSON", "sponsorUs": "贊助我們", "sendEmail": "傳送電子郵件", "addUserToProject": "Add user to project", "getApiSnippet": "取得 API 程式碼片段", "clearCell": "清除儲存格", "addFilterGroup": "增加過濾組", "linkRecord": "連結記錄", "addNewRecord": "新增紀錄", "newRecord": "New record", "tableNameCreateNewRecord": "{tableName}: Create new record", "gotSavedLinkedSuccessfully": "{tableName} '{recordTitle}' got saved & linked successfully", "recordCreatedLinked": "Record Created & Linked", "useConnectionUrl": "使用連接網址", "toggleCommentsDraw": "切換評論抽屜", "expandRecord": "展開紀錄", "deleteRecord": "刪除紀錄", "fullWidth": "Full width", "exitFullWidth": "Exit full width", "markAllAsRead": "Mark all as read", "column": { "delete": "Delete Field", "addNumber": "Add Number Field", "addSingleLineText": "Add SingleLineText Field", "addLongText": "Add LongText Field", "addOther": "Add Other Field" }, "erd": { "showColumns": "顯示欄位", "showPkAndFk": "顯示主鍵與外鍵", "showSqlViews": "顯示 SQL 檢視", "showMMTables": "顯示多對多資料表", "showJunctionTableNames": "顯示連接表名稱" }, "kanban": { "collapseStack": "摺疊此類別", "deleteStack": "刪除此類別", "stackedBy": "分類依據", "chooseGroupingField": "選擇一個分組欄位", "addOrEditStack": "新增/編輯類別" }, "map": { "mappedBy": "映射依據", "chooseMappingField": "選擇一個映射欄位", "openInGoogleMaps": "Google 地圖", "openInOpenStreetMap": "OSM" }, "toggleMobileMode": "切換到手機模式", "startCommenting": "Start commenting!" }, "tooltip": { "reachedSourceLimit": "Limited to only one data source for the moment", "saveChanges": "儲存更動", "xcDB": "建立新專案", "extDB": "支援 MySQL、PostgreSQL、SQL Server 和 SQLite", "apiRest": "可透過 REST API 存取", "apiGQL": "可透過 GraphQL API 存取", "theme": { "dark": "它確實有黑色(^⇧b)", "light": "它是黑色嗎?(^⇧b)" }, "addTable": "新增表", "addDashboard": "Add new Dashboard", "inviteMore": "邀請更多用戶", "toggleNavDraw": "切換導航抽屜", "reloadApiToken": "重新載入 API 權杖", "generateNewApiToken": "產生新 API 權杖", "addRole": "新增角色", "reloadList": "重新加載列表", "metaSync": "同步中繼資料", "sqlMigration": "重新加載遷移", "updateRestart": "更新並重新啟動", "cancelReturn": "取消並返回", "exportMetadata": "將所有中繼資料從中繼資料表匯出至中繼目錄。", "importMetadata": "將所有中繼資料從中繼目錄匯入至中繼資料表。", "clearMetadata": "清除中繼資料表中的所有中繼資料。", "clientKey": "選擇 .key 檔案", "clientCert": "選擇 .cert 檔案", "clientCA": "選擇 CA 檔案" }, "placeholder": { "selectSlackChannels": "Select Slack channels", "selectTeamsChannels": "Select Microsoft Teams channels", "selectDiscordChannels": "Select Discord channels", "selectMattermostChannels": "Select Mattermost channels", "webhookTitle": "Webhook Title", "barcodeColumn": "Select a field for the Barcode value", "notFoundContent": "No valid field Type can be found.", "selectBarcodeFormat": "Select a Barcode format", "projName": "輸入專案名稱", "selectGroupField": "Select a Grouping Field", "selectGroupFieldNotFound": "No Single Select Field can be found. Please create one first.", "selectGeoField": "Select a GeoData Field", "selectGeoFieldNotFound": "No GeoData Field can be found. Please create one first.", "password": { "enter": "輸入密碼", "current": "當前密碼", "new": "新密碼", "save": "儲存密碼", "confirm": "確認新密碼" }, "selectAColumnForTheQRCodeValue": "Select a field for the QR code value", "allowNegativeNumbers": "Allow negative numbers", "searchProjectTree": "搜索表", "searchFields": "搜索欄位", "searchColumn": "搜索{search}列", "searchApps": "搜索應用程序", "searchModels": "搜索模型", "noItemsFound": "未找到任何項目", "defaultValue": "預設值", "filterByEmail": "通過電子郵件過濾", "filterQuery": "過濾查詢", "selectField": "選擇欄位", "precision": "Precision", "decimal1": "1.0", "decimal2": "1.00", "decimal3": "1.000", "decimal4": "1.0000", "decimal5": "1.00000", "decimal6": "1.000000", "decimal7": "1.0000000", "decimal8": "1.00000000", "value": "Value", "key": "Key" }, "msg": { "clickToCopyFieldId": "Click to copy Field Id", "enterPassword": "Enter password", "bySigningUp": "By signing up, you agree to the", "subscribeToOurWeeklyNewsletter": "Subscribe to our weekly newsletter", "verifyingPassword": "Verifying Password", "thisSharedViewIsProtected": "This shared view is protected", "successfullySubmittedFormData": "Successfully submitted form data", "formViewNotSupportedOnMobile": "Form view is not supported on mobile", "newFormWillBeLoaded": "New form will be loaded after {seconds} seconds", "optimizedQueryDisabled": "Optimized query is disabled", "optimizedQueryEnabled": "Optimized query is enabled", "lookupNonBtWarning": "Lookup field is not supported for non-Belongs to relation", "invalidTime": "Invalid Time", "linkColumnClearNotSupportedYet": "You don't have any supported links for Lookup", "recordCouldNotBeFound": "Record could not be found", "invalidPhoneNumber": "Invalid phone number", "pageSizeChanged": "Page size changed", "errorLoadingData": "Error loading data", "webhookBodyMsg1": "Use context variable", "webhookBodyMsg2": "body", "webhookBodyMsg3": "to refer the record under consideration", "formula": { "hintStart": "Hint: Use {placeholder1} to reference fields, e.g: {placeholder2}. For more, please check out", "hintEnd": "Formulas.", "noSuggestedFormulaFound": "No suggested formula found", "typeIsExpected": "{calleeName} requires a {type} at position {position}", "numericTypeIsExpected": "Numeric type is expected", "stringTypeIsExpected": "String type is expected", "operationNotAvailable": "{operation} operation not available", "cantSaveFieldFormulaInvalid": "Can’t save field because formula is invalid", "notSupportedToReferenceColumn": "Not supported to reference field {columnName}", "typeIsExpectedButFound": "Type {type} is expected but found Type {found}", "requiredArgumentsFormula": "{calleeName} requires {requiredArguments} arguments", "minRequiredArgumentsFormula": "{calleeName} required minimum {minRequiredArguments} arguments", "maxRequiredArgumentsFormula": "{calleeName} required maximum {maxRequiredArguments} arguments", "functionNotAvailable": "{function} function is not available", "firstParamWeekDayHaveDate": "The first parameter of WEEKDAY() should have date value", "secondParamWeekDayHaveDate": "The second parameter of WEEKDAY() should have the value either \"sunday\", \"monday\", \"tuesday\", \"wednesday\", \"thursday\", \"friday\" or \"saturday\"", "firstParamDateAddHaveDate": "The first parameter of DATEADD() should have date value", "secondParamDateAddHaveNumber": "The second parameter of DATEADD() should have numeric value", "thirdParamDateAddHaveDate": "The third parameter of DATEADD() should have the value either \"day\", \"week\", \"month\" or \"year\"", "firstParamDateDiffHaveDate": "The first parameter of DATEDIFF() should have date value", "secondParamDateDiffHaveDate": "The second parameter of DATEDIFF() should have date value", "thirdParamDateDiffHaveDate": "The third parameter of DATETIME_DIFF() should have value either \"milliseconds\", \"ms\", \"seconds\", \"s\", \"minutes\", \"m\", \"hours\", \"h\", \"days\", \"d\", \"weeks\", \"w\", \"months\", \"M\", \"quarters\", \"Q\", \"years\", or \"y\"", "columnNotAvailable": "Field {columnName} is not available", "cantSaveCircularReference": "Can’t save field because it causes a circular reference", "columnWithTypeFoundButExpected": "Field {columnName} with {columnType} type is found but {expectedType} type is expected", "columnNotMatchedWithType": "{columnName} is not matched with {columnType}" }, "selectOption": { "cantBeNull": "Select options can't be null", "multiSelectCantHaveCommas": "MultiSelect fields can't have commas(',')", "cantHaveDuplicates": "Select options can't have duplicates", "createNewOptionNamed": "Create new option named" }, "plsEnterANumber": "Please enter a number", "plsInputEmail": "Please input email", "invalidDate": "Invalid date", "invalidLocale": "Invalid locale", "invalidCurrencyCode": "Invalid Currency Code", "postgresHasItsOwnCurrencySettings": "PostgreSQL 'money' type has own currency settings", "validColumnsForBarCode": "The valid Field Types for a Barcode Field are: Number, Single Line Text, Long Text, Phone Number, URL, Email, Decimal. Please create one first.", "hm": { "title": "Has Many Relation", "tooltip_desc": "A single record from table ", "tooltip_desc2": " can be linked with multiple records from table " }, "mm": { "title": "Many to Many Relation", "tooltip_desc": "Multiple records from table ", "tooltip_desc2": " can be linked with multiple records from table " }, "bt": { "title": "Belongs to Relation", "tooltip_desc": "A single record from table ", "tooltip_desc2": " can be linked with a record from table " }, "oo": { "title": "One to One Relation", "tooltip_desc": "A single record from table ", "tooltip_desc2": " can be linked with a single record from table " }, "noRecordsAreLinkedFromTable": "No records are linked from table", "noRecordsLinked": "No records linked", "recordsLinked": "records linked", "acceptOnlyValid": "Accepts only", "apiTokenCreate": "Create personal API tokens to use in automation or external apps.", "selectFieldToSort": "Select Field to Sort", "selectFieldToGroup": "Select Field to Group", "thereAreNoRecordsInTable": "There are no records in table", "createWebhookMsg1": "Get started with web-hooks!", "createWebhookMsg2": "Create web-hooks to power you automations,", "createWebhookMsg3": "Get notified as soon as there are changes in your data", "areYouSureUWantTo": "Are you sure you want to delete the following", "areYouSureUWantToDeleteLabel": "Are you sure you want to {deleteLabel} the following", "idColumnRequired": "ID field is required, you can rename this later if required.", "length59Required": "The length exceeds the max 59 characters", "noNewNotifications": "You have no new notifications", "noRecordFound": "Record not found", "rowDeleted": "Record deleted", "saveChanges": "Do you want to save the changes?", "tooLargeFieldEntity": "The field is too large to be converted to {entity}", "roleRequired": "Role required", "warning": { "dbValid": "Please make sure database you are trying to connect is valid! This operation can cause schema loss!!", "barcode": { "renderError": "條碼錯誤 - 請檢查輸入和條碼類型之間的兼容性" }, "nonEditableFields": { "computedFieldUnableToClear": "警告:計算欄位 - 無法清除文字", "qrFieldsCannotBeDirectlyChanged": "警告:無法直接更改 QR 欄位", "barcodeFieldsCannotBeDirectlyChanged": "Warning: Barcode fields cannot be directly changed." }, "duplicateProject": "Are you sure you want to duplicate the base?", "duplicateTable": "Are you sure you want to duplicate the table?", "multiField": { "fieldVisibility": "You cannot change visibility of a field that is being edited. Please save or discard changes first.", "moveEditedField": "You cannot move field that is being edited. Either save or discard changes first", "moveDeletedField": "You cannot move field that is deleted. Either save or discard changes first" } }, "info": { "disabledAsViewLocked": "Disabled as View is locked", "basesMigrated": "Bases are migrated. Please try again.", "pasteNotSupported": "不支援在啟用的儲存格中執行貼上", "roles": { "orgCreator": "建立者可以建立專案與存取任何受邀請的專案", "orgViewer": "檢視者不能建立專案但可以存取任何受邀請的專案" }, "codeScanner": { "loadingScanner": "正在載入掃描器...", "selectColumn": "Select a column (QR code or Barcode) that you want to use for finding a row by scanning.", "moreThanOneRowFoundForCode": "More than one row found for this code. Currently only unique codes are supported.", "noRowFoundForCode": "No row found for this code for the selected column" }, "map": { "overLimit": "您已接近上限。", "closeLimit": "您超過了上限。", "limitNumber": "在地圖檢視中顯示的標記數量上限為 1000 條記錄。" }, "footerInfo": "每頁行駛", "upload": "選擇檔案以上傳", "upload_sub": "或拖放檔案", "excelSupport": "支持:.xls,.xlsx,.xlsm,.ods,.ots", "excelURL": "輸入 Excel 檔案 URL", "csvURL": "輸入 CSV 檔案 URL", "footMsg": "要解析為推斷數據類型的行數", "excelImport": "工作表可匯入", "exportMetadata": "您想從中繼表匯出中繼資料嗎?", "importMetadata": "您想從中繼表匯入中繼資料嗎?", "clearMetadata": "你想清除中繼表的中繼資料嗎?", "projectEmptyMessage": "從建立新專案開始", "stopProject": "你想停止這個專案嗎?", "startProject": "你想啟動這個專案嗎?", "restartProject": "你想重新啟動專案嗎?", "deleteProject": "你想刪除這個專案嗎?", "shareBasePrivate": "產生公開分享的唯讀資料庫", "shareBasePublic": "網路上的任何人都可以查看", "userInviteNoSMTP": "看起來你還沒有配置郵件!請複制上面的邀請鏈接並將其發送給", "dragDropHide": "拖放欄位到此處隱藏", "formInput": "輸入表單輸入標籤", "formHelpText": "新增一些說明文字", "onlyCreator": "僅建立者可見", "formDesc": "新增表單描述", "beforeEnablePwd": "使用密碼限制存取權限", "afterEnablePwd": "存取受密碼限制", "privateLink": "此檢視通過私人連結共享", "privateLinkAdditionalInfo": "具有私有連結的人只能看到此檢視中可見的儲存格", "afterFormSubmitted": "表格提交後", "apiOptions": "存取專案方式", "submitAnotherForm": "顯示“提交另一個表格”按鈕", "showBlankForm": "5 秒後顯示空白表格", "emailForm": "發電子郵件給我", "showSysFields": "顯示系統欄位", "filterAutoApply": "自動申請", "showMessage": "顯示此消息", "viewNotShared": "當前檢視不共享!", "showAllViews": "顯示此表的所有共享視圖", "collabView": "擁有編輯權限或更高權限的協作者可以更改檢視配置。", "lockedView": "在解鎖之前,沒有人可以編輯檢視配置。", "personalView": "只有您可以編輯檢視配置。其他協作者的個人檢視預設情況下是隱藏的。", "ownerDesc": "可以新增或移除建立者,以及完全編輯資料庫的結構和欄位。", "creatorDesc": "可以完全編輯資料庫結構和值。", "editorDesc": "可以編輯記錄但無法更改資料庫/欄位的結構。", "commenterDesc": "可以查看和評論記錄,但無法編輯任何內容", "viewerDesc": "可以查看記錄但無法編輯任何內容", "addUser": "新增使用者", "staticRoleInfo": "無法編輯系統定義的角色", "exportZip": "將專案中繼資料匯出為 ZIP 檔案並下載。", "importZip": "匯入專案中繼資料 ZIP 檔案並重新啟動。", "importText": "透過上傳中繼資料 ZIP 檔案來匯入 NocoDB 專案", "metaNoChange": "沒有確定更改", "sqlMigration": "將自動創建架構遷移。創建一個表並刷新此頁面。", "dbConnectionStatus": "環境驗證", "dbConnected": "連線成功", "notifications": { "no_new": "沒有新通知", "clear": "清除" }, "sponsor": { "header": "你可以幫助我們!", "message": "我們是一支小型團隊,全職工作,使Nocodb開放來源。我們相信一個像Nocodb這樣的工具應該在互聯網上的每個問題求解器上自由提供。" }, "loginMsg": "登入 NocoDB", "passwordRecovery": { "message_1": "請填入您註冊時使用的電子信箱地址。", "message_2": "我們將傳給您一封電子郵件,其中包含重設密碼的連結。", "success": "請確認您的電子郵件以重設密碼" }, "signUp": { "superAdmin": "您將是「超級管理員」", "alreadyHaveAccount": "已經有帳號了?", "workEmail": "輸入您的工作電子信箱地址", "enterPassword": "輸入您的密碼", "forgotPassword": "忘記密碼?", "dontHaveAccount": "沒有帳號?" }, "addView": { "grid": "新增網格檢視", "gallery": "新增相簿檢視", "form": "新增表單檢視", "kanban": "新增看板檢視", "map": "新增地圖檢視", "calendar": "新增日曆檢視" }, "tablesMetadataInSync": "表中繼資料同步", "addMultipleUsers": "您可以添加多個逗號(,)分隔的電子郵件", "enterTableName": "輸入表名", "enterLayoutName": "Enter Layout name", "enterDashboardName": "Enter Dashboard name", "defaultColumns": "Default fields", "addDefaultColumns": "添加默認列", "tableNameInDb": "資料庫中保存的表名", "airtable": { "credentials": "在哪裡找到這個?" }, "import": { "clickOrDrag": "點擊或拖動文件到此區域上傳" }, "metaDataRecreated": "表中繼資料重建成功", "invalidCredentials": "無效憑證", "downloadingMoreFiles": "下載更多檔案", "copiedToClipboard": "複製到剪貼簿", "requriedFieldsCantBeMoved": "必填欄位無法移動", "updateNotAllowedWithoutPK": "無主鍵的表不允許更新", "autoIncFieldNotEditable": "自動遞增欄位不可編輯", "editingPKnotSupported": "不支援編輯主鍵", "deletedCache": "刪除快取成功", "cacheEmpty": "快取是空的", "exportedCache": "匯出快取成功", "valueAlreadyInList": "此值已在列表中", "noColumnsToUpdate": "No columns to update", "tableDeleted": "刪除資料表成功", "layoutDeleted": "Deleted layout successfully", "generatePublicShareableReadonlyBase": "產生可公開分享的唯讀資料庫", "deleteViewConfirmation": "是否確定要刪除此檢視?", "deleteLayoutConfirmation": "Are you sure you want to delete this Layout?", "deleteTableConfirmation": "你想刪除此資料表", "showM2mTables": "顯示多對多資料表", "showM2mTablesDesc": "透過交叉表支援多對多關係,默認情況下此選項是隱藏的。啟用此選項以列出所有這樣的表,以及現有的表格。", "showNullInCells": "在儲存格中顯示 NULL", "showNullInCellsDesc": "在包含 NULL 值的儲存格中顯示 \"NULL\" 標籤,這有助於與包含空字串的儲存格區分開來。", "showNullAndEmptyInFilter": "在篩選器中顯示 NULL 和 EMPTY", "showNullAndEmptyInFilterDesc": "啟用 '額外' 過濾器來區分包含 NULL 和空字串的欄位。默認支持空白,將 NULL 和空字符串視為相同。", "deleteKanbanStackConfirmation": "刪除此類別也將從 `{groupingField}` 中刪除選項 `{stackToBeDeleted}`。記錄將移至未分類的類別。", "computedFieldEditWarning": "Computed field: contents are read-only. Use column edit menu to reconfigure", "computedFieldDeleteWarning": "Computed field: contents are read-only. Unable to clear content.", "noMoreRecords": "已無更多紀錄", "tokenNameNotEmpty": "Token name should not be empty", "tokenNameMaxLength": "Token name should not be more than 255 characters", "dbNameRequired": "Database name is required", "wsNameRequired": "Workspace name required", "wsNameMinLength": "Workspace name must be at least 3 characters long", "wsNameMaxLength": "Workspace name must be at most 50 characters long", "wsDeleteDlg": "Delete this workspace and all it’s contents.", "userConfirmation": "I understand that this action is irreversible", "pageNotFound": "Page Not Found", "makeLineBreak": "to make a line break", "goToPrevious": "Go to previous", "goToNext": "Go to next", "thankYou": "Thank you!", "submittedFormData": "You have successfully submitted the form data.", "editingSystemKeyNotSupported": "Editing system key not supported", "notAvailableAtTheMoment": "Not available at the moment" }, "error": { "nameRequired": "Name Required", "nameMinLength": "Name must be at least 2 characters long", "nameMaxLength": "Name must be at most 60 characters long", "viewNameRequired": "View name is required", "nameMaxLength256": "Name must be at most 256 characters long", "viewNameUnique": "View name should be unique", "searchProject": "您的搜尋 {search} 找不到結果", "invalidChar": "資料夾路徑有無效字元。", "invalidDbCredentials": "資料庫憑證無效。", "unableToConnectToDb": "無法連線至資料庫。請檢查您的資料庫是否已經上線。", "invalidYear": "Invalid year", "userDoesntHaveSufficientPermission": "使用者不存在,或者是無權建立結構。", "dbConnectionStatus": "資料庫參數無效", "dbConnectionFailed": "連線失敗:", "nullFilterExists": "Null filter exists. Please remove them", "signUpRules": { "emailRequired": "Email is required", "emailInvalid": "電子信箱地址格式錯誤", "passwdRequired": "密碼為必填", "passwdLength": "您的密碼應至少有 8 個字元", "passwdMismatch": "密碼不匹配", "completeRuleSet": "密碼必須含有至少 8 個字元,其中有一個大寫字母、一個數字和一個特殊字元", "atLeast8Char": "至少 8 個字元", "atLeastOneUppercase": "一個大寫字母", "atLeastOneNumber": "一個數字", "atLeastOneSpecialChar": "一個特殊字元", "allowedSpecialCharList": "允許特殊字元列表", "invalidEmails": "Invalid emails", "invalidEmail": "Invalid Email" }, "invalidURL": "無效的連結", "invalidEmail": "無效的電子郵件", "internalError": "發生內部錯誤", "templateGeneratorNotFound": "無法找到模板生成器!", "fileUploadFailed": "上傳文件失敗", "primaryColumnUpdateFailed": "Failed to update primary column", "formDescriptionTooLong": "表單描述資料過長", "columnsRequired": "Following columns are required", "selectAtleastOneColumn": "至少必須選擇一個欄位", "columnDescriptionNotFound": "Cannot find the destination column for", "duplicateMappingFound": "找到重複的映射,請移除其中一個映射", "nullValueViolatesNotNull": "Null 值違反不可為 Null 限制條件", "sourceHasInvalidNumbers": "來源資料包含無效的數字", "sourceHasInvalidBoolean": "來源資料包含無效的布林值", "invalidForm": "無效的表單", "formValidationFailed": "表單驗證失敗", "youHaveBeenSignedOut": "您已登出", "failedToLoadList": "加載清單失敗", "failedToLoadChildrenList": "加載子清單失敗", "deleteFailed": "刪除失敗", "unlinkFailed": "解除連結失敗", "rowUpdateFailed": "資料更新失敗", "deleteRowFailed": "刪除資料失敗", "setFormDataFailed": "設置表單資料失敗", "formViewUpdateFailed": "更新表單視圖失敗", "tableNameRequired": "資料表名稱必填", "nameShouldStartWithAnAlphabetOr_": "名稱必須用 英文字母 或 _ 當開頭", "followingCharactersAreNotAllowed": "以下字元不允許", "columnNameRequired": "欄位名稱必填", "duplicateColumnName": "Duplicate field name", "duplicateSystemColumnName": "Name already used for system field", "uiDataTypeRequired": "UI data type is required", "columnNameExceedsCharacters": "The length of column name exceeds the max {value} characters", "projectNameExceeds50Characters": "專案名稱超過 50 個字元", "projectNameCannotStartWithSpace": "專案名稱不能有空白開頭", "requiredField": "必填欄位", "ipNotAllowed": "不允許的 IP", "targetFileIsNotAnAcceptedFileType": "不受支持的檔案類型", "theAcceptedFileTypeIsCsv": "受支持的檔案類型是 .csv", "theAcceptedFileTypesAreXlsXlsxXlsmOdsOts": "受支持的檔案類型包括 .xls、.xlsx、.xlsm、.ods 和 .ots", "parameterKeyCannotBeEmpty": "參數鍵不可為空", "duplicateParameterKeysAreNotAllowed": "不允許重複的參數鍵", "fieldRequired": "{value} 不能為空", "projectNotAccessible": "Project not accessible", "copyToClipboardError": "複製到剪貼簿失敗", "pasteFromClipboardError": "Failed to paste from clipboard", "multiFieldSaveValidation": "Please complete the configuration of all fields before saving", "somethingWentWrong": "Something went wrong" }, "toast": { "exportMetadata": "專案中繼資料已成功匯出", "importMetadata": "專案中繼資料已成功匯入", "clearMetadata": "專案中繼資料已成功清除", "stopProject": "專案成功停止", "startProject": "專案成功啟動", "restartProject": "專案成功重新啟動", "deleteProject": "專案已成功刪除", "authToken": "驗證權杖已複製到剪貼簿", "projInfo": "已將專案資訊複製到剪貼簿", "inviteUrlCopy": "已將邀請連結複製到剪貼簿", "createView": "成功建立檢視", "formEmailSMTP": "請啟用 App Store 中的 SMTP 外掛程式以啟用電子郵件通知", "collabView": "成功轉換為協作視圖", "lockedView": "成功轉換為鎖定視圖", "futureRelease": "即將推出!" }, "success": { "licenseKeyUpdated": "License Key Updated", "columnDuplicated": "Column duplicated successfully", "rowDuplicatedWithoutSavedYet": "Row duplicated (not saved)", "updatedUIACL": "更新表格的 UI 存取控制清單成功", "pluginUninstalled": "外掛移除安裝成功", "pluginSettingsSaved": "外掛設定儲存成功", "pluginTested": "外掛設定測試成功", "tableRenamed": "資料表重新命名成功", "layoutRenamed": "Layout renamed successfully", "viewDeleted": "檢視刪除成功", "primaryColumnUpdated": "Successfully updated as primary column", "tableDataExported": "成功匯出所有表格資料", "updated": "成功更新", "sharedViewDeleted": "刪除共享視圖成功", "userDeleted": "使用者已成功删除", "viewRenamed": "檢視重新命名成功", "tokenGenerated": "Token 產生成功", "tokenDeleted": "Token 刪除成功", "userAddedToProject": "專案增加使用者成功", "userAdded": "新增使用者成功", "userDeletedFromProject": "專案移除使用者成功", "inviteEmailSent": "邀請郵件發送成功", "inviteURLCopied": "邀請連結已複製到剪貼簿", "commentCopied": "評論已複製到剪貼簿", "passwordResetURLCopied": "密碼重置連結已複製到剪貼簿", "shareableURLCopied": "已複製共享的資料庫 URL 到剪貼簿!", "embeddableHTMLCodeCopied": "已複製嵌入 HTML 代碼!", "userDetailsUpdated": "成功更新使用者資料", "tableDataImported": "成功匯入表格資料", "webhookUpdated": "Webhook 詳情更新成功", "webhookDeleted": "Hook 刪除成功", "webhookTested": "Webhook 測試成功", "columnUpdated": "欄位已更新", "columnCreated": "欄位已建立", "passwordChanged": "密碼已更新,請重新登入。", "settingsSaved": "設定已成功儲存", "roleUpdated": "角色已成功更新" } } }
packages/nc-gui/lang/zh-Hant.json
0
https://github.com/nocodb/nocodb/commit/bd6115eb5eb53d7d1d30a351bbfb234b2adffe8e
[ 0.00023948424495756626, 0.00017398713680449873, 0.00016642268747091293, 0.00017397383635398, 0.00000636298591416562 ]
{ "id": 0, "code_window": [ "import { ViewTypes, isCreatedOrLastModifiedByCol, isSystemColumn } from 'nocodb-sdk'\n", "import type { ColumnType, GridColumnReqType, GridColumnType, MapType, TableType, ViewType } from 'nocodb-sdk'\n", "import type { ComputedRef, Ref } from 'vue'\n", "import { computed, ref, storeToRefs, useBase, useNuxtApp, useRoles, useUndoRedo, watch } from '#imports'\n", "import type { Field } from '#imports'\n", "\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { ViewTypes, isCreatedOrLastModifiedByCol, isMMSystemCol, isSystemColumn } from 'nocodb-sdk'\n" ], "file_path": "packages/nc-gui/composables/useViewColumns.ts", "type": "replace", "edit_start_line_idx": 0 }
--- title: "Lookup" description: "Understanding Lookup Column!" --- ## Lookup ### Example organization structure Consider an organization with - 5 departments (company departments), each department has a team name & associated team code. Each `Team` **has many** `Employees` - relationship has been defined using `LinkToAnotherRecord` or `Links`column - 5 employees working at different departments ![Screenshot 2022-09-09 at 12 57 32 PM](https://user-images.githubusercontent.com/86527202/189295738-a4197818-f7d7-4769-acad-13b6d05afe7e.png) <!-- ![Screenshot 2022-09-09 at 12 18 40 PM](https://user-images.githubusercontent.com/86527202/189291758-21c81ec6-7967-45f1-b49c-b3b6f2701edc.png) --> <!-- ![Screenshot 2022-09-09 at 12 19 16 PM](https://user-images.githubusercontent.com/86527202/189291766-f619078e-0881-4531-a3f8-ede22269f6fc.png) --> Now, let's explore procedure to retrieve team-code information in Employee table using **LOOKUP** columns ### Configuring a lookup column #### 1. Add new column : Click on '+' icon to the left of column headers in Employee table #### 2. Feed column name #### 3. Select column type as 'Lookup' #### 4. Choose child table #### 5. Select child column #### 6. Click on 'Save' ![Screenshot 2022-09-09 at 12 21 13 PM](https://user-images.githubusercontent.com/86527202/189291720-642a6a96-0b3d-4eaa-886a-20d33a967644.png) Required information is now populated in the newly created column ![Screenshot 2022-09-09 at 12 26 06 PM](https://user-images.githubusercontent.com/86527202/189291679-09503e32-9146-41fa-b28c-d900f2dc35a4.png) ## Additional notes - Nested 'Lookup' supported: a Lookup field can have its child column datatype as Lookup (or Rollup).
packages/noco-docs/versioned_docs/version-0.109.7/030.setup-and-usages/070.lookup.md
0
https://github.com/nocodb/nocodb/commit/bd6115eb5eb53d7d1d30a351bbfb234b2adffe8e
[ 0.00016836337454151362, 0.00016572547610849142, 0.00016238981334026903, 0.00016607432917226106, 0.000002146865199392778 ]
{ "id": 0, "code_window": [ "import { ViewTypes, isCreatedOrLastModifiedByCol, isSystemColumn } from 'nocodb-sdk'\n", "import type { ColumnType, GridColumnReqType, GridColumnType, MapType, TableType, ViewType } from 'nocodb-sdk'\n", "import type { ComputedRef, Ref } from 'vue'\n", "import { computed, ref, storeToRefs, useBase, useNuxtApp, useRoles, useUndoRedo, watch } from '#imports'\n", "import type { Field } from '#imports'\n", "\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { ViewTypes, isCreatedOrLastModifiedByCol, isMMSystemCol, isSystemColumn } from 'nocodb-sdk'\n" ], "file_path": "packages/nc-gui/composables/useViewColumns.ts", "type": "replace", "edit_start_line_idx": 0 }
module.exports = { tn: 'country', columns: [{ cn: 'country_id', type: 'integer', dt: 'smallint', rqd: true, un: true, pk: true, ai: true, validate: { func: [], args: [], msg: [] }, }, { cn: 'country', type: 'string', dt: 'varchar', rqd: true, validate: { func: [], args: [], msg: [] }, }, { cn: 'last_update', type: 'timestamp', dt: 'timestamp', rqd: true, default: "CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP", validate: { func: [], args: [], msg: [] }, }, ], pks: [], hasMany: [{ "cstn": "fk_city_country", "tn": "city", "cn": "country_id", "puc": 1, "rtn": "country", "rcn": "country_id", "mo": "NONE", "UR": "CASCADE", "dr": "RESTRICT", "ts": "sakila" }], belongsTo: [] }
packages/nocodb/src/db/sql-data-mapper/__tests__/models/country.meta.js
0
https://github.com/nocodb/nocodb/commit/bd6115eb5eb53d7d1d30a351bbfb234b2adffe8e
[ 0.00017589829803910106, 0.0001743990578688681, 0.0001725702459225431, 0.00017447561549488455, 0.0000011715234222720028 ]
{ "id": 1, "code_window": [ " }, {})\n", "\n", " fields.value = meta.value?.columns\n", " ?.filter((column: ColumnType) => {\n", " // filter created by and last modified by system columns\n", " if (isCreatedOrLastModifiedByCol(column) && column.system) return false\n", " return true\n", " })\n", " .map((column: ColumnType) => {\n", " const currentColumnField = fieldById[column.id!] || {}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if ((isCreatedOrLastModifiedByCol(column) || isMMSystemCol(column)) && column.system) return false\n" ], "file_path": "packages/nc-gui/composables/useViewColumns.ts", "type": "replace", "edit_start_line_idx": 74 }
export * from '~/lib/XcUIBuilder'; export * from '~/lib/XcNotification'; export * from '~/lib/Api'; export * from '~/lib/columnRules'; export * from '~/lib/sqlUi'; export * from '~/lib/globals'; export * from '~/lib/helperFunctions'; export * from '~/lib/enums'; export * from '~/lib/formulaHelpers'; export { default as UITypes, UITypesName, numericUITypes, isNumericCol, isVirtualCol, isLinksOrLTAR, isCreatedOrLastModifiedTimeCol, isCreatedOrLastModifiedByCol, } from '~/lib/UITypes'; export { default as CustomAPI, FileType } from '~/lib/CustomAPI'; export { default as TemplateGenerator } from '~/lib/TemplateGenerator'; export * from '~/lib/passwordHelpers'; export * from '~/lib/mergeSwaggerSchema'; export * from '~/lib/dateTimeHelper';
packages/nocodb-sdk/src/lib/index.ts
1
https://github.com/nocodb/nocodb/commit/bd6115eb5eb53d7d1d30a351bbfb234b2adffe8e
[ 0.0008512191125191748, 0.0003996470768470317, 0.0001731484371703118, 0.0001745737827150151, 0.00031931017292663455 ]
{ "id": 1, "code_window": [ " }, {})\n", "\n", " fields.value = meta.value?.columns\n", " ?.filter((column: ColumnType) => {\n", " // filter created by and last modified by system columns\n", " if (isCreatedOrLastModifiedByCol(column) && column.system) return false\n", " return true\n", " })\n", " .map((column: ColumnType) => {\n", " const currentColumnField = fieldById[column.id!] || {}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if ((isCreatedOrLastModifiedByCol(column) || isMMSystemCol(column)) && column.system) return false\n" ], "file_path": "packages/nc-gui/composables/useViewColumns.ts", "type": "replace", "edit_start_line_idx": 74 }
<script setup lang="ts"> import Draggable from 'vuedraggable' import { UITypes } from 'nocodb-sdk' import InfiniteLoading from 'v3-infinite-loading' import { IsKanbanInj, enumColor, iconMap, onMounted, useColumnCreateStoreOrThrow, useVModel } from '#imports' interface Option { color: string title: string id?: string fk_colum_id?: string order?: number } const props = defineProps<{ value: any fromTableExplorer?: boolean }>() const emit = defineEmits(['update:value']) const vModel = useVModel(props, 'value', emit) const { setAdditionalValidations, validateInfos } = useColumnCreateStoreOrThrow() // const { base } = storeToRefs(useBase()) const { optionsMagic: _optionsMagic } = useNocoEe() const optionsWrapperDomRef = ref<HTMLElement>() const options = ref<(Option & { status?: 'remove'; index?: number })[]>([]) const isAddingOption = ref(false) // TODO: Implement proper top and bottom virtual scrolling const OPTIONS_PAGE_COUNT = 20 const loadedOptionAnchor = ref(OPTIONS_PAGE_COUNT) const isReverseLazyLoad = ref(false) const renderedOptions = ref<(Option & { status?: 'remove'; index?: number })[]>([]) const savedDefaultOption = ref<Option | null>(null) const savedCdf = ref<string | null>(null) const colorMenus = ref<any>({}) const colors = ref(enumColor.light) const defaultOption = ref() const isKanban = inject(IsKanbanInj, ref(false)) const { t } = useI18n() const validators = { colOptions: [ { type: 'object', fields: { options: { validator: (_: any, _opt: any) => { return new Promise<void>((resolve, reject) => { for (const opt of options.value) { if ((opt as any).status === 'remove') continue if (!opt.title.length) { return reject(new Error(t('msg.selectOption.cantBeNull'))) } if (vModel.value.uidt === UITypes.MultiSelect && opt.title.includes(',')) { return reject(new Error(t('msg.selectOption.multiSelectCantHaveCommas'))) } if (options.value.filter((el) => el.title === opt.title && (el as any).status !== 'remove').length > 1) { return reject(new Error(t('msg.selectOption.cantHaveDuplicates'))) } } resolve() }) }, }, }, }, ], } // we use a correct syntax from async-validator but causes a type mismatch on antdv so we cast any setAdditionalValidations({ ...validators, } as any) onMounted(() => { if (!vModel.value.colOptions?.options) { vModel.value.colOptions = { options: [], } } isReverseLazyLoad.value = false options.value = vModel.value.colOptions.options let indexCounter = 0 options.value.map((el) => { el.index = indexCounter++ return el }) loadedOptionAnchor.value = Math.min(loadedOptionAnchor.value, options.value.length) renderedOptions.value = [...options.value].slice(0, loadedOptionAnchor.value) // Support for older options for (const op of options.value.filter((el) => el.order === null)) { op.title = op.title.replace(/^'/, '').replace(/'$/, '') } if (vModel.value.cdf && typeof vModel.value.cdf === 'string') { const fndDefaultOption = options.value.find((el) => el.title === vModel.value.cdf) if (!fndDefaultOption) { vModel.value.cdf = vModel.value.cdf.replace(/^'/, '').replace(/'$/, '') } } const fndDefaultOption = options.value.find((el) => el.title === vModel.value.cdf) if (fndDefaultOption) { defaultOption.value = fndDefaultOption } }) const getNextColor = () => { let tempColor = colors.value[0] if (options.value.length && options.value[options.value.length - 1].color) { const lastColor = colors.value.indexOf(options.value[options.value.length - 1].color) tempColor = colors.value[(lastColor + 1) % colors.value.length] } return tempColor } const addNewOption = () => { isAddingOption.value = true const tempOption = { title: '', color: getNextColor(), index: options.value.length, } options.value.push(tempOption) isReverseLazyLoad.value = true loadedOptionAnchor.value = options.value.length - OPTIONS_PAGE_COUNT loadedOptionAnchor.value = Math.max(loadedOptionAnchor.value, 0) renderedOptions.value = options.value.slice(loadedOptionAnchor.value, options.value.length) optionsWrapperDomRef.value!.scrollTop = optionsWrapperDomRef.value!.scrollHeight nextTick(() => { // Last child doesnt work for query selector setTimeout(() => { const doms = document.querySelectorAll(`.nc-col-option-select-option .nc-select-col-option-select-option`) const dom = doms[doms.length - 1] as HTMLInputElement if (dom) { dom.focus() } }, 150) optionsWrapperDomRef.value!.scrollTop = optionsWrapperDomRef.value!.scrollHeight isAddingOption.value = false }) } // const optionsMagic = async () => { // await _optionsMagic(base, formState, getNextColor, options.value, renderedOptions.value) // } const syncOptions = () => { // set initial colOptions if not set vModel.value.colOptions = vModel.value.colOptions || {} vModel.value.colOptions.options = options.value .filter((op) => op.status !== 'remove') .sort((a, b) => { const renderA = renderedOptions.value.findIndex((el) => a.index !== undefined && el.index === a.index) const renderB = renderedOptions.value.findIndex((el) => a.index !== undefined && el.index === b.index) if (renderA === -1 || renderB === -1) return 0 return renderA - renderB }) .map((op) => { const { index: _i, status: _s, ...rest } = op return rest }) } const removeRenderedOption = (index: number) => { const renderedOption = renderedOptions.value[index] if (renderedOption.index === undefined || isNaN(renderedOption.index)) return const option = options.value[renderedOption.index] renderedOption.status = 'remove' option.status = 'remove' syncOptions() const optionId = renderedOptions.value[index]?.id if (optionId === defaultOption.value?.id) { savedDefaultOption.value = { ...defaultOption.value } savedCdf.value = vModel.value.cdf defaultOption.value = null vModel.value.cdf = null } } const optionChanged = (changedId: string) => { if (changedId && changedId === defaultOption.value?.id) { vModel.value.cdf = defaultOption.value.title } syncOptions() } const undoRemoveRenderedOption = (index: number) => { const renderedOption = renderedOptions.value[index] if (renderedOption.index === undefined || isNaN(renderedOption.index)) return const option = options.value[renderedOption.index] renderedOption.status = undefined option.status = undefined syncOptions() const optionId = renderedOptions.value[index]?.id if (optionId === savedDefaultOption.value?.id) { defaultOption.value = { ...savedDefaultOption.value } vModel.value.cdf = savedCdf.value savedDefaultOption.value = null savedCdf.value = null } } // focus last created input // watch(inputs, () => { // if (inputs.value?.$el) { // inputs.value.$el.focus() // } // }) // Removes the Select Option from cdf if the option is removed watch(vModel.value, (next) => { const cdfs = (next.cdf ?? '').toString().split(',') const values = (next.colOptions.options ?? []).map((col) => { return col.title.replace(/^'/, '').replace(/'$/, '') }) const newCdf = cdfs.filter((c: string) => values.includes(c)).join(',') next.cdf = newCdf.length === 0 ? null : newCdf }) const loadListDataReverse = async ($state: any) => { if (isAddingOption.value) return if (loadedOptionAnchor.value === 0) { $state.complete() return } $state.loading() loadedOptionAnchor.value -= OPTIONS_PAGE_COUNT loadedOptionAnchor.value = Math.max(loadedOptionAnchor.value, 0) renderedOptions.value = options.value.slice(loadedOptionAnchor.value, options.value.length) optionsWrapperDomRef.value!.scrollTop = optionsWrapperDomRef.value!.scrollTop + 100 if (loadedOptionAnchor.value === 0) { $state.complete() return } $state.loaded() } const loadListData = async ($state: any) => { if (isAddingOption.value) return if (loadedOptionAnchor.value === options.value.length) { return $state.complete() } $state.loading() loadedOptionAnchor.value += OPTIONS_PAGE_COUNT loadedOptionAnchor.value = Math.min(loadedOptionAnchor.value, options.value.length) renderedOptions.value = options.value.slice(0, loadedOptionAnchor.value) if (loadedOptionAnchor.value === options.value.length) { return $state.complete() } $state.loaded() } </script> <template> <div class="w-full"> <div ref="optionsWrapperDomRef" class="nc-col-option-select-option overflow-x-auto scrollbar-thin-dull" :style="{ maxHeight: props.fromTableExplorer ? 'calc(100vh - (var(--topbar-height) * 3.6) - 320px)' : 'calc(min(30vh, 250px))', }" > <InfiniteLoading v-if="isReverseLazyLoad" v-bind="$attrs" @infinite="loadListDataReverse"> <template #spinner> <div class="flex flex-row w-full justify-center mt-2"> <GeneralLoader /> </div> </template> <template #complete> <span></span> </template> </InfiniteLoading> <Draggable :list="renderedOptions" item-key="id" handle=".nc-child-draggable-icon" @change="syncOptions"> <template #item="{ element, index }"> <div class="flex py-1 items-center nc-select-option"> <div class="flex items-center w-full" :data-testid="`select-column-option-${index}`" :class="{ removed: element.status === 'remove' }" > <component :is="iconMap.dragVertical" v-if="!isKanban" small class="nc-child-draggable-icon handle" :data-testid="`select-option-column-handle-icon-${element.title}`" /> <a-dropdown v-model:visible="colorMenus[index]" :trigger="['click']" overlay-class-name="nc-dropdown-select-color-options rounded-md overflow-hidden border-1 border-gray-200 " > <template #overlay> <LazyGeneralColorPicker v-model="element.color" :pick-button="true" @close-modal="colorMenus[index] = false" @input="(el:string) => (element.color = el)" /> </template> <MdiArrowDownDropCircle class="mr-2 text-[1.5em] outline-0 hover:!text-[1.75em] cursor-pointer" :class="{ 'text-[1.75em]': colorMenus[index] }" :style="{ color: element.color }" /> </a-dropdown> <a-input v-model:value="element.title" class="caption !rounded-lg nc-select-col-option-select-option" :data-testid="`select-column-option-input-${index}`" :disabled="element.status === 'remove'" @keydown.enter.prevent="element.title?.trim() && addNewOption()" @change="optionChanged(element.id)" /> </div> <div v-if="element.status !== 'remove'" :data-testid="`select-column-option-remove-${index}`" class="ml-1 hover:!text-black-500 text-gray-500 cursor-pointer hover:bg-gray-50 py-1 px-1.5 rounded-md" @click="removeRenderedOption(index)" > <component :is="iconMap.close" class="-mt-0.25" /> </div> <MdiArrowULeftBottom v-else class="ml-2 hover:!text-black-500 text-gray-500 cursor-pointer" :data-testid="`select-column-option-remove-undo-${index}`" @click="undoRemoveRenderedOption(index)" /> </div> </template> </Draggable> <InfiniteLoading v-if="!isReverseLazyLoad" v-bind="$attrs" @infinite="loadListData"> <template #spinner> <div class="flex flex-row w-full justify-center mt-2"> <GeneralLoader /> </div> </template> <template #complete> <span></span> </template> </InfiniteLoading> </div> <div v-if="validateInfos?.colOptions?.help?.[0]?.[0]" class="text-error text-[10px] mb-1 mt-2"> {{ validateInfos.colOptions.help[0][0] }} </div> <a-button type="dashed" class="w-full caption mt-2" @click="addNewOption()"> <div class="flex items-center"> <component :is="iconMap.plus" /> <span class="flex-auto">Add option</span> </div> </a-button> <!-- <div v-if="isEeUI" class="w-full cursor-pointer" @click="optionsMagic()"> <GeneralIcon icon="magic" :class="{ 'nc-animation-pulse': loadMagic }" class="w-full flex mt-2 text-orange-400" /> </div> --> </div> </template> <style scoped> .removed { position: relative; } .removed:after { position: absolute; left: 0; top: 50%; height: 1px; background: #ccc; content: ''; width: calc(100% + 5px); display: block; } </style>
packages/nc-gui/components/smartsheet/column/SelectOptions.vue
0
https://github.com/nocodb/nocodb/commit/bd6115eb5eb53d7d1d30a351bbfb234b2adffe8e
[ 0.0051118857227265835, 0.0002831841993611306, 0.00016323370800819248, 0.00017001567175611854, 0.000736378482542932 ]
{ "id": 1, "code_window": [ " }, {})\n", "\n", " fields.value = meta.value?.columns\n", " ?.filter((column: ColumnType) => {\n", " // filter created by and last modified by system columns\n", " if (isCreatedOrLastModifiedByCol(column) && column.system) return false\n", " return true\n", " })\n", " .map((column: ColumnType) => {\n", " const currentColumnField = fieldById[column.id!] || {}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if ((isCreatedOrLastModifiedByCol(column) || isMMSystemCol(column)) && column.system) return false\n" ], "file_path": "packages/nc-gui/composables/useViewColumns.ts", "type": "replace", "edit_start_line_idx": 74 }
<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M3 6H12.75M3 6V5H12.75V6M3 6V7M12.75 6V7M3 15H12.75M3 19.5H12.75M3 7H12.75M3 7V7.875M12.75 7V7.875M12.75 8.75H3M12.75 8.75V7.875M12.75 8.75V9.625M3 8.75V7.875M3 8.75V9.625M3 7.875H12.75M12.75 9.625V10.5H3V9.625M12.75 9.625H3" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> <path d="M18.5 5V19.5M18.5 5L15.5 8M18.5 5L21.5 8M18.5 19.5L15.5 16.5M18.5 19.5L21.5 16.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> </svg>
packages/nc-gui/assets/nc-icons/row-height-medium.svg
0
https://github.com/nocodb/nocodb/commit/bd6115eb5eb53d7d1d30a351bbfb234b2adffe8e
[ 0.00017439626390114427, 0.00017439626390114427, 0.00017439626390114427, 0.00017439626390114427, 0 ]
{ "id": 1, "code_window": [ " }, {})\n", "\n", " fields.value = meta.value?.columns\n", " ?.filter((column: ColumnType) => {\n", " // filter created by and last modified by system columns\n", " if (isCreatedOrLastModifiedByCol(column) && column.system) return false\n", " return true\n", " })\n", " .map((column: ColumnType) => {\n", " const currentColumnField = fieldById[column.id!] || {}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if ((isCreatedOrLastModifiedByCol(column) || isMMSystemCol(column)) && column.system) return false\n" ], "file_path": "packages/nc-gui/composables/useViewColumns.ts", "type": "replace", "edit_start_line_idx": 74 }
import type { AttachmentType } from 'nocodb-sdk' import RenameFile from './RenameFile.vue' import { ColumnInj, EditModeInj, IsFormInj, IsPublicInj, MetaInj, NOCO, ReadonlyInj, computed, inject, isImage, message, parseProp, ref, storeToRefs, useApi, useAttachment, useBase, useFileDialog, useI18n, useInjectionState, watch, } from '#imports' import MdiPdfBox from '~icons/mdi/pdf-box' import MdiFileWordOutline from '~icons/mdi/file-word-outline' import MdiFilePowerpointBox from '~icons/mdi/file-powerpoint-box' import MdiFileExcelOutline from '~icons/mdi/file-excel-outline' import IcOutlineInsertDriveFile from '~icons/ic/outline-insert-drive-file' export const [useProvideAttachmentCell, useAttachmentCell] = useInjectionState( (updateModelValue: (data: string | Record<string, any>[]) => void) => { const isReadonly = inject(ReadonlyInj, ref(false)) const { t } = useI18n() const isPublic = inject(IsPublicInj, ref(false)) const isForm = inject(IsFormInj, ref(false)) const meta = inject(MetaInj, ref()) const column = inject(ColumnInj, ref()) const editEnabled = inject(EditModeInj, ref(false)) /** keep user selected File object */ const storedFiles = ref<AttachmentType[]>([]) const attachments = ref<AttachmentType[]>([]) const modalVisible = ref(false) /** for image carousel */ const selectedImage = ref() const { base } = storeToRefs(useBase()) const { api, isLoading } = useApi() const { files, open } = useFileDialog() const { appInfo } = useGlobal() const { getAttachmentSrc } = useAttachment() const defaultAttachmentMeta = { ...(appInfo.value.ee && { // Maximum Number of Attachments per cell maxNumberOfAttachments: Math.max(1, +appInfo.value.ncMaxAttachmentsAllowed || 50) || 50, // Maximum File Size per file maxAttachmentSize: Math.max(1, +appInfo.value.ncMaxAttachmentsAllowed || 20) || 20, supportedAttachmentMimeTypes: ['*'], }), } /** our currently visible items, either the locally stored or the ones from db, depending on isPublic & isForm status */ const visibleItems = computed<any[]>(() => (isPublic.value && isForm.value ? storedFiles.value : attachments.value)) /** for bulk download */ const selectedVisibleItems = ref<boolean[]>(Array.from({ length: visibleItems.value.length }, () => false)) /** remove a file from our stored attachments (either locally stored or saved ones) */ function removeFile(i: number) { if (isPublic.value) { storedFiles.value.splice(i, 1) attachments.value.splice(i, 1) selectedVisibleItems.value.splice(i, 1) updateModelValue(storedFiles.value) } else { attachments.value.splice(i, 1) selectedVisibleItems.value.splice(i, 1) updateModelValue(JSON.stringify(attachments.value)) } } /** save a file on select / drop, either locally (in-memory) or in the db */ async function onFileSelect(selectedFiles: FileList | File[]) { if (!selectedFiles.length) return const attachmentMeta = { ...defaultAttachmentMeta, ...parseProp(column?.value?.meta), } const newAttachments = [] const files: File[] = [] for (const file of selectedFiles) { if (appInfo.value.ee) { // verify number of files if (visibleItems.value.length + selectedFiles.length > attachmentMeta.maxNumberOfAttachments) { message.error( `You can only upload at most ${attachmentMeta.maxNumberOfAttachments} file${ attachmentMeta.maxNumberOfAttachments > 1 ? 's' : '' } to this cell.`, ) return } // verify file size if (file.size > attachmentMeta.maxAttachmentSize * 1024 * 1024) { message.error(`The size of ${file.name} exceeds the maximum file size ${attachmentMeta.maxAttachmentSize} MB.`) continue } // verify mime type if ( !attachmentMeta.supportedAttachmentMimeTypes.includes('*') && !attachmentMeta.supportedAttachmentMimeTypes.includes(file.type) && !attachmentMeta.supportedAttachmentMimeTypes.includes(file.type.split('/')[0]) ) { message.error(`${file.name} has the mime type ${file.type} which is not allowed in this column.`) continue } } // this prevent file with same names const isFileNameAlreadyExist = attachments.value.some((el) => el.title === file.name) if (isFileNameAlreadyExist) { message.error( t('labels.duplicateAttachment', { filename: file.name, }), ) return } files.push(file) } if (isPublic.value && isForm.value) { const newFiles = await Promise.all<AttachmentType>( Array.from(files).map( (file) => new Promise<AttachmentType>((resolve) => { const res: { file: File; title: string; mimetype: string; data?: any } = { ...file, file, title: file.name, mimetype: file.type, } if (isImage(file.name, (<any>file).mimetype ?? file.type)) { const reader = new FileReader() reader.onload = (e) => { res.data = e.target?.result resolve(res) } reader.onerror = () => { resolve(res) } reader.readAsDataURL(file) } else { resolve(res) } }), ), ) attachments.value = [...attachments.value, ...newFiles] return updateModelValue(attachments.value) } try { const data = await api.storage.upload( { path: [NOCO, base.value.id, meta.value?.id, column.value?.id].join('/'), }, { files, }, ) newAttachments.push(...data) } catch (e: any) { message.error(e.message || t('msg.error.internalError')) } updateModelValue(JSON.stringify([...attachments.value, ...newAttachments])) } async function renameFile(attachment: AttachmentType, idx: number) { return new Promise<boolean>((resolve) => { const { close } = useDialog(RenameFile, { title: attachment.title, onRename: (newTitle: string) => { attachments.value[idx].title = newTitle updateModelValue(JSON.stringify(attachments.value)) close() resolve(true) }, onCancel: () => { close() resolve(true) }, }) }) } /** save files on drop */ async function onDrop(droppedFiles: FileList | File[] | null) { if (isReadonly.value) return if (droppedFiles) { // set files await onFileSelect(droppedFiles) } } /** bulk download selected files */ async function bulkDownloadFiles() { await Promise.all(selectedVisibleItems.value.map(async (v, i) => v && (await downloadFile(visibleItems.value[i])))) selectedVisibleItems.value = Array.from({ length: visibleItems.value.length }, () => false) } /** download a file */ async function downloadFile(item: AttachmentType) { const src = await getAttachmentSrc(item) if (src) { ;(await import('file-saver')).saveAs(src, item.title) } else { message.error('Failed to download file') } } const FileIcon = (icon: string) => { switch (icon) { case 'mdi-pdf-box': return MdiPdfBox case 'mdi-file-word-outline': return MdiFileWordOutline case 'mdi-file-powerpoint-box': return MdiFilePowerpointBox case 'mdi-file-excel-outline': return MdiFileExcelOutline default: return IcOutlineInsertDriveFile } } watch(files, (nextFiles) => nextFiles && onFileSelect(nextFiles)) return { attachments, visibleItems, isPublic, isForm, isReadonly, meta, column, editEnabled, isLoading, api, open: () => open(), onDrop, modalVisible, FileIcon, removeFile, renameFile, downloadFile, updateModelValue, selectedImage, selectedVisibleItems, storedFiles, bulkDownloadFiles, defaultAttachmentMeta, } }, 'useAttachmentCell', )
packages/nc-gui/components/cell/attachment/utils.ts
0
https://github.com/nocodb/nocodb/commit/bd6115eb5eb53d7d1d30a351bbfb234b2adffe8e
[ 0.0019159173825755715, 0.0003140511689707637, 0.000164560362463817, 0.00017130572814494371, 0.0003981073386967182 ]
{ "id": 2, "code_window": [ " <UITypes>(typeof col === 'object' ? col?.uidt : col)\n", " );\n", "}\n", "\n", "export function isLinksOrLTAR(\n", " colOrUidt: ColumnType | { uidt: UITypes | string } | UITypes | string\n", ") {\n", " return [UITypes.LinkToAnotherRecord, UITypes.Links].includes(\n", " <UITypes>(typeof colOrUidt === 'object' ? colOrUidt?.uidt : colOrUidt)\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function isMMSystemCol(\n", " col: (ColumnReqType | ColumnType) & { system?: number | boolean }\n", ") {\n", " return (\n", " col.system && [UITypes.LinkToAnotherRecord].includes(<UITypes>col.uidt)\n", " );\n", "}\n", "\n" ], "file_path": "packages/nocodb-sdk/src/lib/UITypes.ts", "type": "add", "edit_start_line_idx": 164 }
import { ViewTypes, isCreatedOrLastModifiedByCol, isSystemColumn } from 'nocodb-sdk' import type { ColumnType, GridColumnReqType, GridColumnType, MapType, TableType, ViewType } from 'nocodb-sdk' import type { ComputedRef, Ref } from 'vue' import { computed, ref, storeToRefs, useBase, useNuxtApp, useRoles, useUndoRedo, watch } from '#imports' import type { Field } from '#imports' const [useProvideViewColumns, useViewColumns] = useInjectionState( ( view: Ref<ViewType | undefined>, meta: Ref<TableType | undefined> | ComputedRef<TableType | undefined>, reloadData?: () => void, isPublic = false, ) => { const fields = ref<Field[]>() const filterQuery = ref('') const { $api, $e } = useNuxtApp() const { isUIAllowed } = useRoles() const { isSharedBase } = storeToRefs(useBase()) const isViewColumnsLoading = ref(false) const { addUndo, defineViewScope } = useUndoRedo() const isLocalMode = computed( () => isPublic || !isUIAllowed('viewFieldEdit') || !isUIAllowed('viewFieldEdit') || isSharedBase.value, ) const localChanges = ref<Field[]>([]) const isColumnViewEssential = (column: ColumnType) => { // TODO: consider at some point ti delegate this via a cleaner design pattern to view specific check logic // which could be inside of a view specific helper class (and generalized via an interface) // (on the other hand, the logic complexity is still very low atm - might be overkill) return view.value?.type === ViewTypes.MAP && (view.value?.view as MapType)?.fk_geo_data_col_id === column.id } const metaColumnById = computed<Record<string, ColumnType>>(() => { if (!meta.value?.columns) return {} return (meta.value.columns as ColumnType[]).reduce( (acc, curr) => ({ ...acc, [curr.id!]: curr, }), {}, ) as Record<string, ColumnType> }) const gridViewCols = ref<Record<string, GridColumnType>>({}) const loadViewColumns = async () => { if (!meta || !view) return let order = 1 if (view.value?.id) { const data = (isPublic ? meta.value?.columns : (await $api.dbViewColumn.list(view.value.id)).list) as any[] const fieldById = data.reduce<Record<string, any>>((acc, curr) => { curr.show = !!curr.show return { ...acc, [curr.fk_column_id]: curr, } }, {}) fields.value = meta.value?.columns ?.filter((column: ColumnType) => { // filter created by and last modified by system columns if (isCreatedOrLastModifiedByCol(column) && column.system) return false return true }) .map((column: ColumnType) => { const currentColumnField = fieldById[column.id!] || {} return { title: column.title, fk_column_id: column.id, ...currentColumnField, show: currentColumnField.show || isColumnViewEssential(currentColumnField), order: currentColumnField.order || order++, system: isSystemColumn(metaColumnById?.value?.[currentColumnField.fk_column_id!]), isViewEssentialField: isColumnViewEssential(column), } }) .sort((a: Field, b: Field) => a.order - b.order) if (isLocalMode.value && fields.value) { for (const field of localChanges.value) { const fieldIndex = fields.value.findIndex((f) => f.fk_column_id === field.fk_column_id) if (fieldIndex !== undefined && fieldIndex > -1) { fields.value[fieldIndex] = field fields.value = fields.value.sort((a: Field, b: Field) => a.order - b.order) } } } const colsData: GridColumnType[] = (isPublic.value ? view.value?.columns : fields.value) ?? [] gridViewCols.value = colsData.reduce<Record<string, GridColumnType>>( (o, col) => ({ ...o, [col.fk_column_id as string]: col, }), {}, ) } } const showAll = async (ignoreIds?: any) => { if (isLocalMode.value) { fields.value = fields.value?.map((field: Field) => ({ ...field, show: true, })) reloadData?.() return } if (view?.value?.id) { if (ignoreIds) { await $api.dbView.showAllColumn(view.value.id, { ignoreIds, }) } else { await $api.dbView.showAllColumn(view.value.id) } } await loadViewColumns() reloadData?.() $e('a:fields:show-all') } const hideAll = async (ignoreIds?: any) => { if (isLocalMode.value) { fields.value = fields.value?.map((field: Field) => ({ ...field, show: !!field.isViewEssentialField, })) reloadData?.() return } if (view?.value?.id) { if (ignoreIds) { await $api.dbView.hideAllColumn(view.value.id, { ignoreIds, }) } else { await $api.dbView.hideAllColumn(view.value.id) } } await loadViewColumns() reloadData?.() $e('a:fields:show-all') } const saveOrUpdate = async (field: any, index: number, disableDataReload: boolean = false) => { if (isLocalMode.value && fields.value) { fields.value[index] = field meta.value!.columns = meta.value!.columns?.map((column: ColumnType) => { if (column.id === field.fk_column_id) { return { ...column, ...field, id: field.fk_column_id, } } return column }) localChanges.value.push(field) } if (isUIAllowed('viewFieldEdit')) { if (field.id && view?.value?.id) { await $api.dbViewColumn.update(view.value.id, field.id, field) } else if (view.value?.id) { const insertedField = (await $api.dbViewColumn.create(view.value.id, field)) as any /** update the field in fields if defined */ if (fields.value) fields.value[index] = insertedField return insertedField } } if (!disableDataReload) { await loadViewColumns() reloadData?.() } } const showSystemFields = computed({ get() { return (view.value?.show_system_fields as boolean) || false }, set(v: boolean) { if (view?.value?.id) { if (!isLocalMode.value) { $api.dbView .update(view.value.id, { show_system_fields: v, }) .finally(() => { loadViewColumns() reloadData?.() }) } view.value.show_system_fields = v } $e('a:fields:system-fields') }, }) const filteredFieldList = computed(() => { return ( fields.value?.filter((field: Field) => { if (metaColumnById?.value?.[field.fk_column_id!]?.pv) return true // hide system columns if not enabled if (!showSystemFields.value && isSystemColumn(metaColumnById?.value?.[field.fk_column_id!])) { return false } if (filterQuery.value === '') { return true } else { return field.title.toLowerCase().includes(filterQuery.value.toLowerCase()) } }) || [] ) }) const sortedAndFilteredFields = computed<ColumnType[]>(() => { return (fields?.value ?.filter((field: Field) => { // hide system columns if not enabled if ( !showSystemFields.value && metaColumnById.value && metaColumnById?.value?.[field.fk_column_id!] && isSystemColumn(metaColumnById.value?.[field.fk_column_id!]) && !metaColumnById.value?.[field.fk_column_id!]?.pv ) { return false } return field.show && metaColumnById?.value?.[field.fk_column_id!] }) ?.sort((a: Field, b: Field) => a.order - b.order) ?.map((field: Field) => metaColumnById?.value?.[field.fk_column_id!]) || []) as ColumnType[] }) const toggleFieldVisibility = (checked: boolean, field: any) => { const fieldIndex = fields.value?.findIndex((f) => f.fk_column_id === field.fk_column_id) if (!fieldIndex && fieldIndex !== 0) return addUndo({ undo: { fn: (v: boolean) => { field.show = !v saveOrUpdate(field, fieldIndex) }, args: [checked], }, redo: { fn: (v: boolean) => { field.show = v saveOrUpdate(field, fieldIndex) }, args: [checked], }, scope: defineViewScope({ view: view.value }), }) saveOrUpdate(field, fieldIndex) } // reload view columns when active view changes // or when columns changes(delete/add) watch( [() => view?.value?.id, () => meta.value?.columns], async ([newViewId]) => { // reload only if view belongs to current table if (newViewId && view.value?.fk_model_id === meta.value?.id) { isViewColumnsLoading.value = true try { await loadViewColumns() } catch (e) { console.error(e) } isViewColumnsLoading.value = false } }, { immediate: true }, ) const resizingColOldWith = ref('200px') const updateGridViewColumn = async (id: string, props: Partial<GridColumnReqType>, undo = false) => { if (!undo) { const oldProps = Object.keys(props).reduce<Partial<GridColumnReqType>>((o: any, k) => { if (gridViewCols.value[id][k as keyof GridColumnType]) { if (k === 'width') o[k] = `${resizingColOldWith.value}px` else o[k] = gridViewCols.value[id][k as keyof GridColumnType] } return o }, {}) addUndo({ redo: { fn: (w: Partial<GridColumnReqType>) => updateGridViewColumn(id, w, true), args: [props], }, undo: { fn: (w: Partial<GridColumnReqType>) => updateGridViewColumn(id, w, true), args: [oldProps], }, scope: defineViewScope({ view: view.value }), }) } // sync with server if allowed if (!isPublic.value && isUIAllowed('viewFieldEdit') && gridViewCols.value[id]?.id) { await $api.dbView.gridColumnUpdate(gridViewCols.value[id].id as string, { ...props, }) } if (gridViewCols.value?.[id]) { Object.assign(gridViewCols.value[id], { ...gridViewCols.value[id], ...props, }) } else { // fallback to reload await loadViewColumns() } } return { fields, loadViewColumns, filteredFieldList, filterQuery, showAll, hideAll, saveOrUpdate, sortedAndFilteredFields, showSystemFields, metaColumnById, toggleFieldVisibility, isViewColumnsLoading, updateGridViewColumn, gridViewCols, resizingColOldWith, } }, 'useViewColumnsOrThrow', ) export { useProvideViewColumns } export function useViewColumnsOrThrow() { const viewColumns = useViewColumns() if (viewColumns == null) throw new Error('Please call `useProvideViewColumns` on the appropriate parent component') return viewColumns }
packages/nc-gui/composables/useViewColumns.ts
1
https://github.com/nocodb/nocodb/commit/bd6115eb5eb53d7d1d30a351bbfb234b2adffe8e
[ 0.010437814518809319, 0.0005010178429074585, 0.00016541569493710995, 0.0001709458592813462, 0.0016420878237113357 ]
{ "id": 2, "code_window": [ " <UITypes>(typeof col === 'object' ? col?.uidt : col)\n", " );\n", "}\n", "\n", "export function isLinksOrLTAR(\n", " colOrUidt: ColumnType | { uidt: UITypes | string } | UITypes | string\n", ") {\n", " return [UITypes.LinkToAnotherRecord, UITypes.Links].includes(\n", " <UITypes>(typeof colOrUidt === 'object' ? colOrUidt?.uidt : colOrUidt)\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function isMMSystemCol(\n", " col: (ColumnReqType | ColumnType) & { system?: number | boolean }\n", ") {\n", " return (\n", " col.system && [UITypes.LinkToAnotherRecord].includes(<UITypes>col.uidt)\n", " );\n", "}\n", "\n" ], "file_path": "packages/nocodb-sdk/src/lib/UITypes.ts", "type": "add", "edit_start_line_idx": 164 }
import { test } from '@playwright/test'; import { BaseType, ProjectTypes } from 'nocodb-sdk'; import { DashboardPage } from '../../pages/Dashboard'; import setup, { NcContext } from '../../setup'; test.describe('Page history', () => { let dashboard: DashboardPage; let context: NcContext; let base: BaseType; test.beforeEach(async ({ page }) => { context = await setup({ page, baseType: ProjectTypes.DOCUMENTATION }); base = context.base; dashboard = new DashboardPage(page, context.base); }); test('Update page and verify history', async ({ page }) => { const openedPage = await dashboard.docs.openedPage; await dashboard.sidebar.docsSidebar.createPage({ baseTitle: base.title as any, title: 'Page title', }); await page.waitForTimeout(3500); await openedPage.fillTitle({ title: 'New Page title', }); await openedPage.tiptap.fillContent({ content: 'Page content', waitForNetwork: false, }); await openedPage.tiptap.fillContent({ index: 1, content: 'Page content 2', waitForNetwork: false, }); await page.waitForTimeout(3500); await openedPage.history.clickHistoryButton(); await openedPage.history.verifyHistoryList({ count: 4, items: [ { title: 'Current version', index: 0, active: true, }, { title: 'Edited a few seconds ago', index: 1, }, { title: 'Edited a few seconds ago', index: 2, }, { title: 'Created a few seconds ago', index: 3, }, ], }); await openedPage.history.clickHistoryItem({ index: 1, }); await openedPage.history.verifyHistoryList({ count: 4, items: [ { title: 'Current version', index: 0, }, { title: 'Edited a few seconds ago', index: 1, active: true, }, { title: 'Edited a few seconds ago', index: 2, }, { title: 'Created a few seconds ago', index: 3, }, ], }); await openedPage.tiptap.verifyNode({ index: 0, content: 'Page content', history: { added: true, }, }); await openedPage.tiptap.verifyNode({ index: 1, content: 'Page content 2', history: { added: true, }, }); await openedPage.history.clickHistoryItem({ index: 0, }); await openedPage.history.verifyHistoryList({ count: 4, items: [ { title: 'Current version', index: 0, active: true, }, { title: 'Edited a few seconds ago', index: 1, }, ], }); await openedPage.history.clickHistoryButton(); await openedPage.tiptap.clickNode({ index: 0, start: false, }); await page.keyboard.press('Enter'); await page.waitForTimeout(400); await openedPage.tiptap.addNewNode({ index: 1, type: 'Image', filePath: `${process.cwd()}/fixtures/sampleFiles/sampleImage.jpeg`, }); await page.waitForTimeout(500); await openedPage.tiptap.fillContent({ index: 0, content: '0', }); await openedPage.history.clickHistoryButton(); await openedPage.history.verifyHistoryList({ items: [ { title: 'Current version', index: 0, active: true, }, { title: 'Edited a few seconds ago', index: 1, }, { title: 'Edited a few seconds ago', index: 2, }, ], }); await openedPage.history.clickHistoryItem({ index: 1, }); await openedPage.tiptap.verifyNode({ index: 0, content: 'content', type: 'Paragraph', history: { removed: true, }, }); await openedPage.tiptap.verifyNode({ index: 0, content: 'content0', type: 'Paragraph', history: { added: true, }, }); await openedPage.tiptap.verifyNode({ index: 2, type: 'Image', history: { added: true, }, }); await openedPage.history.clickHistoryItem({ index: 3, }); await openedPage.history.clickRestoreButton(); await openedPage.history.clickRestoreModalConfirmButton(); await openedPage.tiptap.verifyNode({ index: 0, content: 'Page content', }); await openedPage.tiptap.verifyNode({ index: 1, content: 'Page content 2', }); }); });
tests/playwright/disabledTests/docs/history.spec.ts
0
https://github.com/nocodb/nocodb/commit/bd6115eb5eb53d7d1d30a351bbfb234b2adffe8e
[ 0.00017582200234755874, 0.00017365253006573766, 0.00016784356557764113, 0.0001739666040521115, 0.00000166002712376212 ]
{ "id": 2, "code_window": [ " <UITypes>(typeof col === 'object' ? col?.uidt : col)\n", " );\n", "}\n", "\n", "export function isLinksOrLTAR(\n", " colOrUidt: ColumnType | { uidt: UITypes | string } | UITypes | string\n", ") {\n", " return [UITypes.LinkToAnotherRecord, UITypes.Links].includes(\n", " <UITypes>(typeof colOrUidt === 'object' ? colOrUidt?.uidt : colOrUidt)\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function isMMSystemCol(\n", " col: (ColumnReqType | ColumnType) & { system?: number | boolean }\n", ") {\n", " return (\n", " col.system && [UITypes.LinkToAnotherRecord].includes(<UITypes>col.uidt)\n", " );\n", "}\n", "\n" ], "file_path": "packages/nocodb-sdk/src/lib/UITypes.ts", "type": "add", "edit_start_line_idx": 164 }
{ "name": "nocodb", "version": "0.204.0", "description": "NocoDB Backend", "main": "dist/bundle.js", "author": { "name": "NocoDB Inc", "url": "https://nocodb.com/" }, "homepage": "https://github.com/nocodb/nocodb", "repository": { "type": "git", "url": "https://github.com/nocodb/nocodb.git" }, "bugs": { "url": "https://github.com/nocodb/nocodb/issues" }, "engines": { "node": ">=18" }, "license": "AGPL-3.0-or-later", "scripts": { "build": "pnpm run docker:build", "build:obfuscate": "EE=true webpack --config webpack.config.js", "obfuscate:build:publish": "pnpm run build:obfuscate && pnpm publish .", "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", "start": "pnpm run watch:run", "start:prod": "node docker/main", "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", "test": "jest", "test:watch": "jest --watch", "test:cov": "jest --coverage", "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", "test:e2e": "jest --config ./test/jest-e2e.json", "watch:run": "cross-env NC_DISABLE_TELE=true EE=true nodemon -e ts,js -w ./src -x \"ts-node src/run/docker --log-error --project tsconfig.json\"", "watch:run:mysql": "cross-env NC_DISABLE_TELE=true EE=true nodemon -e ts,js -w ./src -x \"ts-node src/run/dockerRunMysql --log-error --project tsconfig.json\"", "watch:run:pg": "cross-env NC_DISABLE_TELE=true EE=true nodemon -e ts,js -w ./src -x \"ts-node src/run/dockerRunPG --log-error --project tsconfig.json\"", "watch:run:playwright:mysql": "rm -f ./test_noco.db; cross-env DB_TYPE=mysql NC_DB=\"mysql2://localhost:3306?u=root&p=password&d=pw_ncdb\" PLAYWRIGHT_TEST=true NC_DISABLE_TELE=true EE=true nodemon -e ts,js -w ./src -x \"ts-node src/run/testDocker --log-error --project tsconfig.json\"", "watch:run:playwright:pg": "rm -f ./test_noco.db; cross-env DB_TYPE=pg NC_DB=\"pg://localhost:5432?u=postgres&p=password&d=pw_ncdb\" PLAYWRIGHT_TEST=true NC_DISABLE_TELE=true EE=true nodemon -e ts,js -w ./src -x \"ts-node src/run/testDocker --log-error --project tsconfig.json\"", "watch:run:playwright": "rm -f ./test_*.db; cross-env DB_TYPE=sqlite DATABASE_URL=sqlite:./test_noco.db PLAYWRIGHT_TEST=true NC_DISABLE_TELE=true EE=true NC_SNAPSHOT_WINDOW_SEC=3 nodemon -e ts,js -w ./src -x \"ts-node src/run/testDocker --log-error --project tsconfig.json\"", "watch:run:playwright:quick": "rm -f ./test_noco.db; cp ../../tests/playwright/fixtures/noco_0_91_7.db ./test_noco.db; cross-env DATABASE_URL=sqlite:./test_noco.db NC_DISABLE_TELE=true EE=true nodemon -e ts,js -w ./src -x \"ts-node src/run/docker --log-error --project tsconfig.json\"", "watch:run:playwright:pg:cyquick": "rm -f ./test_noco.db; cp ../../tests/playwright/fixtures/noco_0_91_7.db ./test_noco.db; cross-env NC_DISABLE_TELE=true EE=true nodemon -e ts,js -w ./src -x \"ts-node src/run/dockerRunPG_CyQuick.ts --log-error --project tsconfig.json\"", "test:unit": "cross-env EE=false TS_NODE_PROJECT=./tests/unit/tsconfig.json mocha -r ts-node/register tests/unit/index.test.ts --recursive --timeout 300000 --exit --delay", "test:unit:pg": "cp tests/unit/.pg.env tests/unit/.env; cross-env EE=false TS_NODE_PROJECT=./tests/unit/tsconfig.json mocha -r ts-node/register tests/unit/index.test.ts --recursive --timeout 300000 --exit --delay", "docker:build": "EE=\"true-xc-test\" webpack --config docker/webpack.config.js" }, "dependencies": { "@aws-sdk/client-kafka": "^3.410.0", "@aws-sdk/client-s3": "^3.423.0", "@aws-sdk/lib-storage": "^3.451.0", "@aws-sdk/s3-request-presigner": "^3.423.0", "@google-cloud/storage": "^7.1.0", "@graphql-tools/merge": "^6.2.17", "@jm18457/kafkajs-msk-iam-authentication-mechanism": "^3.1.2", "@nestjs/bull": "^10.0.1", "@nestjs/common": "^10.2.10", "@nestjs/config": "^3.1.1", "@nestjs/core": "^10.2.10", "@nestjs/event-emitter": "^2.0.3", "@nestjs/jwt": "^10.2.0", "@nestjs/mapped-types": "^2.0.4", "@nestjs/passport": "^10.0.3", "@nestjs/platform-express": "^10.2.10", "@nestjs/platform-socket.io": "^10.2.10", "@nestjs/serve-static": "^4.0.0", "@nestjs/throttler": "^4.2.1", "@nestjs/websockets": "^10.2.10", "@ntegral/nestjs-sentry": "^4.0.0", "@sentry/node": "^6.19.7", "@techpass/passport-openidconnect": "^0.3.3", "@types/chai": "^4.3.11", "airtable": "^0.12.2", "ajv": "^8.12.0", "ajv-formats": "^2.1.1", "archiver": "^5.0.2", "auto-bind": "^4.0.0", "aws-kcl": "^2.2.2", "aws-sdk": "^2.1455.0", "axios": "^1.6.5", "bcryptjs": "^2.4.3", "body-parser": "^1.20.2", "boxen": "^5.1.2", "bull": "^4.11.5", "bullmq": "^1.91.1", "clear": "^0.1.0", "clickhouse": "^2.6.0", "clickhouse-migrations": "^0.1.13", "colors": "^1.4.0", "compare-versions": "^6.1.0", "cookie-parser": "^1.4.6", "cors": "^2.8.5", "cron": "^1.8.2", "crypto-js": "^4.0.0", "dataloader": "^2.0.0", "dayjs": "^1.11.10", "debug": "^4.3.4", "dotenv": "^8.2.0", "ejs": "^3.1.3", "emittery": "^0.7.2", "express": "^4.18.2", "extract-zip": "^2.0.1", "fast-levenshtein": "^2.0.6", "fs-extra": "^9.0.1", "glob": "^7.2.3", "graphql": "^15.3.0", "graphql-depth-limit": "^1.1.0", "graphql-type-json": "^0.3.2", "handlebars": "^4.7.6", "html-to-json-parser": "^1.1.0", "import-fresh": "^3.3.0", "inflection": "^1.12.0", "ioredis": "^5.3.2", "ioredis-mock": "^8.8.3", "is-docker": "^2.2.1", "isomorphic-dompurify": "^1.8.0", "jsep": "^1.3.8", "json5": "^2.2.3", "jsonfile": "^6.1.0", "jsonwebtoken": "^9.0.2", "kafkajs": "^2.2.4", "knex": "2.4.2", "list-github-dir-content": "^3.0.0", "lodash": "^4.17.19", "lru-cache": "^6.0.0", "mailersend": "^1.5.0", "marked": "^4.3.0", "minio": "^7.1.3", "mkdirp": "^2.1.6", "morgan": "^1.10.0", "mssql": "^10.0.1", "multer": "^1.4.5-lts.1", "mysql2": "^3.6.5", "nanoid": "^3.1.20", "nc-help": "0.3.1", "nc-lib-gui": "0.204.0", "nc-plugin": "^0.1.3", "ncp": "^2.0.0", "nestjs-kafka": "^1.0.6", "nestjs-throttler-storage-redis": "^0.3.3", "nocodb-sdk": "workspace:^", "nodemailer": "^6.4.10", "object-hash": "^3.0.0", "object-sizeof": "^2.6.3", "os-locale": "^6.0.2", "p-queue": "^6.6.2", "papaparse": "^5.4.1", "parse-database-url": "^0.3.0", "passport": "^0.6.0", "passport-auth-token": "^1.0.1", "passport-custom": "^1.1.1", "passport-github": "^1.1.0", "passport-google-oauth20": "^2.0.0", "passport-http": "^0.3.0", "passport-jwt": "^4.0.1", "passport-local": "^1.0.0", "pg": "^8.10.0", "redlock": "^5.0.0-beta.2", "reflect-metadata": "^0.1.14", "request-filtering-agent": "^1.1.2", "request-ip": "^2.1.3", "rmdir": "^1.2.0", "rxjs": "^7.2.0", "slash": "^3.0.0", "slug": "^8.2.3", "socket.io": "^4.4.1", "sql-query-identifier": "^2.5.0", "sqlite3": "^5.1.7", "tedious": "^16.6.1", "tinycolor2": "^1.4.2", "twilio": "^3.55.1", "unique-names-generator": "^4.7.1", "uuid": "^9.0.1", "validator": "^13.1.17", "xc-core-ts": "^0.1.0", "xlsx": "^0.18.5" }, "devDependencies": { "@nestjs/cli": "^10.2.1", "@nestjs/schematics": "^10.0.3", "@nestjs/testing": "^10.2.10", "@nestjsplus/dyn-schematics": "^1.0.12", "@types/ejs": "^3.1.5", "@types/express": "^4.17.21", "@types/jest": "^29.5.11", "@types/mocha": "^10.0.6", "@types/multer": "^1.4.11", "@types/node": "20.3.3", "@types/passport-google-oauth20": "^2.0.14", "@types/passport-jwt": "^3.0.13", "@types/supertest": "^2.0.16", "@typescript-eslint/eslint-plugin": "^6.11.0", "@typescript-eslint/parser": "^6.11.0", "chai": "^4.2.0", "copy-webpack-plugin": "^11.0.0", "cross-env": "^7.0.3", "eslint": "^8.33.0", "eslint-config-prettier": "^8.8.0", "eslint-plugin-eslint-comments": "^3.2.0", "eslint-plugin-functional": "^5.0.8", "eslint-plugin-import": "^2.27.5", "eslint-plugin-prettier": "^4.2.1", "jest": "29.5.0", "mocha": "^10.1.0", "nodemon": "^3.0.2", "prettier": "^2.8.8", "source-map-support": "^0.5.21", "supertest": "^6.3.3", "ts-jest": "29.0.5", "ts-loader": "^9.2.9", "ts-node": "^10.9.2", "tsconfig-paths": "^4.2.0", "typescript": "^5.3.3", "webpack-cli": "^5.1.4" }, "jest": { "moduleFileExtensions": [ "js", "json", "ts" ], "rootDir": "src", "testRegex": ".*\\.spec\\.ts$", "transform": { "^.+\\.(t|j)s$": "ts-jest" }, "collectCoverageFrom": [ "**/*.(t|j)s" ], "coverageDirectory": "../coverage", "testEnvironment": "node" } }
packages/nocodb/package.json
0
https://github.com/nocodb/nocodb/commit/bd6115eb5eb53d7d1d30a351bbfb234b2adffe8e
[ 0.00017450039740651846, 0.0001714802347123623, 0.00016660922847222537, 0.00017155730165541172, 0.0000017203461766257533 ]
{ "id": 2, "code_window": [ " <UITypes>(typeof col === 'object' ? col?.uidt : col)\n", " );\n", "}\n", "\n", "export function isLinksOrLTAR(\n", " colOrUidt: ColumnType | { uidt: UITypes | string } | UITypes | string\n", ") {\n", " return [UITypes.LinkToAnotherRecord, UITypes.Links].includes(\n", " <UITypes>(typeof colOrUidt === 'object' ? colOrUidt?.uidt : colOrUidt)\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export function isMMSystemCol(\n", " col: (ColumnReqType | ColumnType) & { system?: number | boolean }\n", ") {\n", " return (\n", " col.system && [UITypes.LinkToAnotherRecord].includes(<UITypes>col.uidt)\n", " );\n", "}\n", "\n" ], "file_path": "packages/nocodb-sdk/src/lib/UITypes.ts", "type": "add", "edit_start_line_idx": 164 }
<script setup lang="ts"> import { MetaInj, iconMap, inject, useSidebar, useTable } from '#imports' const meta = inject(MetaInj)! const { deleteTable } = useTable() const { isOpen } = useSidebar('nc-right-sidebar') </script> <template> <a-tooltip :placement="isOpen ? 'bottomRight' : 'left'"> <template #title> {{ $t('activity.deleteTable') }} </template> <div class="nc-sidebar-right-item hover:after:bg-red-500 group"> <component :is="iconMap.delete" class="cursor-pointer" @click="deleteTable(meta)" /> </div> </a-tooltip> </template>
packages/nc-gui/components/smartsheet/sidebar/toolbar/DeleteTable.vue
0
https://github.com/nocodb/nocodb/commit/bd6115eb5eb53d7d1d30a351bbfb234b2adffe8e
[ 0.0001734678662614897, 0.0001729873038129881, 0.00017250674136448652, 0.0001729873038129881, 4.805624485015869e-7 ]
{ "id": 3, "code_window": [ " isVirtualCol,\n", " isLinksOrLTAR,\n", " isCreatedOrLastModifiedTimeCol,\n", " isCreatedOrLastModifiedByCol,\n", "} from '~/lib/UITypes';\n", "export { default as CustomAPI, FileType } from '~/lib/CustomAPI';\n", "export { default as TemplateGenerator } from '~/lib/TemplateGenerator';\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " isMMSystemCol\n" ], "file_path": "packages/nocodb-sdk/src/lib/index.ts", "type": "add", "edit_start_line_idx": 18 }
export * from '~/lib/XcUIBuilder'; export * from '~/lib/XcNotification'; export * from '~/lib/Api'; export * from '~/lib/columnRules'; export * from '~/lib/sqlUi'; export * from '~/lib/globals'; export * from '~/lib/helperFunctions'; export * from '~/lib/enums'; export * from '~/lib/formulaHelpers'; export { default as UITypes, UITypesName, numericUITypes, isNumericCol, isVirtualCol, isLinksOrLTAR, isCreatedOrLastModifiedTimeCol, isCreatedOrLastModifiedByCol, } from '~/lib/UITypes'; export { default as CustomAPI, FileType } from '~/lib/CustomAPI'; export { default as TemplateGenerator } from '~/lib/TemplateGenerator'; export * from '~/lib/passwordHelpers'; export * from '~/lib/mergeSwaggerSchema'; export * from '~/lib/dateTimeHelper';
packages/nocodb-sdk/src/lib/index.ts
1
https://github.com/nocodb/nocodb/commit/bd6115eb5eb53d7d1d30a351bbfb234b2adffe8e
[ 0.9948018789291382, 0.3320738971233368, 0.00018613362044561654, 0.0012336933286860585, 0.4686196446418762 ]
{ "id": 3, "code_window": [ " isVirtualCol,\n", " isLinksOrLTAR,\n", " isCreatedOrLastModifiedTimeCol,\n", " isCreatedOrLastModifiedByCol,\n", "} from '~/lib/UITypes';\n", "export { default as CustomAPI, FileType } from '~/lib/CustomAPI';\n", "export { default as TemplateGenerator } from '~/lib/TemplateGenerator';\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " isMMSystemCol\n" ], "file_path": "packages/nocodb-sdk/src/lib/index.ts", "type": "add", "edit_start_line_idx": 18 }
import { test } from '@playwright/test'; import { DashboardPage } from '../../../pages/Dashboard'; import { ToolbarPage } from '../../../pages/Dashboard/common/Toolbar'; import setup, { unsetup } from '../../../setup'; test.describe('Views CRUD Operations', () => { let dashboard: DashboardPage; let context: any; let toolbar: ToolbarPage; test.beforeEach(async ({ page }) => { context = await setup({ page, isEmptyProject: false }); dashboard = new DashboardPage(page, context.base); toolbar = dashboard.grid.toolbar; }); test.afterEach(async () => { await unsetup(context); }); test('Create views, reorder and delete', async () => { await dashboard.treeView.openTable({ title: 'City' }); await dashboard.viewSidebar.createGridView({ title: 'CityGrid' }); await dashboard.viewSidebar.verifyView({ title: 'CityGrid', index: 0 }); await dashboard.viewSidebar.renameView({ title: 'CityGrid', newTitle: 'CityGrid2', }); await dashboard.viewSidebar.verifyView({ title: 'CityGrid2', index: 0, }); await dashboard.viewSidebar.createFormView({ title: 'CityForm' }); await dashboard.viewSidebar.verifyView({ title: 'CityForm', index: 1 }); await dashboard.viewSidebar.renameView({ title: 'CityForm', newTitle: 'CityForm2', }); await dashboard.viewSidebar.verifyView({ title: 'CityForm2', index: 1, }); await dashboard.viewSidebar.createGalleryView({ title: 'CityGallery' }); await dashboard.viewSidebar.verifyView({ title: 'CityGallery', index: 2 }); await dashboard.viewSidebar.renameView({ title: 'CityGallery', newTitle: 'CityGallery2', }); await dashboard.viewSidebar.verifyView({ title: 'CityGallery2', index: 2, }); await dashboard.viewSidebar.changeViewIcon({ title: 'CityGallery2', icon: 'american-football', iconDisplay: '🏈', }); // todo: Enable when view bug is fixed // await dashboard.viewSidebar.reorderViews({ // sourceView: "CityGrid", // destinationView: "CityForm", // }); // await dashboard.viewSidebar.verifyView({ title: "CityGrid", index: 2 }); // await dashboard.viewSidebar.verifyView({ title: "CityForm", index: 1 }); // await dashboard.viewSidebar.deleteView({ title: "CityForm2" }); // await dashboard.viewSidebar.verifyViewNotPresent({ // title: "CityGrid2", // index: 2, // }); await dashboard.viewSidebar.deleteView({ title: 'CityForm2' }); await dashboard.viewSidebar.verifyViewNotPresent({ title: 'CityForm2', index: 1, }); // fix index after enabling reorder test await dashboard.viewSidebar.deleteView({ title: 'CityGallery2' }); await dashboard.viewSidebar.verifyViewNotPresent({ title: 'CityGallery2', index: 0, }); }); test('Save search query for each table and view', async () => { await dashboard.treeView.openTable({ title: 'City' }); await toolbar.searchData.verify(''); await toolbar.searchData.get().fill('City-City'); await toolbar.searchData.verify('City-City'); await dashboard.viewSidebar.createGridView({ title: 'CityGrid' }); await toolbar.searchData.verify(''); await toolbar.searchData.get().fill('City-CityGrid'); await toolbar.searchData.verify('City-CityGrid'); await dashboard.viewSidebar.createGridView({ title: 'CityGrid2' }); await toolbar.searchData.verify(''); await toolbar.searchData.get().fill('City-CityGrid2'); await toolbar.searchData.verify('City-CityGrid2'); await dashboard.viewSidebar.openView({ title: 'CityGrid' }); await dashboard.rootPage.waitForTimeout(1000); await toolbar.searchData.verify('City-CityGrid'); await dashboard.treeView.openTable({ title: 'City' }); await dashboard.rootPage.waitForTimeout(1000); await toolbar.searchData.verify('City-City'); await dashboard.treeView.openTable({ title: 'Actor' }); await toolbar.searchData.verify(''); await dashboard.viewSidebar.createGridView({ title: 'ActorGrid' }); await toolbar.searchData.verify(''); await toolbar.searchData.get().fill('Actor-ActorGrid'); await toolbar.searchData.verify('Actor-ActorGrid'); await dashboard.treeView.openTable({ title: 'Actor' }); await dashboard.rootPage.waitForTimeout(1000); await toolbar.searchData.verify(''); await dashboard.treeView.openTable({ title: 'City', mode: '' }); await toolbar.searchData.verify('City-City'); }); });
tests/playwright/tests/db/general/views.spec.ts
0
https://github.com/nocodb/nocodb/commit/bd6115eb5eb53d7d1d30a351bbfb234b2adffe8e
[ 0.00017917552031576633, 0.0001766198838595301, 0.0001721933513181284, 0.00017651531379669905, 0.0000017400067235939787 ]
{ "id": 3, "code_window": [ " isVirtualCol,\n", " isLinksOrLTAR,\n", " isCreatedOrLastModifiedTimeCol,\n", " isCreatedOrLastModifiedByCol,\n", "} from '~/lib/UITypes';\n", "export { default as CustomAPI, FileType } from '~/lib/CustomAPI';\n", "export { default as TemplateGenerator } from '~/lib/TemplateGenerator';\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " isMMSystemCol\n" ], "file_path": "packages/nocodb-sdk/src/lib/index.ts", "type": "add", "edit_start_line_idx": 18 }
import { Page, test } from '@playwright/test'; import setup from '../../../setup'; import { DashboardPage } from '../../../pages/Dashboard'; import { ToolbarPage } from '../../../pages/Dashboard/common/Toolbar'; import { createDemoTable } from '../../../setup/demoTable'; import { TopbarPage } from '../../../pages/Dashboard/common/Topbar'; import { enableQuickRun } from '../../../setup/db'; const validateResponse = false; async function undo({ page, dashboard }: { page: Page; dashboard: DashboardPage }) { const isMac = await dashboard.grid.isMacOs(); if (validateResponse) { await dashboard.grid.waitForResponse({ uiAction: () => page.keyboard.press(isMac ? 'Meta+z' : 'Control+z'), httpMethodsToMatch: ['GET'], requestUrlPathToMatch: `/api/v1/db/data/noco/`, responseJsonMatcher: json => json.pageInfo, }); } else { await page.keyboard.press(isMac ? 'Meta+z' : 'Control+z'); // allow time for undo to complete rendering await page.waitForTimeout(500); } } test.describe('GroupBy CRUD Operations', () => { if (enableQuickRun()) test.skip(); let dashboard: DashboardPage, toolbar: ToolbarPage, topbar: TopbarPage; let context: any; test.beforeEach(async ({ page }) => { context = await setup({ page, isEmptyProject: false }); dashboard = new DashboardPage(page, context.base); toolbar = dashboard.grid.toolbar; topbar = dashboard.grid.topbar; await createDemoTable({ context, type: 'groupBased', recordCnt: 400 }); await page.reload(); }); test('Single GroupBy CRUD Operations', async ({ page }) => { await dashboard.treeView.openTable({ title: 'groupBased' }); await toolbar.sort.add({ title: 'Sub_Group', ascending: true, locallySaved: false }); await toolbar.groupBy.add({ title: 'Category', ascending: false, locallySaved: false }); await dashboard.grid.groupPage.openGroup({ indexMap: [2] }); await dashboard.grid.groupPage.addNewRow({ indexMap: [2], index: 10, columnHeader: 'Sub_Group', value: 'Aaaaaaaaaaaaaaaaaaaa', }); // kludge: refresh once did not work for some reason await topbar.clickRefresh(); await topbar.clickRefresh(); //await toolbar.sort.add({title: 'Sub_Group', ascending: true, locallySaved: true}); await dashboard.grid.groupPage.validateFirstRow({ indexMap: [2], rowIndex: 0, columnHeader: 'Sub_Group', value: 'Aaaaaaaaaaaaaaaaaaaa', }); await dashboard.grid.groupPage.editRow({ indexMap: [2], rowIndex: 0, columnHeader: 'Sub_Group', value: 'Zzzzzzzzzzzzzzzzzzz', }); await toolbar.sort.update({ index: 2, title: 'Sub_Group', ascending: false, locallySaved: false }); await dashboard.grid.groupPage.validateFirstRow({ indexMap: [2], rowIndex: 0, columnHeader: 'Sub_Group', value: 'Zzzzzzzzzzzzzzzzzzz', }); await dashboard.grid.groupPage.deleteRow({ title: 'Sub_Group', indexMap: [2], rowIndex: 0, }); await dashboard.grid.groupPage.validateFirstRow({ indexMap: [2], rowIndex: 0, columnHeader: 'Sub_Group', value: 'Angola', }); await undo({ page, dashboard }); await dashboard.grid.groupPage.validateFirstRow({ indexMap: [2], rowIndex: 0, columnHeader: 'Sub_Group', value: 'Zzzzzzzzzzzzzzzzzzz', }); }); test('Double GroupBy CRUD Operations', async ({ page }) => { await dashboard.treeView.openTable({ title: 'groupBased' }); await toolbar.sort.add({ title: 'Sub_Category', ascending: true, locallySaved: false }); await toolbar.groupBy.add({ title: 'Category', ascending: false, locallySaved: false }); await toolbar.groupBy.add({ title: 'Sub_Group', ascending: false, locallySaved: false }); await dashboard.grid.groupPage.openGroup({ indexMap: [2, 0] }); await dashboard.grid.groupPage.addNewRow({ indexMap: [2, 0], index: 10, columnHeader: 'Sub_Category', value: 'Aaaaaaaaaaaaaaaaaaaa', }); // One Click did not work for some reason await topbar.clickRefresh(); await topbar.clickRefresh(); //await toolbar.sort.add({title: 'Sub_Group', ascending: true, locallySaved: true}); await dashboard.grid.groupPage.validateFirstRow({ indexMap: [2, 0], rowIndex: 0, columnHeader: 'Sub_Category', value: 'Aaaaaaaaaaaaaaaaaaaa', }); await dashboard.grid.groupPage.editRow({ indexMap: [2, 0], rowIndex: 0, columnHeader: 'Sub_Category', value: 'Zzzzzzzzzzzzzzzzzzz', }); await toolbar.sort.update({ index: 3, title: 'Sub_Category', ascending: false, locallySaved: false }); await dashboard.grid.groupPage.validateFirstRow({ indexMap: [2, 0], rowIndex: 0, columnHeader: 'Sub_Category', value: 'Zzzzzzzzzzzzzzzzzzz', }); await dashboard.grid.groupPage.deleteRow({ title: 'Sub_Category', indexMap: [2, 0], rowIndex: 0, }); await dashboard.grid.groupPage.validateFirstRow({ indexMap: [2, 0], rowIndex: 0, columnHeader: 'Sub_Category', value: 'Afghanistan', }); await undo({ page, dashboard }); await dashboard.grid.groupPage.validateFirstRow({ indexMap: [2, 0], rowIndex: 0, columnHeader: 'Sub_Category', value: 'Zzzzzzzzzzzzzzzzzzz', }); }); test('Three GroupBy CRUD Operations', async ({ page }) => { await dashboard.treeView.openTable({ title: 'groupBased' }); await toolbar.sort.add({ title: 'Item', ascending: true, locallySaved: false }); await toolbar.groupBy.add({ title: 'Category', ascending: false, locallySaved: false }); await toolbar.groupBy.add({ title: 'Sub_Group', ascending: false, locallySaved: false }); await toolbar.groupBy.add({ title: 'Sub_Category', ascending: false, locallySaved: false }); await dashboard.grid.groupPage.openGroup({ indexMap: [2, 0, 0] }); await dashboard.grid.groupPage.addNewRow({ indexMap: [2, 0, 0], index: 10, columnHeader: 'Item', value: 'Aaaaaaaaaaaaaaaaaaaa', }); // One Click did not work for some reason await topbar.clickRefresh(); await topbar.clickRefresh(); //await toolbar.sort.add({title: 'Sub_Group', ascending: true, locallySaved: true}); await dashboard.grid.groupPage.validateFirstRow({ indexMap: [2, 0, 0], rowIndex: 0, columnHeader: 'Item', value: 'Aaaaaaaaaaaaaaaaaaaa', }); await dashboard.grid.groupPage.editRow({ indexMap: [2, 0, 0], rowIndex: 0, columnHeader: 'Item', value: 'Zzzzzzzzzzzzzzzzzzz', }); await toolbar.sort.update({ index: 4, title: 'Item', ascending: false, locallySaved: false }); await dashboard.grid.groupPage.validateFirstRow({ indexMap: [2, 0, 0], rowIndex: 0, columnHeader: 'Item', value: 'Zzzzzzzzzzzzzzzzzzz', }); await dashboard.grid.groupPage.deleteRow({ title: 'Item', indexMap: [2, 0, 0], rowIndex: 0, }); await dashboard.grid.groupPage.validateFirstRow({ indexMap: [2, 0, 0], rowIndex: 0, columnHeader: 'Item', value: 'Argentina', }); await undo({ page, dashboard }); await dashboard.grid.groupPage.validateFirstRow({ indexMap: [2, 0, 0], rowIndex: 0, columnHeader: 'Item', value: 'Zzzzzzzzzzzzzzzzzzz', }); }); test('Single GroupBy CRUD Operations - Links', async ({ page }) => { await dashboard.treeView.openTable({ title: 'Film' }); await toolbar.groupBy.add({ title: 'Actors', ascending: false, locallySaved: false }); await dashboard.grid.groupPage.openGroup({ indexMap: [2] }); await dashboard.grid.groupPage.validateFirstRow({ indexMap: [2], rowIndex: 0, columnHeader: 'Title', value: 'ARABIA DOGMA', }); }); });
tests/playwright/tests/db/general/groupCRUD.spec.ts
0
https://github.com/nocodb/nocodb/commit/bd6115eb5eb53d7d1d30a351bbfb234b2adffe8e
[ 0.0001777446159394458, 0.00017525798466522247, 0.00016926106764003634, 0.00017567035683896393, 0.0000017278332506975858 ]
{ "id": 3, "code_window": [ " isVirtualCol,\n", " isLinksOrLTAR,\n", " isCreatedOrLastModifiedTimeCol,\n", " isCreatedOrLastModifiedByCol,\n", "} from '~/lib/UITypes';\n", "export { default as CustomAPI, FileType } from '~/lib/CustomAPI';\n", "export { default as TemplateGenerator } from '~/lib/TemplateGenerator';\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " isMMSystemCol\n" ], "file_path": "packages/nocodb-sdk/src/lib/index.ts", "type": "add", "edit_start_line_idx": 18 }
import { test } from '@playwright/test'; import { DashboardPage } from '../../../pages/Dashboard'; import setup from '../../../setup'; import { isMysql, isPg, isSqlite } from '../../../setup/db'; test.describe('Shared view', () => { let dashboard: DashboardPage; let context: any; let sharedLink: string; test.beforeEach(async ({ page }) => { context = await setup({ page, isEmptyProject: false }); dashboard = new DashboardPage(page, context.base); }); test('Grid Share with GroupBy', async ({ page }) => { await dashboard.treeView.openTable({ title: 'Film' }); await dashboard.grid.toolbar.groupBy.add({ title: 'Title', ascending: false, locallySaved: false, }); await dashboard.grid.toolbar.sort.add({ title: 'Title', ascending: false, locallySaved: false, }); sharedLink = await dashboard.grid.topbar.getSharedViewUrl(); await page.goto(sharedLink); // fix me! kludge@hub; page wasn't getting loaded from previous step await page.reload(); const sharedPage = new DashboardPage(page, context.base); await sharedPage.grid.groupPage.openGroup({ indexMap: [0] }); await sharedPage.grid.groupPage.validateFirstRow({ indexMap: [0], rowIndex: 0, columnHeader: 'Title', value: 'ZORRO ARK', }); // Goto dashboard and Create Filter and verify shared view await dashboard.goto(); await page.reload(); await dashboard.treeView.openTable({ title: 'Film' }); await dashboard.grid.toolbar.clickFilter(); await dashboard.grid.toolbar.filter.add({ title: 'Length', operation: '=', value: '180', }); await dashboard.grid.toolbar.clickFilter(); await page.goto(sharedLink); await page.reload(); await sharedPage.grid.groupPage.openGroup({ indexMap: [0] }); await sharedPage.grid.groupPage.validateFirstRow({ indexMap: [0], rowIndex: 0, columnHeader: 'Title', value: 'SOMETHING DUCK', }); // Goto dashboard and Update Group, Remove Filter and verify shared view await dashboard.goto(); await page.reload(); await dashboard.treeView.openTable({ title: 'Film' }); await dashboard.grid.toolbar.groupBy.update({ index: 0, title: 'Length', ascending: false, }); await dashboard.grid.toolbar.filter.reset(); await page.goto(sharedLink); await page.reload(); await sharedPage.grid.groupPage.openGroup({ indexMap: [0] }); await sharedPage.grid.groupPage.validateFirstRow({ indexMap: [0], rowIndex: 0, columnHeader: 'Title', value: 'WORST BANGER', }); await dashboard.goto(); await page.reload(); // kludge: wait for 3 seconds to avoid flaky test await page.waitForTimeout(5000); await dashboard.treeView.openTable({ title: 'Film' }); await dashboard.grid.toolbar.groupBy.remove({ index: 0 }); await page.goto(sharedLink); await page.reload(); // kludge: wait for 3 seconds to avoid flaky test await page.waitForTimeout(5000); await sharedPage.grid.cell.verify({ index: 0, columnHeader: 'Title', value: 'ZORRO ARK' }); }); test('Grid share ', async ({ page }) => { /** * 1. Create Shared view * - hide column * - add sort * - add filter * - enable download * - disable password * - generate shared view link * - copy link **/ // close 'Team & Auth' tab await dashboard.closeTab({ title: 'Team & Auth' }); await dashboard.treeView.openTable({ title: 'Address' }); // hide column await dashboard.grid.toolbar.fields.toggle({ title: 'Address2' }); await dashboard.grid.toolbar.fields.toggle({ title: 'Stores' }); // sort await dashboard.grid.toolbar.sort.add({ title: 'District', ascending: false, locallySaved: false, }); // filter await dashboard.grid.toolbar.clickFilter(); await dashboard.grid.toolbar.filter.add({ title: 'Address', value: 'Ab', operation: 'is like', locallySaved: false, }); await dashboard.grid.toolbar.clickFilter(); // share with password disabled, download enabled sharedLink = await dashboard.grid.topbar.getSharedViewUrl(); /** * 2. Access shared view: verify * - access without password * - column order * - data order (sort & filter) * - virtual columns (hm, bt) **/ await page.goto(sharedLink); // fix me! kludge@hub; page wasn't getting loaded from previous step await page.reload(); const sharedPage = new DashboardPage(page, context.base); const expectedColumns = [ { title: 'Address', isVisible: true }, { title: 'Address2', isVisible: false }, { title: 'District', isVisible: true }, { title: 'City', isVisible: true }, { title: 'PostalCode', isVisible: true }, { title: 'Phone', isVisible: true }, { title: 'LastUpdate', isVisible: true }, { title: 'Customers', isVisible: true }, { title: 'Staffs', isVisible: true }, { title: 'Stores', isVisible: false }, { title: 'City', isVisible: true }, ]; for (const column of expectedColumns) { await sharedPage.grid.column.verify(column); } const expectedRecordsByDb = isSqlite(context) || isPg(context) ? sqliteExpectedRecords : expectedRecords; await new Promise(resolve => setTimeout(resolve, 1000)); // verify order of records (original sort & filter) for (const record of expectedRecordsByDb) { await sharedPage.grid.cell.verify(record); } const expectedVirtualRecordsByDb = isSqlite(context) || isPg(context) ? sqliteExpectedVirtualRecords : expectedVirtualRecords; // verify virtual records for (const record of expectedVirtualRecordsByDb) { await sharedPage.grid.cell.verifyVirtualCell({ ...record, options: { singular: 'Customer', plural: 'Customers' }, verifyChildList: true, }); } /** * 3. Shared view: verify * - new sort * - new filter * - new column hidden **/ // create new sort & filter criteria in shared view await sharedPage.grid.toolbar.sort.add({ title: 'Address', ascending: true, locallySaved: true, }); if (isMysql(context)) { await sharedPage.grid.toolbar.clickFilter(); await sharedPage.grid.toolbar.filter.add({ title: 'District', value: 'Ta', operation: 'is like', locallySaved: true, }); await sharedPage.grid.toolbar.clickFilter(); } await sharedPage.grid.toolbar.fields.toggle({ title: 'LastUpdate', isLocallySaved: true }); expectedColumns[6].isVisible = false; // verify new sort & filter criteria for (const column of expectedColumns) { await sharedPage.grid.column.verify(column); } const expectedRecordsByDb2 = isSqlite(context) || isPg(context) ? sqliteExpectedRecords2 : expectedRecords2; // verify order of records (original sort & filter) for (const record of expectedRecordsByDb2) { await sharedPage.grid.cell.verify(record); } /** * 4. Download * - Verify download data (order, filter, sort) **/ // verify download await sharedPage.grid.toolbar.clickDownload( 'Download CSV', isSqlite(context) || isPg(context) ? 'expectedDataSqlite.txt' : 'expectedData.txt' ); }); test('Shared view: password', async ({ page }) => { /** * 5. Enable shared view password, disable download: verify * - Incorrect password * - Correct password * - Download disabled * - Add new record & column after shared view creation; verify **/ await dashboard.closeTab({ title: 'Team & Auth' }); await dashboard.treeView.openTable({ title: 'Country' }); sharedLink = await dashboard.grid.topbar.getSharedViewUrl(false, 'p@ssword', true); // add new column, record after share view creation await dashboard.grid.column.create({ title: 'New Column', }); await dashboard.grid.addNewRow({ index: 25, columnHeader: 'Country', value: 'New Country', }); await dashboard.signOut(); await page.goto(sharedLink); await page.reload(); // verify if password request modal exists const sharedPage2 = new DashboardPage(page, context.base); await sharedPage2.rootPage.locator('input[placeholder="Enter password"]').fill('incorrect p@ssword'); await sharedPage2.rootPage.click('button:has-text("Unlock")'); await sharedPage2.verifyToast({ message: 'INVALID_SHARED_VIEW_PASSWORD' }); // correct password await sharedPage2.rootPage.locator('input[placeholder="Enter password"]').fill('p@ssword'); await sharedPage2.rootPage.click('button:has-text("Unlock")'); // verify if download button is disabled await sharedPage2.grid.toolbar.verifyDownloadDisabled(); // verify new column & record await sharedPage2.grid.column.verify({ title: 'New Column', isVisible: true, }); await sharedPage2.grid.toolbar.clickFilter(); await sharedPage2.grid.toolbar.filter.add({ title: 'Country', value: 'New Country', operation: 'is like', locallySaved: true, }); await sharedPage2.grid.toolbar.clickFilter(); await sharedPage2.grid.cell.verify({ index: 0, columnHeader: 'Country', value: 'New Country', }); }); }); const expectedRecords = [ { index: 0, columnHeader: 'Address', value: '1013 Tabuk Boulevard' }, { index: 1, columnHeader: 'Address', value: '1892 Nabereznyje Telny', }, { index: 2, columnHeader: 'Address', value: '1993 Tabuk Lane' }, { index: 0, columnHeader: 'District', value: 'West Bengali' }, { index: 1, columnHeader: 'District', value: 'Tutuila' }, { index: 2, columnHeader: 'District', value: 'Tamil Nadu' }, { index: 0, columnHeader: 'PostalCode', value: '96203' }, { index: 1, columnHeader: 'PostalCode', value: '28396' }, { index: 2, columnHeader: 'PostalCode', value: '64221' }, { index: 0, columnHeader: 'Phone', value: '158399646978' }, { index: 1, columnHeader: 'Phone', value: '478229987054' }, { index: 2, columnHeader: 'Phone', value: '648482415405' }, ]; // const sqliteExpectedRecords = [ // { index: 0, columnHeader: 'Address', value: '669 Firozabad Loop' }, // { index: 1, columnHeader: 'Address', value: '48 Maracabo Place' }, // { index: 2, columnHeader: 'Address', value: '44 Najafabad Way' }, // { index: 0, columnHeader: 'PostalCode', value: '92265' }, // { index: 1, columnHeader: 'PostalCode', value: '1570' }, // { index: 2, columnHeader: 'PostalCode', value: '61391' }, // ]; const sqliteExpectedRecords = [ { index: 0, columnHeader: 'Address', value: '217 Botshabelo Place' }, { index: 1, columnHeader: 'Address', value: '17 Kabul Boulevard' }, { index: 2, columnHeader: 'Address', value: '1888 Kabul Drive' }, { index: 0, columnHeader: 'PostalCode', value: '49521' }, { index: 1, columnHeader: 'PostalCode', value: '38594' }, { index: 2, columnHeader: 'PostalCode', value: '20936' }, ]; const expectedRecords2 = [ { index: 0, columnHeader: 'Address', value: '1661 Abha Drive' }, { index: 1, columnHeader: 'Address', value: '1993 Tabuk Lane' }, { index: 2, columnHeader: 'Address', value: '381 Kabul Way' }, { index: 0, columnHeader: 'District', value: 'Tamil Nadu' }, { index: 1, columnHeader: 'District', value: 'Tamil Nadu' }, { index: 2, columnHeader: 'District', value: 'Taipei' }, { index: 0, columnHeader: 'PostalCode', value: '14400' }, { index: 1, columnHeader: 'PostalCode', value: '64221' }, { index: 2, columnHeader: 'PostalCode', value: '87272' }, { index: 0, columnHeader: 'Phone', value: '270456873752' }, { index: 1, columnHeader: 'Phone', value: '648482415405' }, { index: 2, columnHeader: 'Phone', value: '55477302294' }, ]; const sqliteExpectedRecords2 = [ { index: 0, columnHeader: 'Address', value: '1013 Tabuk Boulevard' }, { index: 1, columnHeader: 'Address', value: '1168 Najafabad Parkway' }, { index: 2, columnHeader: 'Address', value: '1294 Firozabad Drive' }, { index: 0, columnHeader: 'PostalCode', value: '96203' }, { index: 1, columnHeader: 'PostalCode', value: '40301' }, { index: 2, columnHeader: 'PostalCode', value: '70618' }, ]; const expectedVirtualRecords = [ { index: 0, columnHeader: 'Customers', count: 1, type: 'hm' }, { index: 1, columnHeader: 'Customers', count: 1, type: 'hm' }, { index: 0, columnHeader: 'City', count: 1, type: 'bt', value: ['Kanchrapara'] }, { index: 1, columnHeader: 'City', count: 1, type: 'bt', value: ['Tafuna'] }, ]; const sqliteExpectedVirtualRecords = [ { index: 0, columnHeader: 'Customers', count: 1, type: 'hm' }, { index: 1, columnHeader: 'Customers', count: 1, type: 'hm' }, { index: 0, columnHeader: 'City', count: 1, type: 'bt', value: ['Davao'] }, { index: 1, columnHeader: 'City', count: 1, type: 'bt', value: ['Nagareyama'] }, ];
tests/playwright/tests/db/views/viewGridShare.spec.ts
0
https://github.com/nocodb/nocodb/commit/bd6115eb5eb53d7d1d30a351bbfb234b2adffe8e
[ 0.00017751225095707923, 0.00017347800894640386, 0.00016470524133183062, 0.00017429504077881575, 0.0000028750191631843336 ]
{ "id": 0, "code_window": [ "\n", "const emit = defineEmits(['update:modelValue'])\n", "\n", "const column = inject(ColumnInj)!\n", "\n", "const readOnly = inject(ReadonlyInj)!\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "const { isMobileMode } = useGlobal()\n", "\n" ], "file_path": "packages/nc-gui/components/cell/MultiSelect.vue", "type": "add", "edit_start_line_idx": 45 }
<script lang="ts" setup> import { onUnmounted } from '@vue/runtime-core' import { message } from 'ant-design-vue' import tinycolor from 'tinycolor2' import type { Select as AntSelect } from 'ant-design-vue' import type { SelectOptionType } from 'nocodb-sdk' import { ActiveCellInj, CellClickHookInj, ColumnInj, EditColumnInj, EditModeInj, IsFormInj, IsKanbanInj, ReadonlyInj, computed, enumColor, extractSdkResponseErrorMsg, iconMap, inject, isDrawerOrModalExist, ref, useBase, useEventListener, useRoles, useSelectedCellKeyupListener, watch, } from '#imports' interface Props { modelValue?: string | undefined rowIndex?: number disableOptionCreation?: boolean } const { modelValue, disableOptionCreation } = defineProps<Props>() const emit = defineEmits(['update:modelValue']) const column = inject(ColumnInj)! const readOnly = inject(ReadonlyInj)! const isLockedMode = inject(IsLockedInj, ref(false)) const isEditable = inject(EditModeInj, ref(false)) const activeCell = inject(ActiveCellInj, ref(false)) // use both ActiveCellInj or EditModeInj to determine the active state // since active will be false in case of form view const active = computed(() => activeCell.value || isEditable.value) const aselect = ref<typeof AntSelect>() const isOpen = ref(false) const isKanban = inject(IsKanbanInj, ref(false)) const isPublic = inject(IsPublicInj, ref(false)) const isEditColumn = inject(EditColumnInj, ref(false)) const isForm = inject(IsFormInj, ref(false)) const { $api } = useNuxtApp() const searchVal = ref() const { getMeta } = useMetas() const { isUIAllowed } = useRoles() const { isPg, isMysql } = useBase() // a variable to keep newly created option value // temporary until it's add the option to column meta const tempSelectedOptState = ref<string>() const isNewOptionCreateEnabled = computed(() => !isPublic.value && !disableOptionCreation && isUIAllowed('fieldEdit')) const options = computed<(SelectOptionType & { value: string })[]>(() => { if (column?.value.colOptions) { const opts = column.value.colOptions ? // todo: fix colOptions type, options does not exist as a property (column.value.colOptions as any).options.filter((el: SelectOptionType) => el.title !== '') || [] : [] for (const op of opts.filter((el: any) => el.order === null)) { op.title = op.title.replace(/^'/, '').replace(/'$/, '') } return opts.map((o: any) => ({ ...o, value: o.title })) } return [] }) const isOptionMissing = computed(() => { return (options.value ?? []).every((op) => op.title !== searchVal.value) }) const hasEditRoles = computed(() => isUIAllowed('dataEdit')) const editAllowed = computed(() => (hasEditRoles.value || isForm.value) && active.value) const vModel = computed({ get: () => tempSelectedOptState.value ?? modelValue?.trim(), set: (val) => { if (val && isNewOptionCreateEnabled.value && (options.value ?? []).every((op) => op.title !== val)) { tempSelectedOptState.value = val return addIfMissingAndSave() } emit('update:modelValue', val || null) }, }) watch(isOpen, (n, _o) => { if (editAllowed.value) { if (!n) { aselect.value?.$el?.querySelector('input')?.blur() } else { aselect.value?.$el?.querySelector('input')?.focus() } } }) useSelectedCellKeyupListener(activeCell, (e) => { switch (e.key) { case 'Escape': isOpen.value = false break case 'Enter': if (editAllowed.value && active.value && !isOpen.value) { isOpen.value = true } break // skip space bar key press since it's used for expand row case ' ': break default: if (!editAllowed.value) { e.preventDefault() break } // toggle only if char key pressed if (!(e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) && e.key?.length === 1 && !isDrawerOrModalExist()) { e.stopPropagation() isOpen.value = true } break } }) // close dropdown list on escape useSelectedCellKeyupListener(isOpen, (e) => { if (e.key === 'Escape') isOpen.value = false }) async function addIfMissingAndSave() { if (!tempSelectedOptState.value || isPublic.value) return false const newOptValue = tempSelectedOptState.value searchVal.value = '' tempSelectedOptState.value = undefined if (newOptValue && !options.value.some((o) => o.title === newOptValue)) { try { options.value.push({ title: newOptValue, value: newOptValue, color: enumColor.light[(options.value.length + 1) % enumColor.light.length], }) column.value.colOptions = { options: options.value.map(({ value: _, ...rest }) => rest) } const updatedColMeta = { ...column.value } // todo: refactor and avoid repetition if (updatedColMeta.cdf) { // Postgres returns default value wrapped with single quotes & casted with type so we have to get value between single quotes to keep it unified for all databases if (isPg(column.value.source_id)) { updatedColMeta.cdf = updatedColMeta.cdf.substring( updatedColMeta.cdf.indexOf(`'`) + 1, updatedColMeta.cdf.lastIndexOf(`'`), ) } // Mysql escapes single quotes with backslash so we keep quotes but others have to unescaped if (!isMysql(column.value.source_id) && !isPg(column.value.source_id)) { updatedColMeta.cdf = updatedColMeta.cdf.replace(/''/g, "'") } } await $api.dbTableColumn.update( (column.value as { fk_column_id?: string })?.fk_column_id || (column.value?.id as string), updatedColMeta, ) vModel.value = newOptValue await getMeta(column.value.fk_model_id!, true) } catch (e: any) { console.log(e) message.error(await extractSdkResponseErrorMsg(e)) } } } const search = () => { searchVal.value = aselect.value?.$el?.querySelector('.ant-select-selection-search-input')?.value } // prevent propagation of keydown event if select is open const onKeydown = (e: KeyboardEvent) => { if (isOpen.value && active.value) { e.stopPropagation() } if (e.key === 'Enter') { e.stopPropagation() } } const onSelect = () => { isOpen.value = false isEditable.value = false } const cellClickHook = inject(CellClickHookInj, null) const toggleMenu = (e: Event) => { // todo: refactor // check clicked element is clear icon if ( (e.target as HTMLElement)?.classList.contains('ant-select-clear') || (e.target as HTMLElement)?.closest('.ant-select-clear') ) { vModel.value = '' return e.stopPropagation() } if (cellClickHook) return isOpen.value = editAllowed.value && !isOpen.value } const cellClickHookHandler = () => { isOpen.value = editAllowed.value && !isOpen.value } onMounted(() => { cellClickHook?.on(cellClickHookHandler) }) onUnmounted(() => { cellClickHook?.on(cellClickHookHandler) }) const handleClose = (e: MouseEvent) => { if (isOpen.value && aselect.value && !aselect.value.$el.contains(e.target)) { isOpen.value = false } } useEventListener(document, 'click', handleClose, true) const selectedOpt = computed(() => { return options.value.find((o) => o.value === vModel.value) }) </script> <template> <div class="h-full w-full flex items-center nc-single-select" :class="{ 'read-only': readOnly || isLockedMode }" @click="toggleMenu" > <div v-if="!(active || isEditable)"> <a-tag v-if="selectedOpt" class="rounded-tag" :color="selectedOpt.color"> <span :style="{ 'color': tinycolor.isReadable(selectedOpt.color || '#ccc', '#fff', { level: 'AA', size: 'large' }) ? '#fff' : tinycolor.mostReadable(selectedOpt.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '13px', }" :class="{ 'text-sm': isKanban }" > {{ selectedOpt.title }} </span> </a-tag> </div> <a-select v-else ref="aselect" v-model:value="vModel" class="w-full overflow-hidden" :class="{ 'caret-transparent': !hasEditRoles }" :placeholder="isEditColumn ? $t('labels.optional') : ''" :allow-clear="!column.rqd && editAllowed" :bordered="false" :open="isOpen && editAllowed" :disabled="readOnly || !editAllowed || isLockedMode" :show-arrow="hasEditRoles && !(readOnly || isLockedMode) && active && vModel === null" :dropdown-class-name="`nc-dropdown-single-select-cell ${isOpen && active ? 'active' : ''}`" :show-search="isOpen && active" @select="onSelect" @keydown="onKeydown($event)" @search="search" > <a-select-option v-for="op of options" :key="op.title" :value="op.title" :data-testid="`select-option-${column.title}-${rowIndex}`" :class="`nc-select-option-${column.title}-${op.title}`" @click.stop > <a-tag class="rounded-tag" :color="op.color"> <span :style="{ 'color': tinycolor.isReadable(op.color || '#ccc', '#fff', { level: 'AA', size: 'large' }) ? '#fff' : tinycolor.mostReadable(op.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '13px', }" :class="{ 'text-sm': isKanban }" > {{ op.title }} </span> </a-tag> </a-select-option> <a-select-option v-if="searchVal && isOptionMissing && isNewOptionCreateEnabled" :key="searchVal" :value="searchVal"> <div class="flex gap-2 text-gray-500 items-center h-full"> <component :is="iconMap.plusThick" class="min-w-4" /> <div class="text-xs whitespace-normal"> {{ $t('msg.selectOption.createNewOptionNamed') }} <strong>{{ searchVal }}</strong> </div> </div> </a-select-option> </a-select> </div> </template> <style scoped lang="scss"> .rounded-tag { @apply py-0 px-[12px] rounded-[12px]; } :deep(.ant-tag) { @apply "rounded-tag" my-[2px]; } :deep(.ant-select-clear) { opacity: 1; } .nc-single-select:not(.read-only) { :deep(.ant-select-selector), :deep(.ant-select-selector input) { @apply !cursor-pointer; } } :deep(.ant-select-selector) { @apply !px-0; } :deep(.ant-select-selection-search-input) { @apply !text-xs; } :deep(.ant-select-clear > span) { @apply block; } </style>
packages/nc-gui/components/cell/SingleSelect.vue
1
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.9984824061393738, 0.2528083026409149, 0.0001665118761593476, 0.00017643194587435573, 0.42498642206192017 ]
{ "id": 0, "code_window": [ "\n", "const emit = defineEmits(['update:modelValue'])\n", "\n", "const column = inject(ColumnInj)!\n", "\n", "const readOnly = inject(ReadonlyInj)!\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "const { isMobileMode } = useGlobal()\n", "\n" ], "file_path": "packages/nc-gui/components/cell/MultiSelect.vue", "type": "add", "edit_start_line_idx": 45 }
import { XcStoragePlugin } from 'nc-plugin'; import Minio from './Minio'; import type { IStorageAdapterV2 } from 'nc-plugin'; class MinioPlugin extends XcStoragePlugin { private static storageAdapter: Minio; public getAdapter(): IStorageAdapterV2 { return MinioPlugin.storageAdapter; } public async init(config: any): Promise<any> { MinioPlugin.storageAdapter = new Minio(config); await MinioPlugin.storageAdapter.init(); } } export default MinioPlugin;
packages/nocodb/src/plugins/mino/MinioPlugin.ts
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00017732108244672418, 0.00017533800564706326, 0.00017335494339931756, 0.00017533800564706326, 0.000001983069523703307 ]
{ "id": 0, "code_window": [ "\n", "const emit = defineEmits(['update:modelValue'])\n", "\n", "const column = inject(ColumnInj)!\n", "\n", "const readOnly = inject(ReadonlyInj)!\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "const { isMobileMode } = useGlobal()\n", "\n" ], "file_path": "packages/nc-gui/components/cell/MultiSelect.vue", "type": "add", "edit_start_line_idx": 45 }
import { Inject, Injectable } from '@nestjs/common'; import type { ApiCreatedEvent, ApiTokenCreateEvent, ApiTokenDeleteEvent, AttachmentEvent, BaseEvent, FormColumnEvent, GridColumnEvent, MetaDiffEvent, OrgUserInviteEvent, PluginEvent, PluginTestEvent, ProjectUserResendInviteEvent, ProjectUserUpdateEvent, RelationEvent, SharedBaseEvent, SyncSourceEvent, UIAclEvent, UserEmailVerificationEvent, UserPasswordChangeEvent, UserPasswordForgotEvent, UserPasswordResetEvent, ViewColumnEvent, WebhookEvent, } from './interfaces'; import type { AppEvents } from 'nocodb-sdk'; import type { ColumnEvent, FilterEvent, ProjectCreateEvent, ProjectDeleteEvent, ProjectInviteEvent, ProjectUpdateEvent, SortEvent, TableEvent, UserSigninEvent, UserSignupEvent, ViewEvent, WelcomeEvent, } from '~/services/app-hooks/interfaces'; import { IEventEmitter } from '~/modules/event-emitter/event-emitter.interface'; const ALL_EVENTS = '__nc_all_events__'; @Injectable() export class AppHooksService { protected listenerUnsubscribers: Map<(...args: any[]) => void, () => void> = new Map(); constructor( @Inject('IEventEmitter') protected readonly eventEmitter: IEventEmitter, ) {} on( event: AppEvents.PROJECT_INVITE, listener: (data: ProjectInviteEvent) => void, ): () => void; on( event: AppEvents.PROJECT_CREATE, listener: (data: ProjectCreateEvent) => void, ): () => void; on( event: AppEvents.PROJECT_UPDATE, listener: (data: ProjectUpdateEvent) => void, ): () => void; on( event: AppEvents.PROJECT_DELETE, listener: (data: ProjectDeleteEvent) => void, ): () => void; on( event: AppEvents.USER_SIGNUP, listener: (data: UserSignupEvent) => void, ): () => void; on( event: AppEvents.USER_SIGNIN, listener: (data: UserSigninEvent) => void, ): () => void; on( event: AppEvents.WELCOME, listener: (data: WelcomeEvent) => void, ): () => void; on( event: | AppEvents.TABLE_CREATE | AppEvents.TABLE_DELETE | AppEvents.TABLE_UPDATE, listener: (data: TableEvent) => void, ): () => void; on( event: | AppEvents.VIEW_UPDATE | AppEvents.VIEW_DELETE | AppEvents.VIEW_CREATE | AppEvents.SHARED_VIEW_UPDATE | AppEvents.SHARED_VIEW_DELETE | AppEvents.SHARED_VIEW_CREATE, listener: (data: ViewEvent) => void, ): () => void; on( event: | AppEvents.FILTER_UPDATE | AppEvents.FILTER_DELETE | AppEvents.FILTER_CREATE, listener: (data: FilterEvent) => void, ): () => void; on( event: | AppEvents.SORT_UPDATE | AppEvents.SORT_DELETE | AppEvents.SORT_CREATE, listener: (data: SortEvent) => void, ): () => void; on( event: | AppEvents.COLUMN_UPDATE | AppEvents.COLUMN_DELETE | AppEvents.COLUMN_CREATE, listener: (data: ColumnEvent) => void, ): () => void; on(event, listener): () => void { const unsubscribe = this.eventEmitter.on(event, listener); this.listenerUnsubscribers.set(listener, unsubscribe); return unsubscribe; } emit(event: AppEvents.PROJECT_INVITE, data: ProjectInviteEvent): void; emit(event: AppEvents.PROJECT_CREATE, data: ProjectCreateEvent): void; emit(event: AppEvents.PROJECT_DELETE, data: ProjectDeleteEvent): void; emit(event: AppEvents.PROJECT_UPDATE, data: ProjectUpdateEvent): void; emit(event: AppEvents.USER_SIGNUP, data: UserSignupEvent): void; emit(event: AppEvents.USER_SIGNIN, data: UserSigninEvent): void; emit(event: AppEvents.APIS_CREATED, data: ApiCreatedEvent): void; emit( event: AppEvents.USER_PASSWORD_CHANGE, data: UserPasswordChangeEvent, ): void; emit( event: AppEvents.USER_PASSWORD_FORGOT, data: UserPasswordForgotEvent, ): void; emit( event: AppEvents.USER_PASSWORD_RESET, data: UserPasswordResetEvent, ): void; emit(event: AppEvents.WELCOME, data: WelcomeEvent): void; emit( event: AppEvents.PROJECT_USER_UPDATE, data: ProjectUserUpdateEvent, ): void; emit( event: AppEvents.PROJECT_USER_RESEND_INVITE, data: ProjectUserResendInviteEvent, ): void; emit( event: | AppEvents.VIEW_UPDATE | AppEvents.VIEW_DELETE | AppEvents.VIEW_CREATE | AppEvents.SHARED_VIEW_UPDATE | AppEvents.SHARED_VIEW_DELETE | AppEvents.SHARED_VIEW_CREATE, data: ViewEvent, ): void; emit( event: | AppEvents.FILTER_UPDATE | AppEvents.FILTER_DELETE | AppEvents.FILTER_CREATE, data: FilterEvent, ): void; emit( event: | AppEvents.TABLE_UPDATE | AppEvents.TABLE_CREATE | AppEvents.TABLE_DELETE, data: TableEvent, ): void; emit( event: | AppEvents.SORT_UPDATE | AppEvents.SORT_CREATE | AppEvents.SORT_DELETE, data: SortEvent, ): void; emit( event: | AppEvents.COLUMN_UPDATE | AppEvents.COLUMN_CREATE | AppEvents.COLUMN_DELETE, data: ColumnEvent, ): void; emit( event: | AppEvents.WEBHOOK_UPDATE | AppEvents.WEBHOOK_CREATE | AppEvents.WEBHOOK_DELETE | AppEvents.WEBHOOK_TEST, data: WebhookEvent, ): void; emit( event: | AppEvents.SYNC_SOURCE_UPDATE | AppEvents.SYNC_SOURCE_CREATE | AppEvents.SYNC_SOURCE_DELETE, data: SyncSourceEvent, ): void; emit(event: AppEvents.API_TOKEN_CREATE, data: ApiTokenCreateEvent): void; emit(event: AppEvents.API_TOKEN_DELETE, data: ApiTokenDeleteEvent): void; emit(event: AppEvents.ORG_USER_INVITE, data: OrgUserInviteEvent): void; emit(event: AppEvents.ORG_USER_RESEND_INVITE, data: OrgUserInviteEvent): void; emit( event: AppEvents.VIEW_COLUMN_CREATE | AppEvents.VIEW_COLUMN_UPDATE, data: ViewColumnEvent, ): void; emit( event: AppEvents.RELATION_DELETE | AppEvents.RELATION_CREATE, data: RelationEvent, ): void; emit(event: AppEvents.PLUGIN_TEST, data: PluginTestEvent): void; emit( event: AppEvents.PLUGIN_INSTALL | AppEvents.PLUGIN_UNINSTALL, data: PluginEvent, ): void; emit( event: | AppEvents.SHARED_BASE_GENERATE_LINK | AppEvents.SHARED_BASE_DELETE_LINK, data: SharedBaseEvent, ): void; emit( event: | AppEvents.BASE_UPDATE | AppEvents.BASE_DELETE | AppEvents.BASE_CREATE, data: BaseEvent, ): void; emit(event: AppEvents.ATTACHMENT_UPLOAD, data: AttachmentEvent): void; emit(event: AppEvents.FORM_COLUMN_UPDATE, data: FormColumnEvent): void; emit(event: AppEvents.GRID_COLUMN_UPDATE, data: GridColumnEvent): void; emit(event: AppEvents.META_DIFF_SYNC, data: MetaDiffEvent): void; emit(event: AppEvents.UI_ACL_UPDATE, data: UIAclEvent): void; emit(event: AppEvents.ORG_API_TOKEN_CREATE, data: ApiTokenCreateEvent): void; emit(event: AppEvents.ORG_API_TOKEN_DELETE, data: ApiTokenDeleteEvent): void; emit( event: AppEvents.USER_EMAIL_VERIFICATION, data: UserEmailVerificationEvent, ): void; emit(event, data): void { this.eventEmitter.emit(event, data); this.eventEmitter.emit(ALL_EVENTS, { event, data: data }); } removeListener( event: AppEvents | 'notification', listener: (args: any) => void, ) { this.listenerUnsubscribers.get(listener)?.(); this.listenerUnsubscribers.delete(listener); } removeListeners(event: AppEvents | 'notification') { return this.eventEmitter.removeAllListeners(event); } removeAllListener(listener) { this.listenerUnsubscribers.get(listener)?.(); this.listenerUnsubscribers.delete(listener); } onAll( listener: (payload: { event: AppEvents | 'notification'; data: any; }) => void, ) { const unsubscribe = this.eventEmitter.on(ALL_EVENTS, listener); this.listenerUnsubscribers.set(listener, unsubscribe); return unsubscribe; } }
packages/nocodb/src/services/app-hooks/app-hooks.service.ts
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.9738590121269226, 0.037593137472867966, 0.00016787798085715622, 0.0002054507058346644, 0.1775861382484436 ]
{ "id": 0, "code_window": [ "\n", "const emit = defineEmits(['update:modelValue'])\n", "\n", "const column = inject(ColumnInj)!\n", "\n", "const readOnly = inject(ReadonlyInj)!\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "const { isMobileMode } = useGlobal()\n", "\n" ], "file_path": "packages/nc-gui/components/cell/MultiSelect.vue", "type": "add", "edit_start_line_idx": 45 }
import type { BaseType, ColumnType, FilterType, MetaType, PaginatedType, Roles, RolesObj, ViewTypes } from 'nocodb-sdk' import type { I18n } from 'vue-i18n' import type { Theme as AntTheme } from 'ant-design-vue/es/config-provider' import type { UploadFile } from 'ant-design-vue' import type { ImportSource, ImportType, TabType } from './enums' import type { rolePermissions } from './constants' interface User { id: string email: string firstname: string | null lastname: string | null roles: RolesObj base_roles: RolesObj workspace_roles: RolesObj invite_token?: string base_id?: string display_name?: string | null } interface ProjectMetaInfo { Node?: string Arch?: string Platform?: string Docker?: boolean Database?: string ProjectOnRootDB?: boolean RootDB?: string PackageVersion?: string } interface Field { order: number show: number | boolean title: string fk_column_id?: string system?: boolean isViewEssentialField?: boolean } type Filter = FilterType & { field?: string status?: 'update' | 'delete' | 'create' parentId?: string readOnly?: boolean } type NocoI18n = I18n<{}, unknown, unknown, string, false> interface ThemeConfig extends AntTheme { primaryColor: string accentColor: string } interface Row { row: Record<string, any> oldRow: Record<string, any> rowMeta: { new?: boolean selected?: boolean commentCount?: number changed?: boolean saving?: boolean // use in datetime picker component isUpdatedFromCopyNPaste?: Record<string, boolean> } } type RolePermissions = Omit<typeof rolePermissions, 'guest' | 'admin' | 'super'> type GetKeys<T> = T extends Record<any, Record<infer Key, boolean>> ? Key : never type Permission<K extends keyof RolePermissions = keyof RolePermissions> = RolePermissions[K] extends Record<any, any> ? GetKeys<RolePermissions[K]> : never interface TabItem { type: TabType title: string id?: string viewTitle?: string viewId?: string sortsState?: Map<string, any> filterState?: Map<string, any> meta?: MetaType tabMeta?: any baseId?: string } interface SharedViewMeta extends Record<string, any> { surveyMode?: boolean transitionDuration?: number // in ms withTheme?: boolean theme?: Partial<ThemeConfig> allowCSVDownload?: boolean rtl?: boolean } interface SharedView { uuid?: string id: string password?: string type?: ViewTypes meta: SharedViewMeta } type importFileList = (UploadFile & { data: string | ArrayBuffer })[] type streamImportFileList = UploadFile[] type Nullable<T> = { [K in keyof T]: T[K] | null } /** * @description: Base type for frontend */ type NcProject = BaseType & { /** * When base is expanded in sidebar * */ isExpanded?: boolean /** * When base's content is being fetched i.e tables, views, etc */ isLoading?: boolean temp_title?: string edit?: boolean starred?: boolean uuid?: string } interface UndoRedoAction { undo: { fn: Function; args: any[] } redo: { fn: Function; args: any[] } scope?: { key: string; param: string | string[] }[] } interface ImportWorkerPayload { importType: ImportType importSource: ImportSource value: any config: Record<string, any> } interface Group { key: string column: ColumnType color: string count: number nestedIn: GroupNestedIn[] paginationData: PaginatedType nested: boolean children?: Group[] rows?: Row[] root?: boolean } interface GroupNestedIn { title: string column_name: string key: string column_uidt: string } interface Users { emails?: string role: Roles invitationToken?: string } type ViewPageType = 'view' | 'webhook' | 'api' | 'field' | 'relation' type NcButtonSize = 'xxsmall' | 'xsmall' | 'small' | 'medium' export { User, ProjectMetaInfo, Field, Filter, NocoI18n, ThemeConfig, Row, RolePermissions, Permission, TabItem, SharedView, SharedViewMeta, importFileList, streamImportFileList, Nullable, NcProject, UndoRedoAction, ImportWorkerPayload, Group, GroupNestedIn, Users, ViewPageType, NcButtonSize, }
packages/nc-gui/lib/types.ts
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.002440760377794504, 0.00028736278181895614, 0.00016828955267556012, 0.00017383796512149274, 0.0004940463113598526 ]
{ "id": 1, "code_window": [ " :placeholder=\"isEditColumn ? $t('labels.optional') : ''\"\n", " :bordered=\"false\"\n", " clear-icon\n", " show-search\n", " :show-arrow=\"editAllowed && !(readOnly || isLockedMode)\"\n", " :open=\"isOpen && editAllowed\"\n", " :disabled=\"readOnly || !editAllowed || isLockedMode\"\n", " :class=\"{ 'caret-transparent': !hasEditRoles }\"\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " :show-search=\"!isMobileMode\"\n" ], "file_path": "packages/nc-gui/components/cell/MultiSelect.vue", "type": "replace", "edit_start_line_idx": 385 }
<script lang="ts" setup> import { onUnmounted } from '@vue/runtime-core' import { message } from 'ant-design-vue' import tinycolor from 'tinycolor2' import type { Select as AntSelect } from 'ant-design-vue' import type { SelectOptionType } from 'nocodb-sdk' import { ActiveCellInj, CellClickHookInj, ColumnInj, EditColumnInj, EditModeInj, IsFormInj, IsKanbanInj, ReadonlyInj, computed, enumColor, extractSdkResponseErrorMsg, iconMap, inject, isDrawerOrModalExist, ref, useBase, useEventListener, useRoles, useSelectedCellKeyupListener, watch, } from '#imports' interface Props { modelValue?: string | undefined rowIndex?: number disableOptionCreation?: boolean } const { modelValue, disableOptionCreation } = defineProps<Props>() const emit = defineEmits(['update:modelValue']) const column = inject(ColumnInj)! const readOnly = inject(ReadonlyInj)! const isLockedMode = inject(IsLockedInj, ref(false)) const isEditable = inject(EditModeInj, ref(false)) const activeCell = inject(ActiveCellInj, ref(false)) // use both ActiveCellInj or EditModeInj to determine the active state // since active will be false in case of form view const active = computed(() => activeCell.value || isEditable.value) const aselect = ref<typeof AntSelect>() const isOpen = ref(false) const isKanban = inject(IsKanbanInj, ref(false)) const isPublic = inject(IsPublicInj, ref(false)) const isEditColumn = inject(EditColumnInj, ref(false)) const isForm = inject(IsFormInj, ref(false)) const { $api } = useNuxtApp() const searchVal = ref() const { getMeta } = useMetas() const { isUIAllowed } = useRoles() const { isPg, isMysql } = useBase() // a variable to keep newly created option value // temporary until it's add the option to column meta const tempSelectedOptState = ref<string>() const isNewOptionCreateEnabled = computed(() => !isPublic.value && !disableOptionCreation && isUIAllowed('fieldEdit')) const options = computed<(SelectOptionType & { value: string })[]>(() => { if (column?.value.colOptions) { const opts = column.value.colOptions ? // todo: fix colOptions type, options does not exist as a property (column.value.colOptions as any).options.filter((el: SelectOptionType) => el.title !== '') || [] : [] for (const op of opts.filter((el: any) => el.order === null)) { op.title = op.title.replace(/^'/, '').replace(/'$/, '') } return opts.map((o: any) => ({ ...o, value: o.title })) } return [] }) const isOptionMissing = computed(() => { return (options.value ?? []).every((op) => op.title !== searchVal.value) }) const hasEditRoles = computed(() => isUIAllowed('dataEdit')) const editAllowed = computed(() => (hasEditRoles.value || isForm.value) && active.value) const vModel = computed({ get: () => tempSelectedOptState.value ?? modelValue?.trim(), set: (val) => { if (val && isNewOptionCreateEnabled.value && (options.value ?? []).every((op) => op.title !== val)) { tempSelectedOptState.value = val return addIfMissingAndSave() } emit('update:modelValue', val || null) }, }) watch(isOpen, (n, _o) => { if (editAllowed.value) { if (!n) { aselect.value?.$el?.querySelector('input')?.blur() } else { aselect.value?.$el?.querySelector('input')?.focus() } } }) useSelectedCellKeyupListener(activeCell, (e) => { switch (e.key) { case 'Escape': isOpen.value = false break case 'Enter': if (editAllowed.value && active.value && !isOpen.value) { isOpen.value = true } break // skip space bar key press since it's used for expand row case ' ': break default: if (!editAllowed.value) { e.preventDefault() break } // toggle only if char key pressed if (!(e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) && e.key?.length === 1 && !isDrawerOrModalExist()) { e.stopPropagation() isOpen.value = true } break } }) // close dropdown list on escape useSelectedCellKeyupListener(isOpen, (e) => { if (e.key === 'Escape') isOpen.value = false }) async function addIfMissingAndSave() { if (!tempSelectedOptState.value || isPublic.value) return false const newOptValue = tempSelectedOptState.value searchVal.value = '' tempSelectedOptState.value = undefined if (newOptValue && !options.value.some((o) => o.title === newOptValue)) { try { options.value.push({ title: newOptValue, value: newOptValue, color: enumColor.light[(options.value.length + 1) % enumColor.light.length], }) column.value.colOptions = { options: options.value.map(({ value: _, ...rest }) => rest) } const updatedColMeta = { ...column.value } // todo: refactor and avoid repetition if (updatedColMeta.cdf) { // Postgres returns default value wrapped with single quotes & casted with type so we have to get value between single quotes to keep it unified for all databases if (isPg(column.value.source_id)) { updatedColMeta.cdf = updatedColMeta.cdf.substring( updatedColMeta.cdf.indexOf(`'`) + 1, updatedColMeta.cdf.lastIndexOf(`'`), ) } // Mysql escapes single quotes with backslash so we keep quotes but others have to unescaped if (!isMysql(column.value.source_id) && !isPg(column.value.source_id)) { updatedColMeta.cdf = updatedColMeta.cdf.replace(/''/g, "'") } } await $api.dbTableColumn.update( (column.value as { fk_column_id?: string })?.fk_column_id || (column.value?.id as string), updatedColMeta, ) vModel.value = newOptValue await getMeta(column.value.fk_model_id!, true) } catch (e: any) { console.log(e) message.error(await extractSdkResponseErrorMsg(e)) } } } const search = () => { searchVal.value = aselect.value?.$el?.querySelector('.ant-select-selection-search-input')?.value } // prevent propagation of keydown event if select is open const onKeydown = (e: KeyboardEvent) => { if (isOpen.value && active.value) { e.stopPropagation() } if (e.key === 'Enter') { e.stopPropagation() } } const onSelect = () => { isOpen.value = false isEditable.value = false } const cellClickHook = inject(CellClickHookInj, null) const toggleMenu = (e: Event) => { // todo: refactor // check clicked element is clear icon if ( (e.target as HTMLElement)?.classList.contains('ant-select-clear') || (e.target as HTMLElement)?.closest('.ant-select-clear') ) { vModel.value = '' return e.stopPropagation() } if (cellClickHook) return isOpen.value = editAllowed.value && !isOpen.value } const cellClickHookHandler = () => { isOpen.value = editAllowed.value && !isOpen.value } onMounted(() => { cellClickHook?.on(cellClickHookHandler) }) onUnmounted(() => { cellClickHook?.on(cellClickHookHandler) }) const handleClose = (e: MouseEvent) => { if (isOpen.value && aselect.value && !aselect.value.$el.contains(e.target)) { isOpen.value = false } } useEventListener(document, 'click', handleClose, true) const selectedOpt = computed(() => { return options.value.find((o) => o.value === vModel.value) }) </script> <template> <div class="h-full w-full flex items-center nc-single-select" :class="{ 'read-only': readOnly || isLockedMode }" @click="toggleMenu" > <div v-if="!(active || isEditable)"> <a-tag v-if="selectedOpt" class="rounded-tag" :color="selectedOpt.color"> <span :style="{ 'color': tinycolor.isReadable(selectedOpt.color || '#ccc', '#fff', { level: 'AA', size: 'large' }) ? '#fff' : tinycolor.mostReadable(selectedOpt.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '13px', }" :class="{ 'text-sm': isKanban }" > {{ selectedOpt.title }} </span> </a-tag> </div> <a-select v-else ref="aselect" v-model:value="vModel" class="w-full overflow-hidden" :class="{ 'caret-transparent': !hasEditRoles }" :placeholder="isEditColumn ? $t('labels.optional') : ''" :allow-clear="!column.rqd && editAllowed" :bordered="false" :open="isOpen && editAllowed" :disabled="readOnly || !editAllowed || isLockedMode" :show-arrow="hasEditRoles && !(readOnly || isLockedMode) && active && vModel === null" :dropdown-class-name="`nc-dropdown-single-select-cell ${isOpen && active ? 'active' : ''}`" :show-search="isOpen && active" @select="onSelect" @keydown="onKeydown($event)" @search="search" > <a-select-option v-for="op of options" :key="op.title" :value="op.title" :data-testid="`select-option-${column.title}-${rowIndex}`" :class="`nc-select-option-${column.title}-${op.title}`" @click.stop > <a-tag class="rounded-tag" :color="op.color"> <span :style="{ 'color': tinycolor.isReadable(op.color || '#ccc', '#fff', { level: 'AA', size: 'large' }) ? '#fff' : tinycolor.mostReadable(op.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '13px', }" :class="{ 'text-sm': isKanban }" > {{ op.title }} </span> </a-tag> </a-select-option> <a-select-option v-if="searchVal && isOptionMissing && isNewOptionCreateEnabled" :key="searchVal" :value="searchVal"> <div class="flex gap-2 text-gray-500 items-center h-full"> <component :is="iconMap.plusThick" class="min-w-4" /> <div class="text-xs whitespace-normal"> {{ $t('msg.selectOption.createNewOptionNamed') }} <strong>{{ searchVal }}</strong> </div> </div> </a-select-option> </a-select> </div> </template> <style scoped lang="scss"> .rounded-tag { @apply py-0 px-[12px] rounded-[12px]; } :deep(.ant-tag) { @apply "rounded-tag" my-[2px]; } :deep(.ant-select-clear) { opacity: 1; } .nc-single-select:not(.read-only) { :deep(.ant-select-selector), :deep(.ant-select-selector input) { @apply !cursor-pointer; } } :deep(.ant-select-selector) { @apply !px-0; } :deep(.ant-select-selection-search-input) { @apply !text-xs; } :deep(.ant-select-clear > span) { @apply block; } </style>
packages/nc-gui/components/cell/SingleSelect.vue
1
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.0996827706694603, 0.0037502397317439318, 0.00016403803601861, 0.0001729656069073826, 0.016110561788082123 ]
{ "id": 1, "code_window": [ " :placeholder=\"isEditColumn ? $t('labels.optional') : ''\"\n", " :bordered=\"false\"\n", " clear-icon\n", " show-search\n", " :show-arrow=\"editAllowed && !(readOnly || isLockedMode)\"\n", " :open=\"isOpen && editAllowed\"\n", " :disabled=\"readOnly || !editAllowed || isLockedMode\"\n", " :class=\"{ 'caret-transparent': !hasEditRoles }\"\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " :show-search=\"!isMobileMode\"\n" ], "file_path": "packages/nc-gui/components/cell/MultiSelect.vue", "type": "replace", "edit_start_line_idx": 385 }
import { getModelPaths, getViewPaths } from './templates/paths'; import type { Base, Model } from '~/models'; import type { SwaggerColumn } from './getSwaggerColumnMetas'; import type { SwaggerView } from './getSwaggerJSON'; import Noco from '~/Noco'; export default async function getPaths( { base, model, columns, views, }: { base: Base; model: Model; columns: SwaggerColumn[]; views: SwaggerView[]; }, _ncMeta = Noco.ncMeta, ) { const swaggerPaths = await getModelPaths({ tableName: model.title, type: model.type, orgs: 'v1', columns, baseName: base.id, }); for (const { view, columns: viewColumns } of views) { const swaggerColumns = columns.filter( (c) => viewColumns.find((vc) => vc.fk_column_id === c.column.id)?.show, ); Object.assign( swaggerPaths, await getViewPaths({ tableName: model.title, viewName: view.title, type: model.type, orgs: 'v1', columns: swaggerColumns, baseName: base.id, }), ); } return swaggerPaths; }
packages/nocodb/src/services/api-docs/swagger/getPaths.ts
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00017398818454239517, 0.00016931918798945844, 0.00016395219427067786, 0.00017041231330949813, 0.000003908597136614844 ]
{ "id": 1, "code_window": [ " :placeholder=\"isEditColumn ? $t('labels.optional') : ''\"\n", " :bordered=\"false\"\n", " clear-icon\n", " show-search\n", " :show-arrow=\"editAllowed && !(readOnly || isLockedMode)\"\n", " :open=\"isOpen && editAllowed\"\n", " :disabled=\"readOnly || !editAllowed || isLockedMode\"\n", " :class=\"{ 'caret-transparent': !hasEditRoles }\"\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " :show-search=\"!isMobileMode\"\n" ], "file_path": "packages/nc-gui/components/cell/MultiSelect.vue", "type": "replace", "edit_start_line_idx": 385 }
import { AsyncDatabase } from 'promised-sqlite3'; async function sqliteExec(query) { const rootProjectDir = __dirname.replace('/scripts/playwright/setup', ''); const sqliteDb = await AsyncDatabase.open(`${rootProjectDir}/packages/nocodb/test_noco.db`); await sqliteDb.run(query); } export default sqliteExec;
tests/playwright/setup/sqliteExec.ts
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00017020526865962893, 0.00017020526865962893, 0.00017020526865962893, 0.00017020526865962893, 0 ]
{ "id": 1, "code_window": [ " :placeholder=\"isEditColumn ? $t('labels.optional') : ''\"\n", " :bordered=\"false\"\n", " clear-icon\n", " show-search\n", " :show-arrow=\"editAllowed && !(readOnly || isLockedMode)\"\n", " :open=\"isOpen && editAllowed\"\n", " :disabled=\"readOnly || !editAllowed || isLockedMode\"\n", " :class=\"{ 'caret-transparent': !hasEditRoles }\"\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " :show-search=\"!isMobileMode\"\n" ], "file_path": "packages/nc-gui/components/cell/MultiSelect.vue", "type": "replace", "edit_start_line_idx": 385 }
import { IWebhookNotificationAdapter } from '../index'; import XcPlugin from './XcPlugin'; abstract class XcStoragePlugin extends XcPlugin { abstract getAdapter(): IWebhookNotificationAdapter; } export default XcStoragePlugin;
packages/nc-plugin/src/lib/XcWebhookNotificationPlugin.ts
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00017439626390114427, 0.00017439626390114427, 0.00017439626390114427, 0.00017439626390114427, 0 ]
{ "id": 2, "code_window": [ " :dropdown-class-name=\"`nc-dropdown-multi-select-cell ${isOpen ? 'active' : ''}`\"\n", " @search=\"search\"\n", " @keydown.stop\n", " >\n", " <a-select-option\n", " v-for=\"op of options\"\n", " :key=\"op.id || op.title\"\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " <template #suffixIcon>\n", " <GeneralIcon icon=\"arrowDown\" class=\"text-gray-700 nc-select-expand-btn\" />\n", " </template>\n" ], "file_path": "packages/nc-gui/components/cell/MultiSelect.vue", "type": "add", "edit_start_line_idx": 394 }
<script lang="ts" setup> import { onUnmounted } from '@vue/runtime-core' import { message } from 'ant-design-vue' import tinycolor from 'tinycolor2' import type { Select as AntSelect } from 'ant-design-vue' import type { SelectOptionType } from 'nocodb-sdk' import { ActiveCellInj, CellClickHookInj, ColumnInj, EditColumnInj, EditModeInj, IsFormInj, IsKanbanInj, ReadonlyInj, computed, enumColor, extractSdkResponseErrorMsg, iconMap, inject, isDrawerOrModalExist, ref, useBase, useEventListener, useRoles, useSelectedCellKeyupListener, watch, } from '#imports' interface Props { modelValue?: string | undefined rowIndex?: number disableOptionCreation?: boolean } const { modelValue, disableOptionCreation } = defineProps<Props>() const emit = defineEmits(['update:modelValue']) const column = inject(ColumnInj)! const readOnly = inject(ReadonlyInj)! const isLockedMode = inject(IsLockedInj, ref(false)) const isEditable = inject(EditModeInj, ref(false)) const activeCell = inject(ActiveCellInj, ref(false)) // use both ActiveCellInj or EditModeInj to determine the active state // since active will be false in case of form view const active = computed(() => activeCell.value || isEditable.value) const aselect = ref<typeof AntSelect>() const isOpen = ref(false) const isKanban = inject(IsKanbanInj, ref(false)) const isPublic = inject(IsPublicInj, ref(false)) const isEditColumn = inject(EditColumnInj, ref(false)) const isForm = inject(IsFormInj, ref(false)) const { $api } = useNuxtApp() const searchVal = ref() const { getMeta } = useMetas() const { isUIAllowed } = useRoles() const { isPg, isMysql } = useBase() // a variable to keep newly created option value // temporary until it's add the option to column meta const tempSelectedOptState = ref<string>() const isNewOptionCreateEnabled = computed(() => !isPublic.value && !disableOptionCreation && isUIAllowed('fieldEdit')) const options = computed<(SelectOptionType & { value: string })[]>(() => { if (column?.value.colOptions) { const opts = column.value.colOptions ? // todo: fix colOptions type, options does not exist as a property (column.value.colOptions as any).options.filter((el: SelectOptionType) => el.title !== '') || [] : [] for (const op of opts.filter((el: any) => el.order === null)) { op.title = op.title.replace(/^'/, '').replace(/'$/, '') } return opts.map((o: any) => ({ ...o, value: o.title })) } return [] }) const isOptionMissing = computed(() => { return (options.value ?? []).every((op) => op.title !== searchVal.value) }) const hasEditRoles = computed(() => isUIAllowed('dataEdit')) const editAllowed = computed(() => (hasEditRoles.value || isForm.value) && active.value) const vModel = computed({ get: () => tempSelectedOptState.value ?? modelValue?.trim(), set: (val) => { if (val && isNewOptionCreateEnabled.value && (options.value ?? []).every((op) => op.title !== val)) { tempSelectedOptState.value = val return addIfMissingAndSave() } emit('update:modelValue', val || null) }, }) watch(isOpen, (n, _o) => { if (editAllowed.value) { if (!n) { aselect.value?.$el?.querySelector('input')?.blur() } else { aselect.value?.$el?.querySelector('input')?.focus() } } }) useSelectedCellKeyupListener(activeCell, (e) => { switch (e.key) { case 'Escape': isOpen.value = false break case 'Enter': if (editAllowed.value && active.value && !isOpen.value) { isOpen.value = true } break // skip space bar key press since it's used for expand row case ' ': break default: if (!editAllowed.value) { e.preventDefault() break } // toggle only if char key pressed if (!(e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) && e.key?.length === 1 && !isDrawerOrModalExist()) { e.stopPropagation() isOpen.value = true } break } }) // close dropdown list on escape useSelectedCellKeyupListener(isOpen, (e) => { if (e.key === 'Escape') isOpen.value = false }) async function addIfMissingAndSave() { if (!tempSelectedOptState.value || isPublic.value) return false const newOptValue = tempSelectedOptState.value searchVal.value = '' tempSelectedOptState.value = undefined if (newOptValue && !options.value.some((o) => o.title === newOptValue)) { try { options.value.push({ title: newOptValue, value: newOptValue, color: enumColor.light[(options.value.length + 1) % enumColor.light.length], }) column.value.colOptions = { options: options.value.map(({ value: _, ...rest }) => rest) } const updatedColMeta = { ...column.value } // todo: refactor and avoid repetition if (updatedColMeta.cdf) { // Postgres returns default value wrapped with single quotes & casted with type so we have to get value between single quotes to keep it unified for all databases if (isPg(column.value.source_id)) { updatedColMeta.cdf = updatedColMeta.cdf.substring( updatedColMeta.cdf.indexOf(`'`) + 1, updatedColMeta.cdf.lastIndexOf(`'`), ) } // Mysql escapes single quotes with backslash so we keep quotes but others have to unescaped if (!isMysql(column.value.source_id) && !isPg(column.value.source_id)) { updatedColMeta.cdf = updatedColMeta.cdf.replace(/''/g, "'") } } await $api.dbTableColumn.update( (column.value as { fk_column_id?: string })?.fk_column_id || (column.value?.id as string), updatedColMeta, ) vModel.value = newOptValue await getMeta(column.value.fk_model_id!, true) } catch (e: any) { console.log(e) message.error(await extractSdkResponseErrorMsg(e)) } } } const search = () => { searchVal.value = aselect.value?.$el?.querySelector('.ant-select-selection-search-input')?.value } // prevent propagation of keydown event if select is open const onKeydown = (e: KeyboardEvent) => { if (isOpen.value && active.value) { e.stopPropagation() } if (e.key === 'Enter') { e.stopPropagation() } } const onSelect = () => { isOpen.value = false isEditable.value = false } const cellClickHook = inject(CellClickHookInj, null) const toggleMenu = (e: Event) => { // todo: refactor // check clicked element is clear icon if ( (e.target as HTMLElement)?.classList.contains('ant-select-clear') || (e.target as HTMLElement)?.closest('.ant-select-clear') ) { vModel.value = '' return e.stopPropagation() } if (cellClickHook) return isOpen.value = editAllowed.value && !isOpen.value } const cellClickHookHandler = () => { isOpen.value = editAllowed.value && !isOpen.value } onMounted(() => { cellClickHook?.on(cellClickHookHandler) }) onUnmounted(() => { cellClickHook?.on(cellClickHookHandler) }) const handleClose = (e: MouseEvent) => { if (isOpen.value && aselect.value && !aselect.value.$el.contains(e.target)) { isOpen.value = false } } useEventListener(document, 'click', handleClose, true) const selectedOpt = computed(() => { return options.value.find((o) => o.value === vModel.value) }) </script> <template> <div class="h-full w-full flex items-center nc-single-select" :class="{ 'read-only': readOnly || isLockedMode }" @click="toggleMenu" > <div v-if="!(active || isEditable)"> <a-tag v-if="selectedOpt" class="rounded-tag" :color="selectedOpt.color"> <span :style="{ 'color': tinycolor.isReadable(selectedOpt.color || '#ccc', '#fff', { level: 'AA', size: 'large' }) ? '#fff' : tinycolor.mostReadable(selectedOpt.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '13px', }" :class="{ 'text-sm': isKanban }" > {{ selectedOpt.title }} </span> </a-tag> </div> <a-select v-else ref="aselect" v-model:value="vModel" class="w-full overflow-hidden" :class="{ 'caret-transparent': !hasEditRoles }" :placeholder="isEditColumn ? $t('labels.optional') : ''" :allow-clear="!column.rqd && editAllowed" :bordered="false" :open="isOpen && editAllowed" :disabled="readOnly || !editAllowed || isLockedMode" :show-arrow="hasEditRoles && !(readOnly || isLockedMode) && active && vModel === null" :dropdown-class-name="`nc-dropdown-single-select-cell ${isOpen && active ? 'active' : ''}`" :show-search="isOpen && active" @select="onSelect" @keydown="onKeydown($event)" @search="search" > <a-select-option v-for="op of options" :key="op.title" :value="op.title" :data-testid="`select-option-${column.title}-${rowIndex}`" :class="`nc-select-option-${column.title}-${op.title}`" @click.stop > <a-tag class="rounded-tag" :color="op.color"> <span :style="{ 'color': tinycolor.isReadable(op.color || '#ccc', '#fff', { level: 'AA', size: 'large' }) ? '#fff' : tinycolor.mostReadable(op.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '13px', }" :class="{ 'text-sm': isKanban }" > {{ op.title }} </span> </a-tag> </a-select-option> <a-select-option v-if="searchVal && isOptionMissing && isNewOptionCreateEnabled" :key="searchVal" :value="searchVal"> <div class="flex gap-2 text-gray-500 items-center h-full"> <component :is="iconMap.plusThick" class="min-w-4" /> <div class="text-xs whitespace-normal"> {{ $t('msg.selectOption.createNewOptionNamed') }} <strong>{{ searchVal }}</strong> </div> </div> </a-select-option> </a-select> </div> </template> <style scoped lang="scss"> .rounded-tag { @apply py-0 px-[12px] rounded-[12px]; } :deep(.ant-tag) { @apply "rounded-tag" my-[2px]; } :deep(.ant-select-clear) { opacity: 1; } .nc-single-select:not(.read-only) { :deep(.ant-select-selector), :deep(.ant-select-selector input) { @apply !cursor-pointer; } } :deep(.ant-select-selector) { @apply !px-0; } :deep(.ant-select-selection-search-input) { @apply !text-xs; } :deep(.ant-select-clear > span) { @apply block; } </style>
packages/nc-gui/components/cell/SingleSelect.vue
1
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.008202832192182541, 0.0008956050151027739, 0.00016461245832033455, 0.00019915141456294805, 0.001811652327887714 ]
{ "id": 2, "code_window": [ " :dropdown-class-name=\"`nc-dropdown-multi-select-cell ${isOpen ? 'active' : ''}`\"\n", " @search=\"search\"\n", " @keydown.stop\n", " >\n", " <a-select-option\n", " v-for=\"op of options\"\n", " :key=\"op.id || op.title\"\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " <template #suffixIcon>\n", " <GeneralIcon icon=\"arrowDown\" class=\"text-gray-700 nc-select-expand-btn\" />\n", " </template>\n" ], "file_path": "packages/nc-gui/components/cell/MultiSelect.vue", "type": "add", "edit_start_line_idx": 394 }
import { Test } from '@nestjs/testing'; import { ProjectUsersService } from '../services/base-users/base-users.service'; import { ProjectUsersController } from './base-users.controller'; import type { TestingModule } from '@nestjs/testing'; describe('ProjectUsersController', () => { let controller: ProjectUsersController; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ controllers: [ProjectUsersController], providers: [ProjectUsersService], }).compile(); controller = module.get<ProjectUsersController>(ProjectUsersController); }); it('should be defined', () => { expect(controller).toBeDefined(); }); });
packages/nocodb/src/controllers/base-users.controller.spec.ts
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00017691237735562027, 0.00017542834393680096, 0.00017452768224757165, 0.00017484500131104141, 0.0000010573292001936352 ]
{ "id": 2, "code_window": [ " :dropdown-class-name=\"`nc-dropdown-multi-select-cell ${isOpen ? 'active' : ''}`\"\n", " @search=\"search\"\n", " @keydown.stop\n", " >\n", " <a-select-option\n", " v-for=\"op of options\"\n", " :key=\"op.id || op.title\"\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " <template #suffixIcon>\n", " <GeneralIcon icon=\"arrowDown\" class=\"text-gray-700 nc-select-expand-btn\" />\n", " </template>\n" ], "file_path": "packages/nc-gui/components/cell/MultiSelect.vue", "type": "add", "edit_start_line_idx": 394 }
const {DbFactory} = require('../../build/main/index'); const path = require('path'); const glob = require('glob'); let models = {}; const password = process.env.NODE_ENV === 'test' ? '' : 'password'; dbDriver = DbFactory.create({ "client": "mysql", "connection": { "host": "localhost", "port": "3306", "user": "root", "password": password, "database": "sakila" } }); let modelsPath = path.join(__dirname, '*.model.js'); dbDriver = dbDriver || {}; glob.sync(modelsPath).forEach((file) => { let model = require(file) models[model.name] = new model({dbDriver}); }); module.exports = models;
packages/nocodb/src/db/sql-data-mapper/__tests__/models/index.js
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00017624144675210118, 0.00017413438763469458, 0.0001728907518554479, 0.00017327099340036511, 0.0000014979739262344083 ]
{ "id": 2, "code_window": [ " :dropdown-class-name=\"`nc-dropdown-multi-select-cell ${isOpen ? 'active' : ''}`\"\n", " @search=\"search\"\n", " @keydown.stop\n", " >\n", " <a-select-option\n", " v-for=\"op of options\"\n", " :key=\"op.id || op.title\"\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " <template #suffixIcon>\n", " <GeneralIcon icon=\"arrowDown\" class=\"text-gray-700 nc-select-expand-btn\" />\n", " </template>\n" ], "file_path": "packages/nc-gui/components/cell/MultiSelect.vue", "type": "add", "edit_start_line_idx": 394 }
<script lang="ts" setup> import { onKeyDown, useEventListener } from '@vueuse/core' import { useAttachmentCell } from './utils' import { useSortable } from './sort' import { iconMap, isImage, ref, useAttachment, useDropZone, useRoles, watch } from '#imports' const { isUIAllowed } = useRoles() const { open, isLoading, isPublic, isReadonly: readOnly, visibleItems, modalVisible, column, FileIcon, removeFile, onDrop, downloadFile, updateModelValue, selectedImage, selectedVisibleItems, bulkDownloadFiles, renameFile, } = useAttachmentCell()! const isLocked = inject(IsLockedInj, ref(false)) const dropZoneRef = ref<HTMLDivElement>() const sortableRef = ref<HTMLDivElement>() const { dragging } = useSortable(sortableRef, visibleItems, updateModelValue, readOnly) const { isOverDropZone } = useDropZone(dropZoneRef, onDrop) const { isSharedForm } = useSmartsheetStoreOrThrow() const { getPossibleAttachmentSrc, openAttachment } = useAttachment() onKeyDown('Escape', () => { modalVisible.value = false isOverDropZone.value = false }) function onClick(item: Record<string, any>) { selectedImage.value = item modalVisible.value = false const stopHandle = watch(selectedImage, (nextImage) => { if (!nextImage) { setTimeout(() => { modalVisible.value = true }, 50) stopHandle?.() } }) } const isModalOpen = ref(false) const filetoDelete = reactive({ title: '', i: 0, }) function onRemoveFileClick(title: any, i: number) { isModalOpen.value = true filetoDelete.i = i filetoDelete.title = title } // when user paste on modal useEventListener(dropZoneRef, 'paste', (event: ClipboardEvent) => { if (event.clipboardData?.files) { onDrop(event.clipboardData.files) } }) const handleFileDelete = (i: number) => { removeFile(i) isModalOpen.value = false filetoDelete.i = 0 filetoDelete.title = '' } </script> <template> <a-modal v-model:visible="modalVisible" class="nc-attachment-modal" :class="{ active: modalVisible }" width="80%" :footer="null" wrap-class-name="nc-modal-attachment-expand-cell" > <template #title> <div class="flex gap-4"> <div v-if="isSharedForm || (!readOnly && isUIAllowed('dataEdit') && !isPublic && !isLocked)" class="nc-attach-file group" data-testid="attachment-expand-file-picker-button" @click="open" > <MaterialSymbolsAttachFile class="transform group-hover:(text-accent scale-120)" /> {{ $t('activity.attachFile') }} </div> <div class="flex items-center gap-2"> <div v-if="readOnly" class="text-gray-400">[{{ $t('labels.readOnly') }}]</div> {{ $t('labels.viewingAttachmentsOf') }} <div class="font-semibold underline">{{ column?.title }}</div> </div> <div v-if="selectedVisibleItems.includes(true)" class="flex flex-1 items-center gap-3 justify-end mr-[30px]"> <NcButton type="primary" class="nc-attachment-download-all" @click="bulkDownloadFiles"> {{ $t('activity.bulkDownload') }} </NcButton> </div> </div> </template> <div ref="dropZoneRef" tabindex="0"> <template v-if="isSharedForm || (!readOnly && !dragging)"> <general-overlay v-model="isOverDropZone" inline class="text-white ring ring-accent ring-opacity-100 bg-gray-700/75 flex items-center justify-center gap-2 backdrop-blur-xl" > <MaterialSymbolsFileCopyOutline class="text-accent" height="35" width="35" /> <div class="text-white text-3xl">{{ $t('labels.dropHere') }}</div> </general-overlay> </template> <div ref="sortableRef" :class="{ dragging }" class="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-6 relative p-6"> <div v-for="(item, i) of visibleItems" :key="`${item.title}-${i}`" class="flex flex-col gap-1"> <a-card class="nc-attachment-item group"> <a-checkbox v-model:checked="selectedVisibleItems[i]" class="nc-attachment-checkbox group-hover:(opacity-100)" :class="{ '!opacity-100': selectedVisibleItems[i] }" /> <a-tooltip v-if="!readOnly"> <template #title> {{ $t('title.removeFile') }} </template> <component :is="iconMap.closeCircle" v-if="isSharedForm || (isUIAllowed('dataEdit') && !isPublic && !isLocked)" class="nc-attachment-remove" @click.stop="onRemoveFileClick(item.title, i)" /> </a-tooltip> <a-tooltip placement="bottom"> <template #title> {{ $t('title.downloadFile') }} </template> <div class="nc-attachment-download group-hover:(opacity-100)"> <component :is="iconMap.download" @click.stop="downloadFile(item)" /> </div> </a-tooltip> <a-tooltip v-if="isSharedForm || (!readOnly && isUIAllowed('dataEdit') && !isPublic && !isLocked)" placement="bottom"> <template #title> {{ $t('title.renameFile') }} </template> <div class="nc-attachment-download group-hover:(opacity-100) mr-[35px]"> <component :is="iconMap.edit" @click.stop="renameFile(item, i)" /> </div> </a-tooltip> <div :class="[dragging ? 'cursor-move' : 'cursor-pointer']" class="nc-attachment h-full w-full flex items-center justify-center overflow-hidden" > <LazyCellAttachmentImage v-if="isImage(item.title, item.mimetype)" :srcs="getPossibleAttachmentSrc(item)" class="object-cover h-64 m-auto justify-center" @click.stop="onClick(item)" /> <component :is="FileIcon(item.icon)" v-else-if="item.icon" height="150" width="150" @click.stop="openAttachment(item)" /> <IcOutlineInsertDriveFile v-else height="150" width="150" @click.stop="openAttachment(item)" /> </div> </a-card> <div class="truncate" :title="item.title"> {{ item.title }} </div> </div> <div v-if="isLoading" class="flex flex-col gap-1"> <a-card class="nc-attachment-item group"> <div class="nc-attachment h-full w-full flex items-center justify-center"> <a-skeleton-image class /> </div> </a-card> </div> </div> </div> <GeneralDeleteModal v-model:visible="isModalOpen" entity-name="File" :on-delete="() => handleFileDelete(filetoDelete.i)"> <template #entity-preview> <span> <div class="flex flex-row items-center py-2.25 px-2.5 bg-gray-50 rounded-lg text-gray-700 mb-4"> <GeneralIcon icon="file" class="nc-view-icon"></GeneralIcon> <div class="capitalize text-ellipsis overflow-hidden select-none w-full pl-1.75" :style="{ wordBreak: 'keep-all', whiteSpace: 'nowrap', display: 'inline' }" > {{ filetoDelete.title }} </div> </div> </span> </template> </GeneralDeleteModal> </a-modal> </template> <style lang="scss"> .nc-attachment-modal { .nc-attach-file { @apply select-none cursor-pointer color-transition flex items-center gap-1 border-1 p-2 rounded @apply hover:(bg-primary bg-opacity-10 text-primary ring); @apply active:(ring-accent ring-opacity-100 bg-primary bg-opacity-20); } .nc-attachment-item { @apply !h-2/3 !min-h-[200px] flex items-center justify-center relative; @supports (-moz-appearance: none) { @apply hover:border-0; } &::after { @apply pointer-events-none rounded absolute top-0 left-0 right-0 bottom-0 transition-all duration-150 ease-in-out; content: ''; } @supports (-moz-appearance: none) { &:hover::after { @apply ring shadow transform scale-103; } &:active::after { @apply ring ring-accent ring-opacity-100 shadow transform scale-103; } } } .nc-attachment-download { @apply bg-white absolute bottom-2 right-2; @apply transition-opacity duration-150 ease-in opacity-0 hover:ring; @apply cursor-pointer rounded shadow flex items-center p-1 border-1; @apply active:(ring border-0 ring-accent); } .nc-attachment-checkbox { @apply absolute top-2 left-2; @apply transition-opacity duration-150 ease-in opacity-0; } .nc-attachment-remove { @apply absolute top-2 right-2 bg-white; @apply hover:(ring ring-red-500); @apply cursor-pointer rounded-full border-2; @apply active:(ring border-0 ring-red-500); } .ant-card-body { @apply !p-2 w-full h-full; } .ant-modal-body { @apply !p-0; } .ghost, .ghost > * { @apply !pointer-events-none; } .dragging { .nc-attachment-item { @apply !pointer-events-none; } .ant-tooltip { @apply !hidden; } } } </style>
packages/nc-gui/components/cell/attachment/Modal.vue
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00020617913105525076, 0.0001709315984044224, 0.00016435509314760566, 0.00016860348114278167, 0.000007729398930678144 ]
{ "id": 3, "code_window": [ "\n", "const { modelValue, disableOptionCreation } = defineProps<Props>()\n", "\n", "const emit = defineEmits(['update:modelValue'])\n", "\n", "const column = inject(ColumnInj)!\n", "\n", "const readOnly = inject(ReadonlyInj)!\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "const { isMobileMode } = useGlobal()\n", "\n" ], "file_path": "packages/nc-gui/components/cell/SingleSelect.vue", "type": "add", "edit_start_line_idx": 39 }
<script lang="ts" setup> import { onUnmounted } from '@vue/runtime-core' import { message } from 'ant-design-vue' import tinycolor from 'tinycolor2' import type { Select as AntSelect } from 'ant-design-vue' import type { SelectOptionType } from 'nocodb-sdk' import { ActiveCellInj, CellClickHookInj, ColumnInj, EditColumnInj, EditModeInj, IsFormInj, IsKanbanInj, ReadonlyInj, computed, enumColor, extractSdkResponseErrorMsg, iconMap, inject, isDrawerOrModalExist, ref, useBase, useEventListener, useRoles, useSelectedCellKeyupListener, watch, } from '#imports' interface Props { modelValue?: string | undefined rowIndex?: number disableOptionCreation?: boolean } const { modelValue, disableOptionCreation } = defineProps<Props>() const emit = defineEmits(['update:modelValue']) const column = inject(ColumnInj)! const readOnly = inject(ReadonlyInj)! const isLockedMode = inject(IsLockedInj, ref(false)) const isEditable = inject(EditModeInj, ref(false)) const activeCell = inject(ActiveCellInj, ref(false)) // use both ActiveCellInj or EditModeInj to determine the active state // since active will be false in case of form view const active = computed(() => activeCell.value || isEditable.value) const aselect = ref<typeof AntSelect>() const isOpen = ref(false) const isKanban = inject(IsKanbanInj, ref(false)) const isPublic = inject(IsPublicInj, ref(false)) const isEditColumn = inject(EditColumnInj, ref(false)) const isForm = inject(IsFormInj, ref(false)) const { $api } = useNuxtApp() const searchVal = ref() const { getMeta } = useMetas() const { isUIAllowed } = useRoles() const { isPg, isMysql } = useBase() // a variable to keep newly created option value // temporary until it's add the option to column meta const tempSelectedOptState = ref<string>() const isNewOptionCreateEnabled = computed(() => !isPublic.value && !disableOptionCreation && isUIAllowed('fieldEdit')) const options = computed<(SelectOptionType & { value: string })[]>(() => { if (column?.value.colOptions) { const opts = column.value.colOptions ? // todo: fix colOptions type, options does not exist as a property (column.value.colOptions as any).options.filter((el: SelectOptionType) => el.title !== '') || [] : [] for (const op of opts.filter((el: any) => el.order === null)) { op.title = op.title.replace(/^'/, '').replace(/'$/, '') } return opts.map((o: any) => ({ ...o, value: o.title })) } return [] }) const isOptionMissing = computed(() => { return (options.value ?? []).every((op) => op.title !== searchVal.value) }) const hasEditRoles = computed(() => isUIAllowed('dataEdit')) const editAllowed = computed(() => (hasEditRoles.value || isForm.value) && active.value) const vModel = computed({ get: () => tempSelectedOptState.value ?? modelValue?.trim(), set: (val) => { if (val && isNewOptionCreateEnabled.value && (options.value ?? []).every((op) => op.title !== val)) { tempSelectedOptState.value = val return addIfMissingAndSave() } emit('update:modelValue', val || null) }, }) watch(isOpen, (n, _o) => { if (editAllowed.value) { if (!n) { aselect.value?.$el?.querySelector('input')?.blur() } else { aselect.value?.$el?.querySelector('input')?.focus() } } }) useSelectedCellKeyupListener(activeCell, (e) => { switch (e.key) { case 'Escape': isOpen.value = false break case 'Enter': if (editAllowed.value && active.value && !isOpen.value) { isOpen.value = true } break // skip space bar key press since it's used for expand row case ' ': break default: if (!editAllowed.value) { e.preventDefault() break } // toggle only if char key pressed if (!(e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) && e.key?.length === 1 && !isDrawerOrModalExist()) { e.stopPropagation() isOpen.value = true } break } }) // close dropdown list on escape useSelectedCellKeyupListener(isOpen, (e) => { if (e.key === 'Escape') isOpen.value = false }) async function addIfMissingAndSave() { if (!tempSelectedOptState.value || isPublic.value) return false const newOptValue = tempSelectedOptState.value searchVal.value = '' tempSelectedOptState.value = undefined if (newOptValue && !options.value.some((o) => o.title === newOptValue)) { try { options.value.push({ title: newOptValue, value: newOptValue, color: enumColor.light[(options.value.length + 1) % enumColor.light.length], }) column.value.colOptions = { options: options.value.map(({ value: _, ...rest }) => rest) } const updatedColMeta = { ...column.value } // todo: refactor and avoid repetition if (updatedColMeta.cdf) { // Postgres returns default value wrapped with single quotes & casted with type so we have to get value between single quotes to keep it unified for all databases if (isPg(column.value.source_id)) { updatedColMeta.cdf = updatedColMeta.cdf.substring( updatedColMeta.cdf.indexOf(`'`) + 1, updatedColMeta.cdf.lastIndexOf(`'`), ) } // Mysql escapes single quotes with backslash so we keep quotes but others have to unescaped if (!isMysql(column.value.source_id) && !isPg(column.value.source_id)) { updatedColMeta.cdf = updatedColMeta.cdf.replace(/''/g, "'") } } await $api.dbTableColumn.update( (column.value as { fk_column_id?: string })?.fk_column_id || (column.value?.id as string), updatedColMeta, ) vModel.value = newOptValue await getMeta(column.value.fk_model_id!, true) } catch (e: any) { console.log(e) message.error(await extractSdkResponseErrorMsg(e)) } } } const search = () => { searchVal.value = aselect.value?.$el?.querySelector('.ant-select-selection-search-input')?.value } // prevent propagation of keydown event if select is open const onKeydown = (e: KeyboardEvent) => { if (isOpen.value && active.value) { e.stopPropagation() } if (e.key === 'Enter') { e.stopPropagation() } } const onSelect = () => { isOpen.value = false isEditable.value = false } const cellClickHook = inject(CellClickHookInj, null) const toggleMenu = (e: Event) => { // todo: refactor // check clicked element is clear icon if ( (e.target as HTMLElement)?.classList.contains('ant-select-clear') || (e.target as HTMLElement)?.closest('.ant-select-clear') ) { vModel.value = '' return e.stopPropagation() } if (cellClickHook) return isOpen.value = editAllowed.value && !isOpen.value } const cellClickHookHandler = () => { isOpen.value = editAllowed.value && !isOpen.value } onMounted(() => { cellClickHook?.on(cellClickHookHandler) }) onUnmounted(() => { cellClickHook?.on(cellClickHookHandler) }) const handleClose = (e: MouseEvent) => { if (isOpen.value && aselect.value && !aselect.value.$el.contains(e.target)) { isOpen.value = false } } useEventListener(document, 'click', handleClose, true) const selectedOpt = computed(() => { return options.value.find((o) => o.value === vModel.value) }) </script> <template> <div class="h-full w-full flex items-center nc-single-select" :class="{ 'read-only': readOnly || isLockedMode }" @click="toggleMenu" > <div v-if="!(active || isEditable)"> <a-tag v-if="selectedOpt" class="rounded-tag" :color="selectedOpt.color"> <span :style="{ 'color': tinycolor.isReadable(selectedOpt.color || '#ccc', '#fff', { level: 'AA', size: 'large' }) ? '#fff' : tinycolor.mostReadable(selectedOpt.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '13px', }" :class="{ 'text-sm': isKanban }" > {{ selectedOpt.title }} </span> </a-tag> </div> <a-select v-else ref="aselect" v-model:value="vModel" class="w-full overflow-hidden" :class="{ 'caret-transparent': !hasEditRoles }" :placeholder="isEditColumn ? $t('labels.optional') : ''" :allow-clear="!column.rqd && editAllowed" :bordered="false" :open="isOpen && editAllowed" :disabled="readOnly || !editAllowed || isLockedMode" :show-arrow="hasEditRoles && !(readOnly || isLockedMode) && active && vModel === null" :dropdown-class-name="`nc-dropdown-single-select-cell ${isOpen && active ? 'active' : ''}`" :show-search="isOpen && active" @select="onSelect" @keydown="onKeydown($event)" @search="search" > <a-select-option v-for="op of options" :key="op.title" :value="op.title" :data-testid="`select-option-${column.title}-${rowIndex}`" :class="`nc-select-option-${column.title}-${op.title}`" @click.stop > <a-tag class="rounded-tag" :color="op.color"> <span :style="{ 'color': tinycolor.isReadable(op.color || '#ccc', '#fff', { level: 'AA', size: 'large' }) ? '#fff' : tinycolor.mostReadable(op.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '13px', }" :class="{ 'text-sm': isKanban }" > {{ op.title }} </span> </a-tag> </a-select-option> <a-select-option v-if="searchVal && isOptionMissing && isNewOptionCreateEnabled" :key="searchVal" :value="searchVal"> <div class="flex gap-2 text-gray-500 items-center h-full"> <component :is="iconMap.plusThick" class="min-w-4" /> <div class="text-xs whitespace-normal"> {{ $t('msg.selectOption.createNewOptionNamed') }} <strong>{{ searchVal }}</strong> </div> </div> </a-select-option> </a-select> </div> </template> <style scoped lang="scss"> .rounded-tag { @apply py-0 px-[12px] rounded-[12px]; } :deep(.ant-tag) { @apply "rounded-tag" my-[2px]; } :deep(.ant-select-clear) { opacity: 1; } .nc-single-select:not(.read-only) { :deep(.ant-select-selector), :deep(.ant-select-selector input) { @apply !cursor-pointer; } } :deep(.ant-select-selector) { @apply !px-0; } :deep(.ant-select-selection-search-input) { @apply !text-xs; } :deep(.ant-select-clear > span) { @apply block; } </style>
packages/nc-gui/components/cell/SingleSelect.vue
1
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.998980700969696, 0.24598072469234467, 0.00016697042156010866, 0.00017716728325467557, 0.42435723543167114 ]
{ "id": 3, "code_window": [ "\n", "const { modelValue, disableOptionCreation } = defineProps<Props>()\n", "\n", "const emit = defineEmits(['update:modelValue'])\n", "\n", "const column = inject(ColumnInj)!\n", "\n", "const readOnly = inject(ReadonlyInj)!\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "const { isMobileMode } = useGlobal()\n", "\n" ], "file_path": "packages/nc-gui/components/cell/SingleSelect.vue", "type": "add", "edit_start_line_idx": 39 }
import { Test } from '@nestjs/testing'; import { GridColumnsService } from './grid-columns.service'; import type { TestingModule } from '@nestjs/testing'; describe('GridColumnsService', () => { let service: GridColumnsService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [GridColumnsService], }).compile(); service = module.get<GridColumnsService>(GridColumnsService); }); it('should be defined', () => { expect(service).toBeDefined(); }); });
packages/nocodb/src/services/grid-columns.service.spec.ts
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.0001767501817084849, 0.00017537522944621742, 0.00017400027718394995, 0.00017537522944621742, 0.0000013749522622674704 ]
{ "id": 3, "code_window": [ "\n", "const { modelValue, disableOptionCreation } = defineProps<Props>()\n", "\n", "const emit = defineEmits(['update:modelValue'])\n", "\n", "const column = inject(ColumnInj)!\n", "\n", "const readOnly = inject(ReadonlyInj)!\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "const { isMobileMode } = useGlobal()\n", "\n" ], "file_path": "packages/nc-gui/components/cell/SingleSelect.vue", "type": "add", "edit_start_line_idx": 39 }
{ "extends": [ "tslint:latest", "tslint-config-prettier", "tslint-immutable" ], "rules": { "interface-name": [ true, "never-prefix" ], // TODO: allow devDependencies only in **/*.spec.ts files: // waiting on https://github.com/palantir/tslint/pull/3708 "no-implicit-dependencies": [ true, "dev" ], /* tslint-immutable rules */ // Recommended built-in rules "no-var-keyword": true, "no-parameter-reassignment": true, // "typedef": [ // true, // "call-signature" // ], // Immutability rules // "readonly-keyword": true, // "readonly-array": true, // "no-let": true, // "no-object-mutation": true, // "no-delete": true, "no-method-signature": true, "no-console": false, // Functional style rules // "no-this": true, // "no-class": true, "no-mixed-interface": true, "no-bitwise": false, "variable-name": false // "no-expression-statement": [ // true, // { "ignore-prefix": ["console.", "process.exit"] } // ], // "no-if-statement": true /* end tslint-immutable rules */ } }
packages/nc-cli/tslint.json
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00017438428767491132, 0.000173743610503152, 0.000172877567820251, 0.00017394307360518724, 6.226097752914939e-7 ]
{ "id": 3, "code_window": [ "\n", "const { modelValue, disableOptionCreation } = defineProps<Props>()\n", "\n", "const emit = defineEmits(['update:modelValue'])\n", "\n", "const column = inject(ColumnInj)!\n", "\n", "const readOnly = inject(ReadonlyInj)!\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "const { isMobileMode } = useGlobal()\n", "\n" ], "file_path": "packages/nc-gui/components/cell/SingleSelect.vue", "type": "add", "edit_start_line_idx": 39 }
--- title: 'Upload via API' description: 'Upload files locally present or from public remote URL via API' hide_table_of_contents: true --- Sample code to upload files via API is listed below. Assumes `http://localhost:8080/` as the base URL for the API calls. # Upload local file ``` let axios = require("axios").default; let FormData = require('form-data'); let fs = require('fs'); // Configurations // const project_id = '<Project Identifier>'; const table_id = '<Table Identifier>'; const xc_token = '<Auth Token>'; const file_path = '<Local File Path>'; // Insert Image // @param image_path : local file path // @return : JSON object to be used in insert record API for attachment field // async function insertImage (path) { const formData = new FormData(); formData.append("file", fs.createReadStream(path)); const data = await axios({ url: 'http://localhost:8080/api/v1/db/storage/upload', data: formData, headers:{ 'Content-Type':`multipart/form-data;`, 'xc-auth': xc_token }, method: 'post', // Optional : storage file path params: {"path": "somePath"} }); return data; } // Insert record with attachment // Assumes a table with two columns : // 'Title' of type SingleLineText and // 'Attachment' of type Attachment // async function uploadFileExample() { let response = await insertImage(file_path); let row = { "Title": "2", "Attachment": response.data }; await axios({ method: 'POST', url: `http://localhost:8080/api/v1/db/data/noco/${project_id}/${table_id}`, data: row, headers: { 'xc-auth': xc_token } }); } (async () => { await uploadFileExample(); })(); ``` # Upload via URL ``` let axios = require("axios").default; let FormData = require('form-data'); let fs = require('fs'); // Configurations // const project_id = '<Project Identifier>'; const table_id = '<Table Identifier>'; const xc_token = '<Auth Token>'; // URL array : URLs of files to be uploaded const URLs = [{ url: '<URL1>' }, { url: '<URL2>' }]; // Insert Image // @param URLs : [] containing public URL for files to be uploaded // @return : JSON object to be used in insert record API for attachment field // async function insertImageByURL (URL_array) { const data = await axios({ url: 'http://localhost:8080/api/v1/db/storage/upload-by-url', data: URL_array, headers: { 'xc-auth': xc_token }, method: 'post', // Optional : storage file path params: {"path": "somePath"} }); return data; } // Insert record with attachment // Assumes a table with two columns : // 'Title' of type SingleLineText and // 'Attachment' of type Attachment // async function uploadByUrlExample() { let response = await insertImageByURL(URLs); // Update two columns : Title and Attachment let row = { "Title": "3", "Attachment": response.data }; await axios({ method: 'POST', url: `http://localhost:8080/api/v1/db/data/noco/${project_id}/${table_id}`, data: row, headers: { 'xc-auth': xc_auth } }); } (async () => { await uploadByUrlExample(); })(); ```
packages/noco-docs/versioned_docs/version-0.109.7/040.developer-resources/050.upload-via-api.md
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00017800343630369753, 0.00017288453818764538, 0.00016854857676662505, 0.00017276019207201898, 0.0000024763630790403113 ]
{ "id": 4, "code_window": [ " }\n", " }\n", "}\n", "\n", "const search = () => {\n", " searchVal.value = aselect.value?.$el?.querySelector('.ant-select-selection-search-input')?.value\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (isMobileMode.value) return\n", "\n" ], "file_path": "packages/nc-gui/components/cell/SingleSelect.vue", "type": "add", "edit_start_line_idx": 204 }
<script lang="ts" setup> import { onUnmounted } from '@vue/runtime-core' import { message } from 'ant-design-vue' import tinycolor from 'tinycolor2' import type { Select as AntSelect } from 'ant-design-vue' import type { SelectOptionType } from 'nocodb-sdk' import { ActiveCellInj, CellClickHookInj, ColumnInj, EditColumnInj, EditModeInj, IsFormInj, IsKanbanInj, ReadonlyInj, computed, enumColor, extractSdkResponseErrorMsg, iconMap, inject, isDrawerOrModalExist, ref, useBase, useEventListener, useRoles, useSelectedCellKeyupListener, watch, } from '#imports' interface Props { modelValue?: string | undefined rowIndex?: number disableOptionCreation?: boolean } const { modelValue, disableOptionCreation } = defineProps<Props>() const emit = defineEmits(['update:modelValue']) const column = inject(ColumnInj)! const readOnly = inject(ReadonlyInj)! const isLockedMode = inject(IsLockedInj, ref(false)) const isEditable = inject(EditModeInj, ref(false)) const activeCell = inject(ActiveCellInj, ref(false)) // use both ActiveCellInj or EditModeInj to determine the active state // since active will be false in case of form view const active = computed(() => activeCell.value || isEditable.value) const aselect = ref<typeof AntSelect>() const isOpen = ref(false) const isKanban = inject(IsKanbanInj, ref(false)) const isPublic = inject(IsPublicInj, ref(false)) const isEditColumn = inject(EditColumnInj, ref(false)) const isForm = inject(IsFormInj, ref(false)) const { $api } = useNuxtApp() const searchVal = ref() const { getMeta } = useMetas() const { isUIAllowed } = useRoles() const { isPg, isMysql } = useBase() // a variable to keep newly created option value // temporary until it's add the option to column meta const tempSelectedOptState = ref<string>() const isNewOptionCreateEnabled = computed(() => !isPublic.value && !disableOptionCreation && isUIAllowed('fieldEdit')) const options = computed<(SelectOptionType & { value: string })[]>(() => { if (column?.value.colOptions) { const opts = column.value.colOptions ? // todo: fix colOptions type, options does not exist as a property (column.value.colOptions as any).options.filter((el: SelectOptionType) => el.title !== '') || [] : [] for (const op of opts.filter((el: any) => el.order === null)) { op.title = op.title.replace(/^'/, '').replace(/'$/, '') } return opts.map((o: any) => ({ ...o, value: o.title })) } return [] }) const isOptionMissing = computed(() => { return (options.value ?? []).every((op) => op.title !== searchVal.value) }) const hasEditRoles = computed(() => isUIAllowed('dataEdit')) const editAllowed = computed(() => (hasEditRoles.value || isForm.value) && active.value) const vModel = computed({ get: () => tempSelectedOptState.value ?? modelValue?.trim(), set: (val) => { if (val && isNewOptionCreateEnabled.value && (options.value ?? []).every((op) => op.title !== val)) { tempSelectedOptState.value = val return addIfMissingAndSave() } emit('update:modelValue', val || null) }, }) watch(isOpen, (n, _o) => { if (editAllowed.value) { if (!n) { aselect.value?.$el?.querySelector('input')?.blur() } else { aselect.value?.$el?.querySelector('input')?.focus() } } }) useSelectedCellKeyupListener(activeCell, (e) => { switch (e.key) { case 'Escape': isOpen.value = false break case 'Enter': if (editAllowed.value && active.value && !isOpen.value) { isOpen.value = true } break // skip space bar key press since it's used for expand row case ' ': break default: if (!editAllowed.value) { e.preventDefault() break } // toggle only if char key pressed if (!(e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) && e.key?.length === 1 && !isDrawerOrModalExist()) { e.stopPropagation() isOpen.value = true } break } }) // close dropdown list on escape useSelectedCellKeyupListener(isOpen, (e) => { if (e.key === 'Escape') isOpen.value = false }) async function addIfMissingAndSave() { if (!tempSelectedOptState.value || isPublic.value) return false const newOptValue = tempSelectedOptState.value searchVal.value = '' tempSelectedOptState.value = undefined if (newOptValue && !options.value.some((o) => o.title === newOptValue)) { try { options.value.push({ title: newOptValue, value: newOptValue, color: enumColor.light[(options.value.length + 1) % enumColor.light.length], }) column.value.colOptions = { options: options.value.map(({ value: _, ...rest }) => rest) } const updatedColMeta = { ...column.value } // todo: refactor and avoid repetition if (updatedColMeta.cdf) { // Postgres returns default value wrapped with single quotes & casted with type so we have to get value between single quotes to keep it unified for all databases if (isPg(column.value.source_id)) { updatedColMeta.cdf = updatedColMeta.cdf.substring( updatedColMeta.cdf.indexOf(`'`) + 1, updatedColMeta.cdf.lastIndexOf(`'`), ) } // Mysql escapes single quotes with backslash so we keep quotes but others have to unescaped if (!isMysql(column.value.source_id) && !isPg(column.value.source_id)) { updatedColMeta.cdf = updatedColMeta.cdf.replace(/''/g, "'") } } await $api.dbTableColumn.update( (column.value as { fk_column_id?: string })?.fk_column_id || (column.value?.id as string), updatedColMeta, ) vModel.value = newOptValue await getMeta(column.value.fk_model_id!, true) } catch (e: any) { console.log(e) message.error(await extractSdkResponseErrorMsg(e)) } } } const search = () => { searchVal.value = aselect.value?.$el?.querySelector('.ant-select-selection-search-input')?.value } // prevent propagation of keydown event if select is open const onKeydown = (e: KeyboardEvent) => { if (isOpen.value && active.value) { e.stopPropagation() } if (e.key === 'Enter') { e.stopPropagation() } } const onSelect = () => { isOpen.value = false isEditable.value = false } const cellClickHook = inject(CellClickHookInj, null) const toggleMenu = (e: Event) => { // todo: refactor // check clicked element is clear icon if ( (e.target as HTMLElement)?.classList.contains('ant-select-clear') || (e.target as HTMLElement)?.closest('.ant-select-clear') ) { vModel.value = '' return e.stopPropagation() } if (cellClickHook) return isOpen.value = editAllowed.value && !isOpen.value } const cellClickHookHandler = () => { isOpen.value = editAllowed.value && !isOpen.value } onMounted(() => { cellClickHook?.on(cellClickHookHandler) }) onUnmounted(() => { cellClickHook?.on(cellClickHookHandler) }) const handleClose = (e: MouseEvent) => { if (isOpen.value && aselect.value && !aselect.value.$el.contains(e.target)) { isOpen.value = false } } useEventListener(document, 'click', handleClose, true) const selectedOpt = computed(() => { return options.value.find((o) => o.value === vModel.value) }) </script> <template> <div class="h-full w-full flex items-center nc-single-select" :class="{ 'read-only': readOnly || isLockedMode }" @click="toggleMenu" > <div v-if="!(active || isEditable)"> <a-tag v-if="selectedOpt" class="rounded-tag" :color="selectedOpt.color"> <span :style="{ 'color': tinycolor.isReadable(selectedOpt.color || '#ccc', '#fff', { level: 'AA', size: 'large' }) ? '#fff' : tinycolor.mostReadable(selectedOpt.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '13px', }" :class="{ 'text-sm': isKanban }" > {{ selectedOpt.title }} </span> </a-tag> </div> <a-select v-else ref="aselect" v-model:value="vModel" class="w-full overflow-hidden" :class="{ 'caret-transparent': !hasEditRoles }" :placeholder="isEditColumn ? $t('labels.optional') : ''" :allow-clear="!column.rqd && editAllowed" :bordered="false" :open="isOpen && editAllowed" :disabled="readOnly || !editAllowed || isLockedMode" :show-arrow="hasEditRoles && !(readOnly || isLockedMode) && active && vModel === null" :dropdown-class-name="`nc-dropdown-single-select-cell ${isOpen && active ? 'active' : ''}`" :show-search="isOpen && active" @select="onSelect" @keydown="onKeydown($event)" @search="search" > <a-select-option v-for="op of options" :key="op.title" :value="op.title" :data-testid="`select-option-${column.title}-${rowIndex}`" :class="`nc-select-option-${column.title}-${op.title}`" @click.stop > <a-tag class="rounded-tag" :color="op.color"> <span :style="{ 'color': tinycolor.isReadable(op.color || '#ccc', '#fff', { level: 'AA', size: 'large' }) ? '#fff' : tinycolor.mostReadable(op.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '13px', }" :class="{ 'text-sm': isKanban }" > {{ op.title }} </span> </a-tag> </a-select-option> <a-select-option v-if="searchVal && isOptionMissing && isNewOptionCreateEnabled" :key="searchVal" :value="searchVal"> <div class="flex gap-2 text-gray-500 items-center h-full"> <component :is="iconMap.plusThick" class="min-w-4" /> <div class="text-xs whitespace-normal"> {{ $t('msg.selectOption.createNewOptionNamed') }} <strong>{{ searchVal }}</strong> </div> </div> </a-select-option> </a-select> </div> </template> <style scoped lang="scss"> .rounded-tag { @apply py-0 px-[12px] rounded-[12px]; } :deep(.ant-tag) { @apply "rounded-tag" my-[2px]; } :deep(.ant-select-clear) { opacity: 1; } .nc-single-select:not(.read-only) { :deep(.ant-select-selector), :deep(.ant-select-selector input) { @apply !cursor-pointer; } } :deep(.ant-select-selector) { @apply !px-0; } :deep(.ant-select-selection-search-input) { @apply !text-xs; } :deep(.ant-select-clear > span) { @apply block; } </style>
packages/nc-gui/components/cell/SingleSelect.vue
1
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.9978739023208618, 0.05426081269979477, 0.0001649240148253739, 0.0001703322195680812, 0.22514867782592773 ]
{ "id": 4, "code_window": [ " }\n", " }\n", "}\n", "\n", "const search = () => {\n", " searchVal.value = aselect.value?.$el?.querySelector('.ant-select-selection-search-input')?.value\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (isMobileMode.value) return\n", "\n" ], "file_path": "packages/nc-gui/components/cell/SingleSelect.vue", "type": "add", "edit_start_line_idx": 204 }
<script lang="ts" setup> import JsBarcode from 'jsbarcode' import { IsGalleryInj, onMounted } from '#imports' const props = defineProps({ barcodeValue: { type: String, required: true }, barcodeFormat: { type: String, required: true }, customStyle: { type: Object, required: false }, }) const emit = defineEmits(['onClickBarcode']) const isGallery = inject(IsGalleryInj, ref(false)) const barcodeSvgRef = ref<HTMLElement>() const errorForCurrentInput = ref(false) const generate = () => { try { JsBarcode(barcodeSvgRef.value, String(props.barcodeValue), { format: props.barcodeFormat, }) if (props.customStyle) { if (barcodeSvgRef.value) { for (const key in props.customStyle) { barcodeSvgRef.value.style.setProperty(key, props.customStyle[key]) } } } errorForCurrentInput.value = false } catch (e) { console.log('e', e) errorForCurrentInput.value = true } } const onBarcodeClick = (ev: MouseEvent) => { if (isGallery.value) return ev.stopPropagation() emit('onClickBarcode') } watch([() => props.barcodeValue, () => props.barcodeFormat, () => props.customStyle], generate) onMounted(generate) </script> <template> <svg v-show="!errorForCurrentInput" ref="barcodeSvgRef" :class="{ 'w-full': !isGallery, 'w-auto': isGallery, }" data-testid="barcode" @click="onBarcodeClick" ></svg> <slot v-if="errorForCurrentInput" name="barcodeRenderError" /> </template>
packages/nc-gui/components/virtual-cell/barcode/JsBarcodeWrapper.vue
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.0002028397429967299, 0.00017533630307298154, 0.00016569953004363924, 0.0001691183279035613, 0.000012856270586780738 ]
{ "id": 4, "code_window": [ " }\n", " }\n", "}\n", "\n", "const search = () => {\n", " searchVal.value = aselect.value?.$el?.querySelector('.ant-select-selection-search-input')?.value\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (isMobileMode.value) return\n", "\n" ], "file_path": "packages/nc-gui/components/cell/SingleSelect.vue", "type": "add", "edit_start_line_idx": 204 }
import { test } from '@playwright/test'; import { BaseType, ProjectTypes } from 'nocodb-sdk'; import { DashboardPage } from '../../pages/Dashboard'; import setup, { NcContext } from '../../setup'; test.describe('Tiptap:Divider and Image', () => { let dashboard: DashboardPage; let context: NcContext; let base: BaseType; test.beforeEach(async ({ page }) => { context = await setup({ page, baseType: ProjectTypes.DOCUMENTATION }); base = context.base; dashboard = new DashboardPage(page, context.base); }); test('Tiptap:Divider', async ({ page }) => { const openedPage = await dashboard.docs.openedPage; await dashboard.sidebar.docsSidebar.createPage({ baseTitle: base.title as any, title: 'page', }); await openedPage.tiptap.fillContent({ content: 'page content', index: 0, }); await openedPage.tiptap.addNewNode({ type: 'Divider', }); await openedPage.tiptap.verifyNode({ index: 1, type: 'Divider', }); await page.waitForTimeout(550); // Verify that styling is correct when selected await openedPage.tiptap.clickNode({ index: 1, start: false, }); await openedPage.tiptap.verifyNodeSelected({ index: 1, }); // Pressing enter when selected should create a new line below it await page.keyboard.press('Enter'); await page.keyboard.type('P'); await openedPage.tiptap.verifyNode({ index: 2, type: 'Paragraph', content: 'P', }); // Pressing backspace on an empty line with a divider on top should select that divider await page.keyboard.press('Backspace'); await page.keyboard.press('Backspace'); await openedPage.tiptap.verifyNodeSelected({ index: 1, }); // Pressing backspace when selected should delete it await page.keyboard.press('Backspace'); await openedPage.tiptap.verifyNode({ index: 1, type: 'Paragraph', }); }); test('Tiptap:Image', async ({ page }) => { const client = await page.context().newCDPSession(page); await client.send('Network.emulateNetworkConditions', { offline: false, downloadThroughput: (1000 * 1024 * 1024) / 8, uploadThroughput: (30 * 1024 * 1024) / 8, latency: 70, }); const openedPage = await dashboard.docs.openedPage; await dashboard.sidebar.docsSidebar.createPage({ baseTitle: base.title as any, title: 'page', }); await openedPage.tiptap.addNewNode({ type: 'Image', filePath: `${process.cwd()}/fixtures/sampleFiles/sampleImage.jpeg`, }); await openedPage.tiptap.verifyNode({ index: 0, type: 'Image', isUploading: true, }); await openedPage.tiptap.verifyNode({ index: 0, type: 'Image', isUploading: false, }); await openedPage.tiptap.clickNode({ index: 0, start: false, }); await openedPage.tiptap.verifyNodeSelected({ index: 0, }); // Pressing enter when selected should create a new line below it await page.keyboard.press('Enter'); await page.keyboard.type('P'); await openedPage.tiptap.verifyNode({ index: 1, type: 'Paragraph', content: 'P', }); // Pressing backspace on an empty line with a image on top should select that image await page.keyboard.press('Backspace'); await page.keyboard.press('Backspace'); await openedPage.tiptap.verifyNodeSelected({ index: 0, }); // Pressing backspace when selected should delete it await page.keyboard.press('Backspace'); await openedPage.tiptap.verifyNode({ index: 0, type: 'Paragraph', }); await openedPage.tiptap.clickNode({ index: 0, start: false, }); await openedPage.dropFile({ domSelector: '.ProseMirror-focused .draggable-block-wrapper:first-child p:first-child', imageFilePath: `${process.cwd()}/fixtures/sampleFiles/sampleImage.jpeg`, }); await openedPage.tiptap.verifyNode({ index: 0, type: 'Image', isUploading: true, }); await openedPage.tiptap.verifyNode({ index: 0, type: 'Image', isUploading: false, }); }); });
tests/playwright/disabledTests/docs/tiptapDividerAndImage.spec.ts
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.0001798200682969764, 0.0001737454440444708, 0.0001682569709373638, 0.00017391568690072745, 0.0000031065542316355277 ]
{ "id": 4, "code_window": [ " }\n", " }\n", "}\n", "\n", "const search = () => {\n", " searchVal.value = aselect.value?.$el?.querySelector('.ant-select-selection-search-input')?.value\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (isMobileMode.value) return\n", "\n" ], "file_path": "packages/nc-gui/components/cell/SingleSelect.vue", "type": "add", "edit_start_line_idx": 204 }
<h1 align="center" style="border-bottom: none"> <b> <a href="https://www.nocodb.com">NocoDB </a><br> </b> ✨ L'alternativa Open Source ad Airtable ✨ <br> </h1> <p align="center"> Trasforma qualsiasi MySQL, PostgreSQL, SQL Server, SQLite & Mariadb in un foglio di calcolo intelligente. </p> <div align="center"> [![Build Status](https://travis-ci.org/dwyl/esta.svg?branch=master)](https://travis-ci.com/github/NocoDB/NocoDB) [![Node version](https://img.shields.io/badge/node-%3E%3D%2014.18.0-brightgreen)](http://nodejs.org/download/) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-green.svg)](https://conventionalcommits.org) </div> <p align="center"> <a href="http://www.nocodb.com"><b>Website</b></a> • <a href="https://discord.gg/5RgZmkW"><b>Discord</b></a> • <a href="https://twitter.com/nocodb"><b>Twitter</b></a> • <a href="https://www.reddit.com/r/NocoDB/"><b>Reddit</b></a> • <a href="https://docs.nocodb.com/"><b>Documentation</b></a> </p> ![OpenSourceAirtableAlternative](https://user-images.githubusercontent.com/5435402/133762127-e94da292-a1c3-4458-b09a-02cd5b57be53.png) <img src="https://static.scarf.sh/a.png?x-pxid=c12a77cc-855e-4602-8a0f-614b2d0da56a" /> <p align="center"> <a href="https://www.producthunt.com/posts/nocodb?utm_source=badge-featured&utm_medium=badge&utm_souce=badge-nocodb" target="_blank"><img src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=297536&theme=dark" alt="NocoDB - The Open Source Airtable alternative | Product Hunt" style="width: 250px; height: 54px;" width="250" height="54" /></a> </p> # Prova veloce ### Con Docker ```bash docker run -d --name nocodb -p 8080:8080 nocodb/nocodb:latest ``` - NocoDB needs a database as input : See [Production Setup](https://github.com/nocodb/nocodb/blob/master/README.md#production-setup). - Per rendere persistenti i dati puoi montare il volume su `/usr/app/data/`. Example: ``` docker run -d -p 8080:8080 --name nocodb -v "$(pwd)"/nocodb:/usr/app/data/ nocodb/nocodb:latest ``` ### Con NPM ``` npx create-nocodb-app ``` ### Con git ``` git clone https://github.com/nocodb/nocodb-seed cd nocodb-seed npm install npm start ``` ### GUI Accedi al Pannello di Controllo visitando: [http://localhost:8080/dashboard](http://localhost:8080/dashboard) # Unisciti alla nostra comunità <a href="https://discord.gg/5RgZmkW"> <img src="https://invidget.switchblade.xyz/5RgZmkW" alt="Unisciti a NocoDB: Una alternativa Gratuita e Open Source ad Airtable" > </a> <br> # Screenshots ![1](https://user-images.githubusercontent.com/86527202/136069047-e9090ea1-c95b-4ae5-9897-b48cab1ea3ab.png) <br> ![2](https://user-images.githubusercontent.com/86527202/136069059-fb225bc4-0dac-439c-9a31-e21d02097427.png) <br> ![5](https://user-images.githubusercontent.com/86527202/136069065-b2371359-7fff-420f-90d1-16e41b52b757.png) <br> ![6](https://user-images.githubusercontent.com/86527202/136069070-df63e1d6-ecdf-4423-989f-51cc9f52e52a.png) <br> ![7](https://user-images.githubusercontent.com/86527202/136069076-b32cdacf-5cb8-44ee-b8fe-4279ec1b4308.png) <br> ![8](https://user-images.githubusercontent.com/86527202/136069078-08b5c09d-b2bd-4cc0-8c92-1d08c46e5f83.png) <br> ![9](https://user-images.githubusercontent.com/86527202/136069081-15dad5b6-dd2c-472d-b4b7-9fdf5e00b0e8.png) <br> ![9a](https://user-images.githubusercontent.com/86527202/136069084-31134cb0-d9b3-441f-ae29-9ff11ee1c45b.png) <br> ![9b](https://user-images.githubusercontent.com/86527202/136069085-770cb6a4-6273-4edd-9382-01e46f59bc3b.png) <br> ![10](https://user-images.githubusercontent.com/86527202/136069088-dba928db-d92a-4ff2-bb05-614becd208a1.png) <br> ![11](https://user-images.githubusercontent.com/86527202/136069091-16764d3e-1995-4a45-99e8-652f28d2a946.png) <br> # Caratteristiche ### Interfaccia a foglio di calcolo - ⚡ Ricerca, ordina, filtra, nascondi le colonne con super facilità - ⚡ Crea Views: Griglie, Gallerie, Kanban, Form - ⚡ Condividi Views: Pubbliche o protette da password - ⚡ Views personali o bloccate - ⚡ Carica immagini nelle celle (funziona con S3, Minio, GCP, Azure, Digitalocean, Linode, OVH, BackBlaze) !! - ⚡ Ruoli: proprietario, creatore, editor, commentatore, visualizzatore, commentatore o ruoli personalizzati. - ⚡ Controllo accessi: controllo di accesso anche a livello di database, tabella e colonna. ### App store per automazioni del flusso di lavoro - ⚡ Chat: Microsoft Teams, Slack, Discord, Mattermost - ⚡ Email: SMTP, SES, MailChimp - ⚡ SMS: Twilio - ⚡ Whatsapp - ⚡ Qualsiasi API di terze parti ### Accesso API programmatico tramite - ⚡ REST APIs (Swagger) - ⚡ APIs GraphQL. - ⚡ Include autenticazione JWT e AUTH - ⚡ API Token da integrare con Zapier, Integromat. # Impostazione in produzione NOCODB richiede un database per memorizzare i metadati delle viste dei fogli di calcolo e dei database esterni. I parametri di connessione per questo database possono essere specificati nella variabile di ambiente NC_DB. ## Docker #### Esempio con MySQL ``` docker run -d -p 8080:8080 \ -e NC_DB="mysql2://host.docker.internal:3306?u=root&p=password&d=d1" \ -e NC_AUTH_JWT_SECRET="569a1821-0a93-45e8-87ab-eb857f20a010" \ nocodb/nocodb:latest ``` #### Esempio con Postgres ``` docker run -d -p 8080:8080 \ -e NC_DB="pg://host:port?u=user&p=password&d=database" \ -e NC_AUTH_JWT_SECRET="569a1821-0a93-45e8-87ab-eb857f20a010" \ nocodb/nocodb:latest ``` #### Esempio con SQL Server ``` docker run -d -p 8080:8080 \ -e NC_DB="mssql://host:port?u=user&p=password&d=database" \ -e NC_AUTH_JWT_SECRET="569a1821-0a93-45e8-87ab-eb857f20a010" \ nocodb/nocodb:latest ``` ## Docker Compose ``` git clone https://github.com/nocodb/nocodb cd nocodb cd docker-compose cd mysql or pg or mssql docker-compose up -d ``` ## Variabili d'ambiente Please refer to [Environment variables](https://docs.nocodb.com/getting-started/environment-variables) # Setup di sviluppo Please refer to [Development Setup](https://docs.nocodb.com/engineering/development-setup) # Contributi Please refer to [Contribution Guide](https://github.com/nocodb/nocodb/blob/master/.github/CONTRIBUTING.md). # Perché lo abbiamo creato? La maggior parte delle aziende utilizza fogli di calcolo o database per le proprie esigenze aziendali. I fogli di calcolo vengono utilizzati da oltre un miliardo di persone in modo collaborativo ogni singolo giorno. Tuttavia, i database che sono strumenti molto più potenti quando si tratta di elaborazione. I tentativi di risolvere questo problema con le offerte SaaS hanno significato orribili controlli di accesso, blocco del fornitore, blocco dei dati, brusche variazioni di prezzo e, soprattutto, un soffitto di vetro su ciò che è possibile in futuro. # La nostra missione La nostra missione è creare la più potente interfaccia per database "senza codice", disponibile a codice libero per ogni azienda nel mondo. Lo facciamo non solo per democratizzare l'accesso ad un potente strumento di elaborazione, ma anche per supportare i miliardi di persone che creano e costruiscono su Internet.
markdown/readme/languages/italian.md
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00017705667414702475, 0.00017015158664435148, 0.00016442280320916325, 0.0001698463165666908, 0.0000038946695894992445 ]
{ "id": 5, "code_window": [ " v-else\n", " ref=\"aselect\"\n", " v-model:value=\"vModel\"\n", " class=\"w-full overflow-hidden\"\n", " :class=\"{ 'caret-transparent': !hasEditRoles }\"\n", " :placeholder=\"isEditColumn ? $t('labels.optional') : ''\"\n", " :allow-clear=\"!column.rqd && editAllowed\"\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " class=\"w-full overflow-hidden xs:min-h-12\"\n" ], "file_path": "packages/nc-gui/components/cell/SingleSelect.vue", "type": "replace", "edit_start_line_idx": 287 }
<script lang="ts" setup> import { onUnmounted } from '@vue/runtime-core' import { message } from 'ant-design-vue' import tinycolor from 'tinycolor2' import type { Select as AntSelect } from 'ant-design-vue' import type { SelectOptionType, SelectOptionsType } from 'nocodb-sdk' import { ActiveCellInj, CellClickHookInj, ColumnInj, EditColumnInj, EditModeInj, IsKanbanInj, ReadonlyInj, RowHeightInj, computed, enumColor, extractSdkResponseErrorMsg, h, iconMap, inject, isDrawerOrModalExist, onMounted, reactive, ref, useBase, useEventListener, useMetas, useRoles, useSelectedCellKeyupListener, watch, } from '#imports' import MdiCloseCircle from '~icons/mdi/close-circle' interface Props { modelValue?: string | string[] rowIndex?: number disableOptionCreation?: boolean location?: 'cell' | 'filter' } const { modelValue, disableOptionCreation } = defineProps<Props>() const emit = defineEmits(['update:modelValue']) const column = inject(ColumnInj)! const readOnly = inject(ReadonlyInj)! const isLockedMode = inject(IsLockedInj, ref(false)) const isEditable = inject(EditModeInj, ref(false)) const activeCell = inject(ActiveCellInj, ref(false)) // use both ActiveCellInj or EditModeInj to determine the active state // since active will be false in case of form view const active = computed(() => activeCell.value || isEditable.value) const isPublic = inject(IsPublicInj, ref(false)) const isForm = inject(IsFormInj, ref(false)) const isEditColumn = inject(EditColumnInj, ref(false)) const rowHeight = inject(RowHeightInj, ref(undefined)) const selectedIds = ref<string[]>([]) const aselect = ref<typeof AntSelect>() const isOpen = ref(false) const isKanban = inject(IsKanbanInj, ref(false)) const searchVal = ref<string | null>() const { $api } = useNuxtApp() const { getMeta } = useMetas() const { isUIAllowed } = useRoles() const { isPg, isMysql } = useBase() // a variable to keep newly created options value // temporary until it's add the option to column meta const tempSelectedOptsState = reactive<string[]>([]) const options = computed<(SelectOptionType & { value?: string })[]>(() => { if (column?.value.colOptions) { const opts = column.value.colOptions ? (column.value.colOptions as SelectOptionsType).options.filter((el: SelectOptionType) => el.title !== '') || [] : [] for (const op of opts.filter((el: SelectOptionType) => el.order === null)) { op.title = op.title?.replace(/^'/, '').replace(/'$/, '') } return opts.map((o: SelectOptionType) => ({ ...o, value: o.title })) } return [] }) const isOptionMissing = computed(() => { return (options.value ?? []).every((op) => op.title !== searchVal.value) }) const hasEditRoles = computed(() => isUIAllowed('dataEdit')) const editAllowed = computed(() => (hasEditRoles.value || isForm.value) && active.value) const vModel = computed({ get: () => { const selected = selectedIds.value.reduce((acc, id) => { const title = (options.value.find((op) => op.id === id) || options.value.find((op) => op.title === id))?.title if (title) acc.push(title) return acc }, [] as string[]) if (tempSelectedOptsState.length) selected.push(...tempSelectedOptsState) return selected }, set: (val) => { if (isOptionMissing.value && val.length && val[val.length - 1] === searchVal.value) { return addIfMissingAndSave() } emit('update:modelValue', val.length === 0 ? null : val.join(',')) }, }) const selectedTitles = computed(() => modelValue ? typeof modelValue === 'string' ? isMysql(column.value.source_id) ? modelValue.split(',').sort((a, b) => { const opa = options.value.find((el) => el.title === a) const opb = options.value.find((el) => el.title === b) if (opa && opb) { return opa.order! - opb.order! } return 0 }) : modelValue.split(',').map((el) => el.trim()) : modelValue.map((el) => el.trim()) : [], ) onMounted(() => { selectedIds.value = selectedTitles.value.flatMap((el) => { const item = options.value.find((op) => op.title === el) const itemIdOrTitle = item?.id || item?.title if (itemIdOrTitle) { return [itemIdOrTitle] } return [] }) }) watch( () => modelValue, () => { selectedIds.value = selectedTitles.value.flatMap((el) => { const item = options.value.find((op) => op.title === el) if (item && (item.id || item.title)) { return [(item.id || item.title)!] } return [] }) }, ) watch(isOpen, (n, _o) => { if (!n) searchVal.value = '' if (editAllowed.value) { if (!n) { aselect.value?.$el?.querySelector('input')?.blur() } else { aselect.value?.$el?.querySelector('input')?.focus() } } }) useSelectedCellKeyupListener(activeCell, (e) => { switch (e.key) { case 'Escape': isOpen.value = false break case 'Enter': if (editAllowed.value && active.value && !isOpen.value) { isOpen.value = true } break // skip space bar key press since it's used for expand row case ' ': break case 'ArrowUp': case 'ArrowDown': case 'ArrowRight': case 'ArrowLeft': case 'Delete': // skip break default: if (!editAllowed.value) { e.preventDefault() break } // toggle only if char key pressed if (!(e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) && e.key?.length === 1 && !isDrawerOrModalExist()) { e.stopPropagation() isOpen.value = true } break } }) // close dropdown list on escape useSelectedCellKeyupListener(isOpen, (e) => { if (e.key === 'Escape') isOpen.value = false }) const activeOptCreateInProgress = ref(0) async function addIfMissingAndSave() { if (!searchVal.value || isPublic.value) return false try { tempSelectedOptsState.push(searchVal.value) const newOptValue = searchVal?.value searchVal.value = '' activeOptCreateInProgress.value++ if (newOptValue && !options.value.some((o) => o.title === newOptValue)) { const newOptions = [...options.value] newOptions.push({ title: newOptValue, value: newOptValue, color: enumColor.light[(options.value.length + 1) % enumColor.light.length], }) column.value.colOptions = { options: newOptions.map(({ value: _, ...rest }) => rest) } const updatedColMeta = { ...column.value } // todo: refactor and avoid repetition if (updatedColMeta.cdf) { // Postgres returns default value wrapped with single quotes & casted with type so we have to get value between single quotes to keep it unified for all databases if (isPg(column.value.source_id)) { updatedColMeta.cdf = updatedColMeta.cdf.substring( updatedColMeta.cdf.indexOf(`'`) + 1, updatedColMeta.cdf.lastIndexOf(`'`), ) } // Mysql escapes single quotes with backslash so we keep quotes but others have to unescaped if (!isMysql(column.value.source_id) && !isPg(column.value.source_id)) { updatedColMeta.cdf = updatedColMeta.cdf.replace(/''/g, "'") } } await $api.dbTableColumn.update( (column.value as { fk_column_id?: string })?.fk_column_id || (column.value?.id as string), updatedColMeta, ) activeOptCreateInProgress.value-- if (!activeOptCreateInProgress.value) { await getMeta(column.value.fk_model_id!, true) vModel.value = [...vModel.value] tempSelectedOptsState.splice(0, tempSelectedOptsState.length) } } else { activeOptCreateInProgress.value-- } } catch (e: any) { console.log(e) activeOptCreateInProgress.value-- message.error(await extractSdkResponseErrorMsg(e)) } } const search = () => { searchVal.value = aselect.value?.$el?.querySelector('.ant-select-selection-search-input')?.value } const onTagClick = (e: Event, onClose: Function) => { // check clicked element is remove icon if ( (e.target as HTMLElement)?.classList.contains('ant-tag-close-icon') || (e.target as HTMLElement)?.closest('.ant-tag-close-icon') ) { e.stopPropagation() onClose() } } const cellClickHook = inject(CellClickHookInj, null) const toggleMenu = () => { if (cellClickHook) return isOpen.value = editAllowed.value && !isOpen.value } const cellClickHookHandler = () => { isOpen.value = editAllowed.value && !isOpen.value } onMounted(() => { cellClickHook?.on(cellClickHookHandler) }) onUnmounted(() => { cellClickHook?.on(cellClickHookHandler) }) const handleClose = (e: MouseEvent) => { // close dropdown if clicked outside of dropdown if ( isOpen.value && aselect.value && !aselect.value.$el.contains(e.target) && !document.querySelector('.nc-dropdown-multi-select-cell.active')?.contains(e.target as Node) ) { // loose focus when clicked outside isEditable.value = false isOpen.value = false } } useEventListener(document, 'click', handleClose, true) const selectedOpts = computed(() => { return vModel.value.reduce<SelectOptionType[]>((selectedOptions, option) => { const selectedOption = options.value.find((o) => o.value === option) if (selectedOption) { selectedOptions.push(selectedOption) } return selectedOptions }, []) }) </script> <template> <div class="nc-multi-select h-full w-full flex items-center" :class="{ 'read-only': readOnly || isLockedMode }" @click="toggleMenu" > <div v-if="!active" class="flex flex-wrap" :style="{ 'display': '-webkit-box', 'max-width': '100%', '-webkit-line-clamp': rowHeight || 1, '-webkit-box-orient': 'vertical', 'overflow': 'hidden', }" > <template v-for="selectedOpt of selectedOpts" :key="selectedOpt.value"> <a-tag class="rounded-tag" :color="selectedOpt.color"> <span :style="{ 'color': tinycolor.isReadable(selectedOpt.color || '#ccc', '#fff', { level: 'AA', size: 'large' }) ? '#fff' : tinycolor.mostReadable(selectedOpt.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '13px', }" :class="{ 'text-sm': isKanban }" > {{ selectedOpt.title }} </span> </a-tag> </template> </div> <a-select v-else ref="aselect" v-model:value="vModel" mode="multiple" class="w-full overflow-hidden" :placeholder="isEditColumn ? $t('labels.optional') : ''" :bordered="false" clear-icon show-search :show-arrow="editAllowed && !(readOnly || isLockedMode)" :open="isOpen && editAllowed" :disabled="readOnly || !editAllowed || isLockedMode" :class="{ 'caret-transparent': !hasEditRoles }" :dropdown-class-name="`nc-dropdown-multi-select-cell ${isOpen ? 'active' : ''}`" @search="search" @keydown.stop > <a-select-option v-for="op of options" :key="op.id || op.title" :value="op.title" :data-testid="`select-option-${column.title}-${location === 'filter' ? 'filter' : rowIndex}`" :class="`nc-select-option-${column.title}-${op.title}`" @click.stop > <a-tag class="rounded-tag" :color="op.color"> <span :style="{ 'color': tinycolor.isReadable(op.color || '#ccc', '#fff', { level: 'AA', size: 'large' }) ? '#fff' : tinycolor.mostReadable(op.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '13px', }" :class="{ 'text-sm': isKanban }" > {{ op.title }} </span> </a-tag> </a-select-option> <a-select-option v-if="searchVal && isOptionMissing && !isPublic && !disableOptionCreation && isUIAllowed('fieldEdit')" :key="searchVal" :value="searchVal" > <div class="flex gap-2 text-gray-500 items-center h-full"> <component :is="iconMap.plusThick" class="min-w-4" /> <div class="text-xs whitespace-normal"> {{ $t('msg.selectOption.createNewOptionNamed') }} <strong>{{ searchVal }}</strong> </div> </div> </a-select-option> <template #tagRender="{ value: val, onClose }"> <a-tag v-if="options.find((el) => el.title === val)" class="rounded-tag nc-selected-option" :style="{ display: 'flex', alignItems: 'center' }" :color="options.find((el) => el.title === val)?.color" :closable="editAllowed && (vModel.length > 1 || !column?.rqd)" :close-icon="h(MdiCloseCircle, { class: ['ms-close-icon'] })" @click="onTagClick($event, onClose)" @close="onClose" > <span :style="{ 'color': tinycolor.isReadable(options.find((el) => el.title === val)?.color || '#ccc', '#fff', { level: 'AA', size: 'large', }) ? '#fff' : tinycolor .mostReadable(options.find((el) => el.title === val)?.color || '#ccc', ['#0b1d05', '#fff']) .toHex8String(), 'font-size': '13px', }" :class="{ 'text-sm': isKanban }" > {{ val }} </span> </a-tag> </template> </a-select> </div> </template> <style scoped lang="scss"> .ms-close-icon { color: rgba(0, 0, 0, 0.25); cursor: pointer; display: flex; font-size: 12px; font-style: normal; height: 12px; line-height: 1; text-align: center; text-transform: none; transition: color 0.3s ease, opacity 0.15s ease; width: 12px; z-index: 1; margin-right: -6px; margin-left: 3px; } .ms-close-icon:before { display: block; } .ms-close-icon:hover { color: rgba(0, 0, 0, 0.45); } .read-only { .ms-close-icon { display: none; } } .rounded-tag { @apply py-0 px-[12px] rounded-[12px]; } :deep(.ant-tag) { @apply "rounded-tag" my-[2px]; } :deep(.ant-tag-close-icon) { @apply "text-slate-500"; } :deep(.ant-select-selection-overflow-item) { @apply "flex overflow-hidden"; } :deep(.ant-select-selection-overflow) { @apply flex-nowrap overflow-hidden; } .nc-multi-select:not(.read-only) { :deep(.ant-select-selector), :deep(.ant-select-selector input) { @apply "!cursor-pointer"; } } :deep(.ant-select-selector) { @apply !px-0; } :deep(.ant-select-selection-search-input) { @apply !text-xs; } </style>
packages/nc-gui/components/cell/MultiSelect.vue
1
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.02499976009130478, 0.0018922357121482491, 0.0001635459193494171, 0.0001735712867230177, 0.005034022498875856 ]
{ "id": 5, "code_window": [ " v-else\n", " ref=\"aselect\"\n", " v-model:value=\"vModel\"\n", " class=\"w-full overflow-hidden\"\n", " :class=\"{ 'caret-transparent': !hasEditRoles }\"\n", " :placeholder=\"isEditColumn ? $t('labels.optional') : ''\"\n", " :allow-clear=\"!column.rqd && editAllowed\"\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " class=\"w-full overflow-hidden xs:min-h-12\"\n" ], "file_path": "packages/nc-gui/components/cell/SingleSelect.vue", "type": "replace", "edit_start_line_idx": 287 }
{ "label": "Field types", "collapsible": true, "collapsed": true }
packages/noco-docs/docs/070.fields/040.field-types/_category_.json
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00017371615103911608, 0.00017371615103911608, 0.00017371615103911608, 0.00017371615103911608, 0 ]
{ "id": 5, "code_window": [ " v-else\n", " ref=\"aselect\"\n", " v-model:value=\"vModel\"\n", " class=\"w-full overflow-hidden\"\n", " :class=\"{ 'caret-transparent': !hasEditRoles }\"\n", " :placeholder=\"isEditColumn ? $t('labels.optional') : ''\"\n", " :allow-clear=\"!column.rqd && editAllowed\"\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " class=\"w-full overflow-hidden xs:min-h-12\"\n" ], "file_path": "packages/nc-gui/components/cell/SingleSelect.vue", "type": "replace", "edit_start_line_idx": 287 }
#!/bin/bash # script to build local docker image. # highlevel steps involved # 1. Stop and remove existing container and image # 2. Install dependencies # 3. Build nc-gui # 3a. static build of nc-gui # 3b. copy nc-gui build to nocodb dir # 4. Build nocodb SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) LOG_FILE=${SCRIPT_DIR}/build-local-docker-image.log ERROR="" function stop_and_remove_container() { # Stop and remove the existing container docker stop nocodb-local >/dev/null 2>&1 docker rm nocodb-local >/dev/null 2>&1 } function remove_image() { # Remove the existing image docker rmi nocodb-local >/dev/null 2>&1 } function install_dependencies() { # Install all dependencies cd ${SCRIPT_DIR} pnpm i || ERROR="install_dependencies failed" } function build_gui() { # build nc-gui export NODE_OPTIONS="--max_old_space_size=16384" # generate static build of nc-gui cd ${SCRIPT_DIR}/packages/nc-gui pnpm run generate || ERROR="gui build failed" } function copy_gui_artifacts() { # copy nc-gui build to nocodb dir rsync -rvzh --delete ./dist/ ${SCRIPT_DIR}/packages/nocodb/docker/nc-gui/ || ERROR="copy_gui_artifacts failed" } function package_nocodb() { # build nocodb ( pack nocodb-sdk and nc-gui ) cd ${SCRIPT_DIR}/packages/nocodb EE=true ${SCRIPT_DIR}/node_modules/.bin/webpack --config ${SCRIPT_DIR}/packages/nocodb/webpack.local.config.js || ERROR="package_nocodb failed" } function build_image() { # build docker docker build . -f Dockerfile.local -t nocodb-local || ERROR="build_image failed" } function log_message() { if [[ ${ERROR} != "" ]]; then >&2 echo "build failed, Please check build-local-docker-image.log for more details" >&2 echo "ERROR: ${ERROR}" exit 1 else echo 'docker image with tag "nocodb-local" built sussessfully. Use below sample command to run the container' echo 'docker run -d -p 3333:8080 --name nocodb-local nocodb-local ' fi } echo "Info: Stopping and removing existing container and image" | tee ${LOG_FILE} stop_and_remove_container remove_image echo "Info: Installing dependencies" | tee -a ${LOG_FILE} install_dependencies 1>> ${LOG_FILE} 2>> ${LOG_FILE} echo "Info: Building nc-gui" | tee -a ${LOG_FILE} build_gui 1>> ${LOG_FILE} 2>> ${LOG_FILE} echo "Info: Copy nc-gui build to nocodb dir" | tee -a ${LOG_FILE} copy_gui_artifacts 1>> ${LOG_FILE} 2>> ${LOG_FILE} echo "Info: Build nocodb, package nocodb-sdk and nc-gui" | tee -a ${LOG_FILE} package_nocodb 1>> ${LOG_FILE} 2>> ${LOG_FILE} if [[ ${ERROR} == "" ]]; then echo "Info: Building docker image" | tee -a ${LOG_FILE} build_image 1>> ${LOG_FILE} 2>> ${LOG_FILE} fi log_message | tee -a ${LOG_FILE}
build-local-docker-image.sh
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00017436184862162918, 0.00016966050316113979, 0.00016419282474089414, 0.00016988826973829418, 0.0000034068330023728777 ]
{ "id": 5, "code_window": [ " v-else\n", " ref=\"aselect\"\n", " v-model:value=\"vModel\"\n", " class=\"w-full overflow-hidden\"\n", " :class=\"{ 'caret-transparent': !hasEditRoles }\"\n", " :placeholder=\"isEditColumn ? $t('labels.optional') : ''\"\n", " :allow-clear=\"!column.rqd && editAllowed\"\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " class=\"w-full overflow-hidden xs:min-h-12\"\n" ], "file_path": "packages/nc-gui/components/cell/SingleSelect.vue", "type": "replace", "edit_start_line_idx": 287 }
{ "general": { "home": "Rumah", "load": "Memuat", "open": "Membuka", "close": "Menutup", "yes": "Ya", "no": "Tidak", "ok": "Oke", "and": "Dan", "or": "Atau", "add": "Menambahkan", "edit": "Sunting", "remove": "Menghapus", "save": "Menyimpan", "cancel": "Membatalkan", "submit": "Kirim", "create": "Membuat", "duplicate": "Duplikat", "insert": "Memasukkan", "delete": "Menghapus", "update": "Memperbarui", "rename": "Ganti nama", "reload": "Reload.", "reset": "Mengatur ulang", "install": "Memasang", "show": "Menunjukkan", "hide": "Bersembunyi", "showAll": "Tunjukkan semua", "hideAll": "Sembunyikan semua", "showMore": "Menampilkan lebih banyak", "showOptions": "Tampilkan opsi", "hideOptions": "Sembunyikan opsi", "showMenu": "Tampilkan menu", "hideMenu": "Sembunyikan menu", "addAll": "Tambahkan semua", "removeAll": "Menghapus semua", "signUp": "Mendaftar", "signIn": "MASUK", "signOut": "Keluar", "required": "Yg dibutuhkan", "enableScanner": "Enable Scanner for filling", "preferred": "Lebih disukai", "mandatory": "Wajib", "loading": "Memuat ...", "title": "Judul", "upload": "Mengunggah", "download": "Unduh.", "default": "Bawaan", "more": "Lagi", "less": "Lebih sedikit", "event": "Peristiwa", "condition": "Kondisi", "after": "Setelah", "before": "Sebelum", "search": "Mencari", "notification": "Pemberitahuan", "reference": "Referensi", "function": "Fungsi", "confirm": "Konfirmasi", "generate": "Menghasilkan", "copy": "Salin", "misc": "Lain-lain", "lock": "Kunci", "unlock": "Membuka kunci", "credentials": "Kredensial", "help": "Bantuan", "questions": "Pertanyaan", "reachOut": "Jangkau di sini", "betaNote": "Fitur ini saat ini dalam versi beta.", "moreInfo": "Informasi lebih lanjut dapat ditemukan di sini", "logs": "Log", "groupingField": "Bidang Pengelompokan", "insertAfter": "Sisipkan Setelah", "insertBefore": "Sisipkan Sebelum", "hideField": "Sembunyikan Bidang", "sortAsc": "Urutkan Menaik", "sortDesc": "Urutkan Menurun", "geoDataField": "GeoData Field" }, "objects": { "project": "Proyek", "projects": "Proyek", "table": "Meja", "tables": "Tabel.", "field": "Bidang", "fields": "Bidang", "column": "Kolom", "columns": "Kolom.", "page": "Halaman", "pages": "Halaman", "record": "Catatan", "records": "Catatan", "webhook": "WebHook.", "webhooks": "WebHooks.", "view": "Melihat", "views": "Tampilan", "viewType": { "grid": "Kisi", "gallery": "Galeri", "form": "Membentuk", "kanban": "Kanban.", "calendar": "Kalender", "map": "Map" }, "user": "Pengguna", "users": "Pengguna.", "role": "Peran", "roles": "Peran.", "roleType": { "owner": "Pemilik", "creator": "Pencipta", "editor": "Editor", "commenter": "Komentator", "viewer": "Penonton", "orgLevelCreator": "Pembuat Tingkat Organisasi", "orgLevelViewer": "Penampil Tingkat Organisasi" }, "sqlVIew": "Tampilan SQL" }, "datatype": { "ID": "Indo", "ForeignKey": "Kunci asing", "SingleLineText": "Teks baris tunggal", "LongText": "Teks Panjang", "Attachment": "Lampiran", "Checkbox": "Centang", "MultiSelect": "Multi Select.", "SingleSelect": "Pilih tunggal", "Collaborator": "Kolaborator", "Date": "Tanggal", "Year": "Tahun", "Time": "Waktu", "PhoneNumber": "Nomor telepon", "Email": "Surel", "URL": "URL", "Number": "Nomor", "Decimal": "Desimal", "Currency": "Mata uang", "Percent": "Persen", "Duration": "Durasi", "GeoData": "GeoData", "Rating": "Peringkat", "Formula": "Rumus", "Rollup": "Rollup.", "Count": "Menghitung", "Lookup": "Mencari", "DateTime": "Tanggal Waktu", "CreateTime": "Buat waktu", "LastModifiedTime": "Waktu yang dimodifikasi terakhir", "AutoNumber": "Nomor otomatis", "Barcode": "Barcode.", "Button": "Tombol", "Password": "Kata sandi", "relationProperties": { "noAction": "Tidak ada tindakan", "cascade": "Riam", "restrict": "Membatasi", "setNull": "Atur null.", "setDefault": "Set standar" } }, "filterOperation": { "isEqual": "sama.", "isNotEqual": "tidak sama", "isLike": "seperti", "isNot like": "tidak seperti", "isEmpty": "kosong", "isNotEmpty": "tidak kosong", "isNull": "adalah null.", "isNotNull": "bukan null." }, "title": { "erdView": "Tampilan ERD", "newProj": "Proyek baru", "myProject": "Proyek saya", "formTitle": "Bentuk judul", "collabView": "Tampilan kolaboratif", "lockedView": "Tampilan yang terkunci", "personalView": "Tampilan pribadi", "appStore": "Toko aplikasi", "teamAndAuth": "Tim & AUTH.", "rolesUserMgmt": "Manajemen Peran & Pengguna", "userMgmt": "Manajemen Pengguna", "apiTokenMgmt": "API Token Management.", "rolesMgmt": "Manajemen peran.", "projMeta": "Metadata proyek", "metaMgmt": "Meta Management.", "metadata": "Metadata.", "exportImportMeta": "Ekspor / Impor Metadata", "uiACL": "UI Access Control.", "metaOperations": "Operasi metadata", "audit": "Audit", "auditLogs": "Log audit", "sqlMigrations": "Migrasi SQL.", "dbCredentials": "Kredensial basis data", "advancedParameters": "SSL & Parameter Lanjutan", "headCreateProject": "Buat Proyek | Nocodb.", "headLogin": "Masuk | Nocodb.", "resetPassword": "Mereset password Anda", "teamAndSettings": "Tim & Pengaturan", "apiDocs": "Dokumen API", "importFromAirtable": "Impor Dari Airtable", "generateToken": "Hasilkan Token", "APIsAndSupport": "API & Dukungan", "helpCenter": "Pusat bantuan", "swaggerDocumentation": "Dokumentasi Kesombongan", "quickImportFrom": "Impor Cepat Dari", "quickImport": "Impor Cepat", "advancedSettings": "Pengaturan Lanjutan", "codeSnippet": "Cuplikan Kode", "keyboardShortcut": "Pintasan Papan Ketik", "generateRandomName": "Generate Random Name", "findRowByScanningCode": "Find row by scanning a QR or Barcode" }, "labels": { "createdBy": "Dibuat oleh", "notifyVia": "Beri tahu VIA.", "projName": "Nama Proyek", "tableName": "Nama meja", "viewName": "Lihat nama", "viewLink": "Lihat Tautan", "columnName": "Nama kolom", "columnToScanFor": "Column to scan", "columnType": "Jenis kolom.", "roleName": "Nama peran", "roleDescription": "Deskripsi peran", "databaseType": "Ketik Database", "lengthValue": "Panjang / Nilai", "dbType": "DATABASE TYPE.", "sqliteFile": "File SQLite.", "hostAddress": "Alamat Tuan Rumah", "port": "Nomor port.", "username": "Nama pengguna", "password": "Kata sandi", "schemaName": "Nama skema", "database": "Basis data", "action": "Tindakan", "actions": "Tindakan", "operation": "Operasi", "operationSub": "Sub Operation", "operationType": "Jenis operasi", "operationSubType": "SUB-tipe operasi", "description": "Keterangan", "authentication": "Autentikasi", "token": "Token", "where": "Di mana", "cache": "Cache", "chat": "Mengobrol", "email": "Surel", "storage": "Penyimpanan", "uiAcl": "UI-ACL", "models": "Model", "syncState": "Sinkronisasi Negara", "created": "Dibuat.", "sqlOutput": "Keluaran SQL", "addOption": "Tambahkan opsi", "qrCodeValueColumn": "Kolom dengan nilai kode QR", "barcodeValueColumn": "Kolom dengan nilai Barcode", "barcodeFormat": "Format kode batang", "qrCodeValueTooLong": "Terlalu banyak karakter untuk kode QR", "barcodeValueTooLong": "Terlalu banyak karakter untuk barcode", "currentLocation": "Current Location", "lng": "Lng", "lat": "Lat", "aggregateFunction": "Fungsi agregat.", "dbCreateIfNotExists": "Basis Data: Buat jika tidak ada", "clientKey": "Kunci klien", "clientCert": "Sertifikat klien", "serverCA": "Server CA.", "requriedCa": "Wajib-ca.", "requriedIdentity": "Wajib-identitas.", "inflection": { "tableName": "Infleksi - Nama Tabel", "columnName": "Infleksi - Nama Kolom" }, "community": { "starUs1": "Bintang", "starUs2": "kami di GitHub", "bookDemo": "Pesan demo gratis", "getAnswered": "Dapatkan pertanyaan Anda dijawab", "joinDiscord": "Bergabunglah dengan Perselisihan", "joinCommunity": "Bergabunglah dengan Komunitas NocoDB", "joinReddit": "Bergabunglah /r/NocoDB", "followNocodb": "Ikuti NocoDB" }, "docReference": "Referensi Dokumen", "selectUserRole": "Pilih Peran Pengguna", "childTable": "Tabel Anak", "childColumn": "Kolom anak.", "linkToAnotherRecord": "Tautan ke catatan lain", "onUpdate": "Pada pembaruan", "onDelete": "Hapus", "account": "Akun", "language": "Bahasa", "primaryColor": "Warna Primer", "accentColor": "Warna Aksen", "customTheme": "Tema Khusus", "requestDataSource": "Meminta sumber data yang Anda butuhkan?", "apiKey": "Kunci API", "sharedBase": "Basis Bersama", "importData": "Impor Data", "importSecondaryViews": "Impor Tampilan Sekunder", "importRollupColumns": "Impor Kolom Rollup", "importLookupColumns": "Impor Kolom Pencarian", "importAttachmentColumns": "Impor Kolom Lampiran", "importFormulaColumns": "Kolom Formula Impor", "noData": "Tidak ada data", "goToDashboard": "Buka Dasbor", "importing": "Mengimpor", "flattenNested": "Ratakan Bersarang", "downloadAllowed": "Unduh diizinkan", "weAreHiring": "Kami merekrut!", "primaryKey": "Kunci utama", "hasMany": "memiliki banyak", "belongsTo": "milik", "manyToMany": "memiliki hubungan banyak ke banyak", "extraConnectionParameters": "Parameter koneksi tambahan", "commentsOnly": "Hanya komentar", "documentation": "Dokumentasi", "subscribeNewsletter": "Berlangganan buletin mingguan kami", "signUpWithProvider": "Daftar dengan {provider}", "signInWithProvider": "Masuk dengan {provider}", "agreeToTos": "Dengan mendaftar, Anda menyetujui Ketentuan Layanan", "welcomeToNc": "Selamat datang di NocoDB!", "inviteOnlySignup": "Izinkan pendaftaran hanya menggunakan url undangan", "nextRow": "Baris Berikutnya", "prevRow": "Baris sebelumnya" }, "activity": { "createProject": "Buat Proyek", "importProject": "Proyek Impor", "searchProject": "Cari proyek", "editProject": "Edit proyek", "stopProject": "Stop Project.", "startProject": "Mulai Proyek", "restartProject": "Restart Project.", "deleteProject": "Hapus proyek", "refreshProject": "Refresh Projects.", "saveProject": "Simpan proyek", "deleteKanbanStack": "Hapus tumpukan?", "createProjectExtended": { "extDB": "Buat dengan menghubungkan <br> ke basis data eksternal", "excel": "Buat proyek dari Excel", "template": "Buat proyek dari template" }, "OkSaveProject": "OK & SIMPAN PROYEK", "upgrade": { "available": "Upgrade tersedia", "releaseNote": "Rilis Catatan", "howTo": "Bagaimana cara meningkatkan?" }, "translate": "Bantu Terjemahkan.", "account": { "authToken": "Salin token auth.", "swagger": "Kesombongan: API REST", "projInfo": "Salin info proyek", "themes": "Tema" }, "sort": "Menyortir", "addSort": "Tambahkan opsi Urutkan", "filter": "Saring", "addFilter": "Tambahkan Filter", "share": "Membagikan", "shareBase": { "disable": "Nonaktifkan basis bersama", "enable": "Siapa pun dengan tautannya", "link": "Tautan dasar bersama" }, "invite": "Undang", "inviteMore": "Undang lebih banyak", "inviteTeam": "Undang Tim", "inviteUser": "Undang Pengguna", "inviteToken": "Undang token.", "newUser": "Pengguna baru", "editUser": "Edit Pengguna", "deleteUser": "Hapus pengguna dari proyek", "resendInvite": "Kirim ulang undangan e-mail", "copyInviteURL": "Salin Undangan URL.", "copyPasswordResetURL": "Salin URL pengaturan ulang kata sandi", "newRole": "Peran Baru", "reloadRoles": "Muat ulang peran", "nextPage": "Halaman selanjutnya", "prevPage": "Halaman sebelumnya", "nextRecord": "Rekor selanjutnya", "previousRecord": "Rekor sebelumnya", "copyApiURL": "Salin API URL.", "createTable": "Create New Table", "refreshTable": "Tabel Refresh.", "renameTable": "Rename Table", "deleteTable": "Delete Table", "addField": "Tambahkan bidang baru ke tabel ini", "setDisplay": "Set as Display value", "addRow": "Tambahkan baris baru", "saveRow": "Hemat Baris", "saveAndExit": "Simpan & Keluar", "saveAndStay": "Simpan & Menginap", "insertRow": "Masukkan baris baru.", "duplicateRow": "Duplicate Row", "deleteRow": "Hapus Baris", "deleteSelectedRow": "Hapus baris yang dipilih", "importExcel": "Impor Excel.", "importCSV": "Impor CSV", "downloadCSV": "Unduh sebagai CSV.", "downloadExcel": "Unduh sebagai XLSX", "uploadCSV": "Unggah CSV.", "import": "Impor", "importMetadata": "Impor Metadata.", "exportMetadata": "Ekspor metadata.", "clearMetadata": "Clear Metadata.", "exportToFile": "Ekspor ke File.", "changePwd": "Ganti kata sandi", "createView": "Buat tampilan", "shareView": "Bagikan Lihat", "findRowByCodeScan": "Find row by scan", "fillByCodeScan": "Fill by scan", "listSharedView": "Daftar Tampilan Bersama", "ListView": "Tampilan daftar", "copyView": "Salin Lihat", "renameView": "Ganti nama tampilan", "deleteView": "Hapus Lihat", "createGrid": "Buat tampilan grid", "createGallery": "Buat Tampilan Galeri", "createCalendar": "Buat tampilan kalender", "createKanban": "Buat Pemandangan Kanban", "createForm": "Buat tampilan bentuk", "showSystemFields": "Tampilkan bidang sistem", "copyUrl": "Salin URL", "openTab": "Buka tab baru.", "iFrame": "Salin kode HTML yang dapat disematkan", "addWebhook": "Tambahkan WebHook Baru", "enableWebhook": "Enable Webhook", "testWebhook": "Test Webhook", "copyWebhook": "Copy Webhook", "deleteWebhook": "Delete Webhook", "newToken": "Tambahkan Token Baru.", "exportZip": "Ekspor Zip.", "importZip": "Impor Zip.", "metaSync": "Sinkronkan sekarang", "settings": "Pengaturan", "previewAs": "Pratinjau sebagai", "resetReview": "Reset Pratinjau", "testDbConn": "Tes Koneksi Basis Data", "removeDbFromEnv": "Hapus basis data dari lingkungan", "editConnJson": "Edit koneksi JSON.", "sponsorUs": "Mensponsori kami", "sendEmail": "MENGIRIM EMAIL", "addUserToProject": "Menambahkan pengguna ke proyek", "getApiSnippet": "Dapatkan Cuplikan API", "clearCell": "Hapus sel", "addFilterGroup": "Tambahkan Grup Filter", "linkRecord": "Catatan tautan", "addNewRecord": "Menambahkan catatan baru", "useConnectionUrl": "Gunakan URL Koneksi", "toggleCommentsDraw": "Beralih komentar menggambar", "expandRecord": "Perluas Catatan", "deleteRecord": "Menghapus Catatan", "erd": { "showColumns": "Tampilkan Kolom", "showPkAndFk": "Menampilkan Kunci Primer dan Kunci Asing", "showSqlViews": "Menampilkan Tampilan SQL", "showMMTables": "Tampilkan tabel Banyak ke Banyak", "showJunctionTableNames": "Tampilkan Nama Tabel Persimpangan" }, "kanban": { "collapseStack": "Tumpukan Runtuh", "deleteStack": "Hapus Tumpukan", "stackedBy": "Ditumpuk oleh", "chooseGroupingField": "Pilih Bidang Pengelompokan", "addOrEditStack": "Tambah / Edit Tumpukan" }, "map": { "mappedBy": "Mapped By", "chooseMappingField": "Choose a Mapping Field", "openInGoogleMaps": "Google Maps", "openInOpenStreetMap": "OSM" }, "toggleMobileMode": "Toggle Mobile Mode" }, "tooltip": { "saveChanges": "Simpan perubahan", "xcDB": "Buat proyek baru", "extDB": "Mendukung MySQL, PostgreSQL, SQL Server & SQLite", "apiRest": "Dapat diakses melalui API REST", "apiGQL": "Dapat diakses melalui Apis Graphql", "theme": { "dark": "Itu masuk hitam (^ ⇧b)", "light": "Apakah itu datang hitam? (^ ⇧b)" }, "addTable": "Tambahkan Tabel Baru", "inviteMore": "Undang lebih banyak pengguna", "toggleNavDraw": "Toggle Navigation Drawer.", "reloadApiToken": "Reload API Token.", "generateNewApiToken": "Menghasilkan token API baru", "addRole": "Tambahkan peran baru", "reloadList": "Muat Ulang Daftar", "metaSync": "Sinkronkan Metadata.", "sqlMigration": "Muat ulang migrasi", "updateRestart": "Perbarui & Restart.", "cancelReturn": "Batalkan dan kembali", "exportMetadata": "Ekspor semua metadata dari tabel meta ke direktori meta.", "importMetadata": "Impor semua metadata dari direktori Meta ke Meta Tables.", "clearMetadata": "Bersihkan semua metadata dari Meta Tables.", "clientKey": "Pilih .Key File.", "clientCert": "Pilih file .cert.", "clientCA": "Pilih CA File." }, "placeholder": { "projName": "Masukkan nama proyek", "password": { "enter": "Masukkan kata sandi", "current": "Kata sandi saat ini", "new": "Kata sandi baru", "save": "Simpan kata sandi", "confirm": "Konfirmasi password baru" }, "searchProjectTree": "Cari tabel", "searchFields": "Cari bidang", "searchColumn": "Cari kolom {search}", "searchApps": "Cari aplikasi", "searchModels": "Model pencarian", "noItemsFound": "Tidak ditemukan item", "defaultValue": "Nilai default.", "filterByEmail": "Saring melalui email", "filterQuery": "Kueri filter", "selectField": "Pilih bidang" }, "msg": { "warning": { "barcode": { "renderError": "Kesalahan kode batang - periksa kompatibilitas antara input dan jenis kode batang" }, "nonEditableFields": { "computedFieldUnableToClear": "Peringatan: Bidang yang dihitung - tidak dapat menghapus teks", "qrFieldsCannotBeDirectlyChanged": "Peringatan: Bidang QR tidak dapat diubah secara langsung." } }, "info": { "pasteNotSupported": "Operasi tempel tidak didukung pada sel aktif", "roles": { "orgCreator": "Kreator dapat membuat proyek baru dan mengakses proyek yang diundang.", "orgViewer": "Penonton tidak diizinkan untuk membuat proyek baru, tetapi mereka dapat mengakses proyek yang diundang." }, "codeScanner": { "loadingScanner": "Loading the scanner...", "selectColumn": "Select a column (QR code or Barcode) that you want to use for finding a row by scanning.", "moreThanOneRowFoundForCode": "More than one row found for this code. Currently only unique codes are supported.", "noRowFoundForCode": "No row found for this code for the selected column" }, "map": { "overLimit": "You're over the limit.", "closeLimit": "You're getting close to the limit.", "limitNumber": "The limit of markers shown in a Map View is 1000 records." }, "footerInfo": "Baris per halaman", "upload": "Pilih file untuk diunggah", "upload_sub": "atau seret dan jatuhkan file", "excelSupport": "Didukung: .xls, .xlsx, .xlsm, .ots, .ots", "excelURL": "Masukkan URL File Excel", "csvURL": "Masukkan URL File CSV", "footMsg": "# dari baris untuk menguraikan untuk menyimpulkan datatype", "excelImport": "Lembar tersedia untuk impor", "exportMetadata": "Apakah Anda ingin mengekspor metadata dari Meta Tables?", "importMetadata": "Apakah Anda ingin mengimpor metadata dari Meta Tables?", "clearMetadata": "Apakah Anda ingin menghapus metadata dari Meta Tables?", "projectEmptyMessage": "Mulailah dengan membuat proyek baru", "stopProject": "Apakah Anda ingin menghentikan proyek?", "startProject": "Apakah Anda ingin memulai proyek?", "restartProject": "Apakah Anda ingin memulai kembali proyek?", "deleteProject": "Apakah Anda ingin menghapus proyek?", "shareBasePrivate": "Menghasilkan basis readonly yang dapat dibagikan secara publik", "shareBasePublic": "Siapa pun di Internet dengan tautan ini dapat dilihat", "userInviteNoSMTP": "Sepertinya Anda belum mengonfigurasi mailer! Harap salin tautan undangan di atas dan kirimkan ke", "dragDropHide": "Seret dan jatuhkan bidang di sini untuk bersembunyi", "formInput": "Masukkan label input formulir", "formHelpText": "Tambahkan beberapa teks bantuan", "onlyCreator": "Hanya terlihat oleh pencipta", "formDesc": "Tambahkan Deskripsi Formulir ..", "beforeEnablePwd": "Batasi akses dengan kata sandi", "afterEnablePwd": "Akses dibatasi kata sandi", "privateLink": "Tampilan ini dibagikan melalui tautan pribadi", "privateLinkAdditionalInfo": "Orang dengan tautan pribadi hanya dapat melihat sel yang terlihat dalam pandangan ini", "afterFormSubmitted": "Setelah formulir dikirimkan", "apiOptions": "PROYEK AKSES VIA.", "submitAnotherForm": "Tampilkan tombol 'Kirim formulir lain'", "showBlankForm": "Tampilkan formulir kosong setelah 5 detik", "emailForm": "E-mail saya di", "showSysFields": "Tampilkan bidang sistem", "filterAutoApply": "Terapkan secara otomatis", "showMessage": "Tampilkan pesan ini", "viewNotShared": "Tampilan saat ini tidak dibagikan!", "showAllViews": "Tampilkan semua tampilan bersama dari tabel ini", "collabView": "Kolaborator dengan izin edit atau lebih tinggi dapat mengubah konfigurasi tampilan.", "lockedView": "Tidak ada yang dapat mengedit konfigurasi tampilan sampai tidak terkunci.", "personalView": "Hanya Anda yang dapat mengedit konfigurasi tampilan. Pandangan pribadi kolaborator lainnya disembunyikan secara default.", "ownerDesc": "Dapat menambah / menghapus pembuat. Dan struktur & bidang edit lengkap.", "creatorDesc": "Dapat sepenuhnya mengedit struktur & nilai basis data.", "editorDesc": "Dapat mengedit catatan tetapi tidak dapat mengubah struktur basis data / bidang.", "commenterDesc": "Dapat melihat dan mengomentari catatan tetapi tidak dapat mengedit apa pun", "viewerDesc": "Dapat melihat catatan tetapi tidak dapat mengedit apa pun", "addUser": "Tambahkan pengguna baru", "staticRoleInfo": "Peran yang ditentukan sistem tidak dapat diedit", "exportZip": "Meta proyek ekspor ke file zip dan unduh.", "importZip": "Impor file meta zip file dan restart.", "importText": "Impor proyek NOCODB dengan mengunggah file zip metadata", "metaNoChange": "Tidak ada perubahan yang diidentifikasi", "sqlMigration": "Migrasi skema akan dibuat secara otomatis. Buat tabel dan segarkan halaman ini.", "dbConnectionStatus": "Lingkungan divalidasi", "dbConnected": "Koneksi berhasil", "notifications": { "no_new": "Tidak ada pemberitahuan baru", "clear": "Jernih" }, "sponsor": { "header": "Anda dapat membantu kami!", "message": "Kami adalah tim kecil yang bekerja penuh waktu untuk membuat nocodb open-source. Kami percaya alat seperti NOCODB harus tersedia secara bebas ke setiap pemecah masalah di internet." }, "loginMsg": "Masuk ke nocodb", "passwordRecovery": { "message_1": "Harap berikan alamat email yang Anda gunakan saat mendaftar.", "message_2": "Kami akan mengirimkan email kepada Anda dengan tautan untuk mengatur ulang kata sandi Anda.", "success": "Silakan periksa email Anda untuk mengatur ulang kata sandi" }, "signUp": { "superAdmin": "Anda akan menjadi 'super admin'", "alreadyHaveAccount": "Sudah memiliki akun ?", "workEmail": "Masukkan email kantor Anda", "enterPassword": "Masukkan kata sandi Anda", "forgotPassword": "Lupa kata sandi Anda ?", "dontHaveAccount": "Tidak punya akun?" }, "addView": { "grid": "Tambahkan tampilan grid", "gallery": "Tambahkan Tampilan Galeri", "form": "Tambahkan tampilan formulir", "kanban": "Tambahkan Kanban Lihat", "map": "Add Map View", "calendar": "Tambahkan tampilan kalender" }, "tablesMetadataInSync": "Tabel metadata sedang disinkronkan", "addMultipleUsers": "Anda dapat menambahkan beberapa email terpisah koma (,)", "enterTableName": "Masukkan nama tabel", "addDefaultColumns": "Tambahkan kolom default.", "tableNameInDb": "Nama tabel sebagaimana disimpan dalam basis data", "airtable": { "credentials": "Di mana saya bisa menemukannya?" }, "import": { "clickOrDrag": "Klik atau seret file ke area ini untuk mengunggah" }, "metaDataRecreated": "Metadata tabel berhasil dibuat ulang", "invalidCredentials": "Kredensial tidak valid", "downloadingMoreFiles": "Mengunduh lebih banyak file", "copiedToClipboard": "Disalin ke papan klip", "requriedFieldsCantBeMoved": "Kolom yang harus diisi tidak dapat dipindahkan", "updateNotAllowedWithoutPK": "Update tidak diperbolehkan untuk tabel yang tidak memiliki primary key", "autoIncFieldNotEditable": "Bidang kenaikan otomatis tidak dapat diedit", "editingPKnotSupported": "Mengedit kunci utama tidak didukung", "deletedCache": "Berhasil menghapus cache", "cacheEmpty": "Cache kosong", "exportedCache": "Tembolok Berhasil Diekspor", "valueAlreadyInList": "Nilai ini sudah ada dalam daftar", "noColumnsToUpdate": "Tidak ada kolom untuk diperbarui", "tableDeleted": "Tabel berhasil dihapus", "generatePublicShareableReadonlyBase": "Menghasilkan basis hanya baca yang dapat dibagikan secara publik", "deleteViewConfirmation": "Apakah Anda yakin ingin menghapus tampilan ini?", "deleteTableConfirmation": "Apakah Anda ingin menghapus tabel", "showM2mTables": "Tampilkan Tabel M2M", "showM2mTablesDesc": "Many-to-many relation is supported via a junction table & is hidden by default. Enable this option to list all such tables along with existing tables.", "showNullInCells": "Show NULL in Cells", "showNullInCellsDesc": "Display 'NULL' tag in cells holding NULL value. This helps differentiate against cells holding EMPTY string.", "showNullAndEmptyInFilter": "Show NULL and EMPTY in Filter", "showNullAndEmptyInFilterDesc": "Enable 'additional' filters to differentiate fields containing NULL & Empty Strings. Default support for Blank treats both NULL & Empty strings alike.", "deleteKanbanStackConfirmation": "Menghapus tumpukan ini juga akan menghapus opsi pilihan `{stackToBeDeleted}` dari `{groupingField}`. Catatan akan berpindah ke tumpukan yang tidak dikategorikan.", "computedFieldEditWarning": "Bidang yang dihitung: isinya hanya dapat dibaca. Gunakan menu edit kolom untuk mengkonfigurasi ulang", "computedFieldDeleteWarning": "Bidang yang dihitung: isinya hanya dapat dibaca. Tidak dapat menghapus konten.", "noMoreRecords": "Tidak ada lagi catatan" }, "error": { "searchProject": "Pencarian Anda untuk {Search} tidak menemukan hasil", "invalidChar": "Karakter tidak valid di jalur folder.", "invalidDbCredentials": "Kredensial basis data tidak valid.", "unableToConnectToDb": "Tidak dapat terhubung ke database, silakan periksa basis data Anda.", "userDoesntHaveSufficientPermission": "Pengguna tidak ada atau memiliki izin yang cukup untuk membuat skema.", "dbConnectionStatus": "Parameter basis data tidak valid.", "dbConnectionFailed": "Koneksi Bermasalah:", "signUpRules": { "emailReqd": "E-mail diperlukan", "emailInvalid": "E-mail harus valid", "passwdRequired": "katakunci dibutuhkan", "passwdLength": "Kata sandi Anda harus minimal 8 karakter", "passwdMismatch": "Sandi tidak cocok", "completeRuleSet": "Minimal 8 karakter dengan satu huruf besar, satu angka, dan satu karakter khusus", "atLeast8Char": "Minimal 8 karakter", "atLeastOneUppercase": "Satu huruf besar", "atLeastOneNumber": "Satu Nomor", "atLeastOneSpecialChar": "Satu karakter khusus", "allowedSpecialCharList": "Daftar karakter khusus yang diizinkan" }, "invalidURL": "URL tidak valid", "invalidEmail": "Invalid Email", "internalError": "Beberapa kesalahan internal terjadi", "templateGeneratorNotFound": "Pembuat Templat tidak dapat ditemukan!", "fileUploadFailed": "Gagal mengunggah file", "primaryColumnUpdateFailed": "Gagal memperbarui kolom utama", "formDescriptionTooLong": "Data terlalu panjang untuk Deskripsi Formulir", "columnsRequired": "Kolom-kolom berikut ini wajib diisi", "selectAtleastOneColumn": "Setidaknya satu kolom harus dipilih", "columnDescriptionNotFound": "Tidak dapat menemukan kolom tujuan untuk", "duplicateMappingFound": "Pemetaan duplikat ditemukan, harap hapus salah satu pemetaan", "nullValueViolatesNotNull": "Nilai nol melanggar batasan bukan-nol", "sourceHasInvalidNumbers": "Data sumber mengandung beberapa angka yang tidak valid", "sourceHasInvalidBoolean": "Data sumber berisi beberapa nilai boolean yang tidak valid", "invalidForm": "Formulir Tidak Valid", "formValidationFailed": "Validasi formulir gagal", "youHaveBeenSignedOut": "Anda telah keluar", "failedToLoadList": "Gagal memuat daftar", "failedToLoadChildrenList": "Gagal memuat daftar anak", "deleteFailed": "Menghapus gagal", "unlinkFailed": "Putuskan tautan gagal", "rowUpdateFailed": "Pembaruan baris gagal", "deleteRowFailed": "Gagal menghapus baris", "setFormDataFailed": "Gagal mengatur data formulir", "formViewUpdateFailed": "Gagal memperbarui tampilan formulir", "tableNameRequired": "Nama tabel harus diisi", "nameShouldStartWithAnAlphabetOr_": "Nama harus dimulai dengan alfabet atau _", "followingCharactersAreNotAllowed": "Karakter berikut tidak diperbolehkan", "columnNameRequired": "Nama kolom harus diisi", "columnNameExceedsCharacters": "The length of column name exceeds the max {value} characters", "projectNameExceeds50Characters": "Nama proyek melebihi 50 karakter", "projectNameCannotStartWithSpace": "Nama proyek tidak boleh dimulai dengan spasi", "requiredField": "Bidang yang dibutuhkan", "ipNotAllowed": "IP tidak diizinkan", "targetFileIsNotAnAcceptedFileType": "File target bukan jenis file yang diterima", "theAcceptedFileTypeIsCsv": "Jenis file yang diterima adalah .csv", "theAcceptedFileTypesAreXlsXlsxXlsmOdsOts": "Jenis file yang diterima adalah .xls, .xlsx, .xlsm, .ods, .ots", "parameterKeyCannotBeEmpty": "Kunci parameter tidak boleh kosong", "duplicateParameterKeysAreNotAllowed": "Kunci parameter duplikat tidak diperbolehkan", "fieldRequired": "{value} tidak boleh kosong.", "projectNotAccessible": "Proyek tidak dapat diakses", "copyToClipboardError": "Gagal menyalin ke papan klip" }, "toast": { "exportMetadata": "Metadata proyek berhasil diekspor", "importMetadata": "Metadata proyek berhasil diimpor", "clearMetadata": "Metadata proyek berhasil dihapus", "stopProject": "Proyek berhasil berhenti", "startProject": "Proyek dimulai dengan sukses", "restartProject": "Proyek berhasil dimulai kembali", "deleteProject": "Proyek berhasil dihapus", "authToken": "Auth Token disalin ke clipboard", "projInfo": "Info proyek yang disalin ke clipboard", "inviteUrlCopy": "URL Undangan yang Disalin ke Clipboard", "createView": "Tampilan berhasil dibuat.", "formEmailSMTP": "Silakan Aktifkan Plugin SMTP di App Store untuk Mengaktifkan Pemberitahuan Email", "collabView": "Berhasil beralih ke tampilan kolaboratif", "lockedView": "Berhasil beralih ke tampilan yang dikunci", "futureRelease": "Segera akan datang!" }, "success": { "columnDuplicated": "Kolom berhasil diduplikasi", "rowDuplicatedWithoutSavedYet": "Row duplicated (not saved)", "updatedUIACL": "Berhasil memperbarui ACL UI untuk tabel", "pluginUninstalled": "Plugin berhasil dihapus instalasinya", "pluginSettingsSaved": "Pengaturan plugin berhasil disimpan", "pluginTested": "Pengaturan plugin yang berhasil diuji", "tableRenamed": "Tabel berhasil diganti namanya", "viewDeleted": "Tampilan berhasil dihapus", "primaryColumnUpdated": "Berhasil diperbarui sebagai kolom utama", "tableDataExported": "Berhasil mengekspor semua data tabel", "updated": "Berhasil diperbarui", "sharedViewDeleted": "Berhasil menghapus tampilan bersama", "userDeleted": "Pengguna berhasil dihapus", "viewRenamed": "Tampilan berhasil diganti namanya", "tokenGenerated": "Token berhasil dibuat", "tokenDeleted": "Token berhasil dihapus", "userAddedToProject": "Berhasil menambahkan pengguna ke proyek", "userAdded": "Berhasil menambahkan pengguna", "userDeletedFromProject": "Berhasil menghapus pengguna dari proyek", "inviteEmailSent": "Email undangan berhasil dikirim", "inviteURLCopied": "Mengundang URL yang disalin ke papan klip", "commentCopied": "Comment copied to clipboard", "passwordResetURLCopied": "URL pengaturan ulang kata sandi disalin ke papan klip", "shareableURLCopied": "Menyalin URL dasar yang dapat dibagikan ke papan klip!", "embeddableHTMLCodeCopied": "Menyalin kode HTML yang dapat disematkan!", "userDetailsUpdated": "Berhasil memperbarui detail pengguna", "tableDataImported": "Berhasil mengimpor data tabel", "webhookUpdated": "Detail webhook berhasil diperbarui", "webhookDeleted": "Pengait berhasil dihapus", "webhookTested": "Webhook berhasil diuji dengan sukses", "columnUpdated": "Kolom diperbarui", "columnCreated": "Kolom dibuat", "passwordChanged": "Kata sandi berhasil diubah. Silakan masuk lagi.", "settingsSaved": "Pengaturan berhasil disimpan", "roleUpdated": "Peran berhasil diperbarui" } } }
packages/nc-gui/lang/id.json
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00017778259643819183, 0.00017509431927464902, 0.00016525393584743142, 0.00017564772861078382, 0.000002180722049160977 ]
{ "id": 6, "code_window": [ " :disabled=\"readOnly || !editAllowed || isLockedMode\"\n", " :show-arrow=\"hasEditRoles && !(readOnly || isLockedMode) && active && vModel === null\"\n", " :dropdown-class-name=\"`nc-dropdown-single-select-cell ${isOpen && active ? 'active' : ''}`\"\n", " :show-search=\"isOpen && active\"\n", " @select=\"onSelect\"\n", " @keydown=\"onKeydown($event)\"\n", " @search=\"search\"\n", " >\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " :show-search=\"!isMobileMode && isOpen && active\"\n" ], "file_path": "packages/nc-gui/components/cell/SingleSelect.vue", "type": "replace", "edit_start_line_idx": 296 }
<script lang="ts" setup> import { onUnmounted } from '@vue/runtime-core' import { message } from 'ant-design-vue' import tinycolor from 'tinycolor2' import type { Select as AntSelect } from 'ant-design-vue' import type { SelectOptionType } from 'nocodb-sdk' import { ActiveCellInj, CellClickHookInj, ColumnInj, EditColumnInj, EditModeInj, IsFormInj, IsKanbanInj, ReadonlyInj, computed, enumColor, extractSdkResponseErrorMsg, iconMap, inject, isDrawerOrModalExist, ref, useBase, useEventListener, useRoles, useSelectedCellKeyupListener, watch, } from '#imports' interface Props { modelValue?: string | undefined rowIndex?: number disableOptionCreation?: boolean } const { modelValue, disableOptionCreation } = defineProps<Props>() const emit = defineEmits(['update:modelValue']) const column = inject(ColumnInj)! const readOnly = inject(ReadonlyInj)! const isLockedMode = inject(IsLockedInj, ref(false)) const isEditable = inject(EditModeInj, ref(false)) const activeCell = inject(ActiveCellInj, ref(false)) // use both ActiveCellInj or EditModeInj to determine the active state // since active will be false in case of form view const active = computed(() => activeCell.value || isEditable.value) const aselect = ref<typeof AntSelect>() const isOpen = ref(false) const isKanban = inject(IsKanbanInj, ref(false)) const isPublic = inject(IsPublicInj, ref(false)) const isEditColumn = inject(EditColumnInj, ref(false)) const isForm = inject(IsFormInj, ref(false)) const { $api } = useNuxtApp() const searchVal = ref() const { getMeta } = useMetas() const { isUIAllowed } = useRoles() const { isPg, isMysql } = useBase() // a variable to keep newly created option value // temporary until it's add the option to column meta const tempSelectedOptState = ref<string>() const isNewOptionCreateEnabled = computed(() => !isPublic.value && !disableOptionCreation && isUIAllowed('fieldEdit')) const options = computed<(SelectOptionType & { value: string })[]>(() => { if (column?.value.colOptions) { const opts = column.value.colOptions ? // todo: fix colOptions type, options does not exist as a property (column.value.colOptions as any).options.filter((el: SelectOptionType) => el.title !== '') || [] : [] for (const op of opts.filter((el: any) => el.order === null)) { op.title = op.title.replace(/^'/, '').replace(/'$/, '') } return opts.map((o: any) => ({ ...o, value: o.title })) } return [] }) const isOptionMissing = computed(() => { return (options.value ?? []).every((op) => op.title !== searchVal.value) }) const hasEditRoles = computed(() => isUIAllowed('dataEdit')) const editAllowed = computed(() => (hasEditRoles.value || isForm.value) && active.value) const vModel = computed({ get: () => tempSelectedOptState.value ?? modelValue?.trim(), set: (val) => { if (val && isNewOptionCreateEnabled.value && (options.value ?? []).every((op) => op.title !== val)) { tempSelectedOptState.value = val return addIfMissingAndSave() } emit('update:modelValue', val || null) }, }) watch(isOpen, (n, _o) => { if (editAllowed.value) { if (!n) { aselect.value?.$el?.querySelector('input')?.blur() } else { aselect.value?.$el?.querySelector('input')?.focus() } } }) useSelectedCellKeyupListener(activeCell, (e) => { switch (e.key) { case 'Escape': isOpen.value = false break case 'Enter': if (editAllowed.value && active.value && !isOpen.value) { isOpen.value = true } break // skip space bar key press since it's used for expand row case ' ': break default: if (!editAllowed.value) { e.preventDefault() break } // toggle only if char key pressed if (!(e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) && e.key?.length === 1 && !isDrawerOrModalExist()) { e.stopPropagation() isOpen.value = true } break } }) // close dropdown list on escape useSelectedCellKeyupListener(isOpen, (e) => { if (e.key === 'Escape') isOpen.value = false }) async function addIfMissingAndSave() { if (!tempSelectedOptState.value || isPublic.value) return false const newOptValue = tempSelectedOptState.value searchVal.value = '' tempSelectedOptState.value = undefined if (newOptValue && !options.value.some((o) => o.title === newOptValue)) { try { options.value.push({ title: newOptValue, value: newOptValue, color: enumColor.light[(options.value.length + 1) % enumColor.light.length], }) column.value.colOptions = { options: options.value.map(({ value: _, ...rest }) => rest) } const updatedColMeta = { ...column.value } // todo: refactor and avoid repetition if (updatedColMeta.cdf) { // Postgres returns default value wrapped with single quotes & casted with type so we have to get value between single quotes to keep it unified for all databases if (isPg(column.value.source_id)) { updatedColMeta.cdf = updatedColMeta.cdf.substring( updatedColMeta.cdf.indexOf(`'`) + 1, updatedColMeta.cdf.lastIndexOf(`'`), ) } // Mysql escapes single quotes with backslash so we keep quotes but others have to unescaped if (!isMysql(column.value.source_id) && !isPg(column.value.source_id)) { updatedColMeta.cdf = updatedColMeta.cdf.replace(/''/g, "'") } } await $api.dbTableColumn.update( (column.value as { fk_column_id?: string })?.fk_column_id || (column.value?.id as string), updatedColMeta, ) vModel.value = newOptValue await getMeta(column.value.fk_model_id!, true) } catch (e: any) { console.log(e) message.error(await extractSdkResponseErrorMsg(e)) } } } const search = () => { searchVal.value = aselect.value?.$el?.querySelector('.ant-select-selection-search-input')?.value } // prevent propagation of keydown event if select is open const onKeydown = (e: KeyboardEvent) => { if (isOpen.value && active.value) { e.stopPropagation() } if (e.key === 'Enter') { e.stopPropagation() } } const onSelect = () => { isOpen.value = false isEditable.value = false } const cellClickHook = inject(CellClickHookInj, null) const toggleMenu = (e: Event) => { // todo: refactor // check clicked element is clear icon if ( (e.target as HTMLElement)?.classList.contains('ant-select-clear') || (e.target as HTMLElement)?.closest('.ant-select-clear') ) { vModel.value = '' return e.stopPropagation() } if (cellClickHook) return isOpen.value = editAllowed.value && !isOpen.value } const cellClickHookHandler = () => { isOpen.value = editAllowed.value && !isOpen.value } onMounted(() => { cellClickHook?.on(cellClickHookHandler) }) onUnmounted(() => { cellClickHook?.on(cellClickHookHandler) }) const handleClose = (e: MouseEvent) => { if (isOpen.value && aselect.value && !aselect.value.$el.contains(e.target)) { isOpen.value = false } } useEventListener(document, 'click', handleClose, true) const selectedOpt = computed(() => { return options.value.find((o) => o.value === vModel.value) }) </script> <template> <div class="h-full w-full flex items-center nc-single-select" :class="{ 'read-only': readOnly || isLockedMode }" @click="toggleMenu" > <div v-if="!(active || isEditable)"> <a-tag v-if="selectedOpt" class="rounded-tag" :color="selectedOpt.color"> <span :style="{ 'color': tinycolor.isReadable(selectedOpt.color || '#ccc', '#fff', { level: 'AA', size: 'large' }) ? '#fff' : tinycolor.mostReadable(selectedOpt.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '13px', }" :class="{ 'text-sm': isKanban }" > {{ selectedOpt.title }} </span> </a-tag> </div> <a-select v-else ref="aselect" v-model:value="vModel" class="w-full overflow-hidden" :class="{ 'caret-transparent': !hasEditRoles }" :placeholder="isEditColumn ? $t('labels.optional') : ''" :allow-clear="!column.rqd && editAllowed" :bordered="false" :open="isOpen && editAllowed" :disabled="readOnly || !editAllowed || isLockedMode" :show-arrow="hasEditRoles && !(readOnly || isLockedMode) && active && vModel === null" :dropdown-class-name="`nc-dropdown-single-select-cell ${isOpen && active ? 'active' : ''}`" :show-search="isOpen && active" @select="onSelect" @keydown="onKeydown($event)" @search="search" > <a-select-option v-for="op of options" :key="op.title" :value="op.title" :data-testid="`select-option-${column.title}-${rowIndex}`" :class="`nc-select-option-${column.title}-${op.title}`" @click.stop > <a-tag class="rounded-tag" :color="op.color"> <span :style="{ 'color': tinycolor.isReadable(op.color || '#ccc', '#fff', { level: 'AA', size: 'large' }) ? '#fff' : tinycolor.mostReadable(op.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '13px', }" :class="{ 'text-sm': isKanban }" > {{ op.title }} </span> </a-tag> </a-select-option> <a-select-option v-if="searchVal && isOptionMissing && isNewOptionCreateEnabled" :key="searchVal" :value="searchVal"> <div class="flex gap-2 text-gray-500 items-center h-full"> <component :is="iconMap.plusThick" class="min-w-4" /> <div class="text-xs whitespace-normal"> {{ $t('msg.selectOption.createNewOptionNamed') }} <strong>{{ searchVal }}</strong> </div> </div> </a-select-option> </a-select> </div> </template> <style scoped lang="scss"> .rounded-tag { @apply py-0 px-[12px] rounded-[12px]; } :deep(.ant-tag) { @apply "rounded-tag" my-[2px]; } :deep(.ant-select-clear) { opacity: 1; } .nc-single-select:not(.read-only) { :deep(.ant-select-selector), :deep(.ant-select-selector input) { @apply !cursor-pointer; } } :deep(.ant-select-selector) { @apply !px-0; } :deep(.ant-select-selection-search-input) { @apply !text-xs; } :deep(.ant-select-clear > span) { @apply block; } </style>
packages/nc-gui/components/cell/SingleSelect.vue
1
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.986524224281311, 0.02825973741710186, 0.00016512243018951267, 0.00017588722403161228, 0.15975329279899597 ]
{ "id": 6, "code_window": [ " :disabled=\"readOnly || !editAllowed || isLockedMode\"\n", " :show-arrow=\"hasEditRoles && !(readOnly || isLockedMode) && active && vModel === null\"\n", " :dropdown-class-name=\"`nc-dropdown-single-select-cell ${isOpen && active ? 'active' : ''}`\"\n", " :show-search=\"isOpen && active\"\n", " @select=\"onSelect\"\n", " @keydown=\"onKeydown($event)\"\n", " @search=\"search\"\n", " >\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " :show-search=\"!isMobileMode && isOpen && active\"\n" ], "file_path": "packages/nc-gui/components/cell/SingleSelect.vue", "type": "replace", "edit_start_line_idx": 296 }
import { useState } from '#imports' export function useFieldQuery() { // initial search object const emptyFieldQueryObj = { field: '', query: '', } // mapping view id (key) to corresponding emptyFieldQueryObj (value) const searchMap = useState<Record<string, { field: string; query: string }>>('field-query-search-map', () => ({})) // the fieldQueryObj under the current view const search = useState<{ field: string; query: string }>('field-query-search', () => ({ ...emptyFieldQueryObj })) // retrieve the fieldQueryObj of the given view id // if it is not found in `searchMap`, init with emptyFieldQueryObj const loadFieldQuery = (id?: string) => { if (!id) return if (!(id in searchMap.value)) { searchMap.value[id] = { ...emptyFieldQueryObj } } search.value = searchMap.value[id] } return { search, loadFieldQuery } }
packages/nc-gui/composables/useFieldQuery.ts
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00017205187759827822, 0.00017049985763151199, 0.0001688654738245532, 0.00017058220691978931, 0.0000013021466429563588 ]
{ "id": 6, "code_window": [ " :disabled=\"readOnly || !editAllowed || isLockedMode\"\n", " :show-arrow=\"hasEditRoles && !(readOnly || isLockedMode) && active && vModel === null\"\n", " :dropdown-class-name=\"`nc-dropdown-single-select-cell ${isOpen && active ? 'active' : ''}`\"\n", " :show-search=\"isOpen && active\"\n", " @select=\"onSelect\"\n", " @keydown=\"onKeydown($event)\"\n", " @search=\"search\"\n", " >\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " :show-search=\"!isMobileMode && isOpen && active\"\n" ], "file_path": "packages/nc-gui/components/cell/SingleSelect.vue", "type": "replace", "edit_start_line_idx": 296 }
{ "general": { "home": "Forside", "load": "Indlæs", "open": "Åbn", "close": "Luk", "yes": "Ja", "no": "Nej", "ok": "Okay", "and": "Og", "or": "Eller", "add": "Tilføj", "edit": "Redigér", "remove": "Fjern", "save": "Gem", "cancel": "Fortryd", "submit": "Indsend", "create": "Opret", "duplicate": "Duplikat", "insert": "Indsæt", "delete": "Slet", "update": "Opdatér", "rename": "Omdøb", "reload": "Genindlæs", "reset": "Nulstil", "install": "Installer", "show": "Vis", "hide": "Skjul", "showAll": "Vis alt", "hideAll": "Gem alt", "showMore": "Vis mere", "showOptions": "Vis muligheder.", "hideOptions": "Skjul muligheder.", "showMenu": "Vis menu.", "hideMenu": "Skjul menu.", "addAll": "Tilføj alt.", "removeAll": "Fjern alt", "signUp": "Tilmelde", "signIn": "LOG IND", "signOut": "Log ud", "required": "Påkrævet", "enableScanner": "Enable Scanner for filling", "preferred": "Foretrukne", "mandatory": "Obligatorisk", "loading": "Indlæser ...", "title": "Titel", "upload": "Upload", "download": "Hent", "default": "Standard", "more": "Mere", "less": "Mindre", "event": "Begivenhed", "condition": "Tilstand", "after": "Efter", "before": "Før", "search": "Søg", "notification": "Notifikation", "reference": "Henvisning", "function": "Fungere", "confirm": "Bekræft", "generate": "Generer", "copy": "Kopier", "misc": "Diverse", "lock": "Lås", "unlock": "Lås op", "credentials": "Legitimationsoplysninger", "help": "Hjælp", "questions": "Spørgsmål", "reachOut": "Kontakt os her", "betaNote": "Denne funktion er i øjeblikket i betaversion.", "moreInfo": "Du kan finde flere oplysninger her", "logs": "Logfiler", "groupingField": "Grupperingsfelt", "insertAfter": "Indsæt efter", "insertBefore": "Indsæt før", "hideField": "Skjul felt", "sortAsc": "Sortere stigende", "sortDesc": "Sortere nedadgående", "geoDataField": "GeoData-felt" }, "objects": { "project": "Projekt", "projects": "Projekter", "table": "Bord", "tables": "Tabeller", "field": "Mark", "fields": "Felter", "column": "Kolonne", "columns": "Kolonner.", "page": "Side", "pages": "sider", "record": "Optage", "records": "Optegnelser.", "webhook": "WebHook.", "webhooks": "Webhooks.", "view": "Visning", "views": "Visninger", "viewType": { "grid": "Grid", "gallery": "Galleri", "form": "Formular", "kanban": "Kanban.", "calendar": "Kalender", "map": "Kort" }, "user": "Bruger", "users": "Brugere", "role": "Rolle", "roles": "Roller.", "roleType": { "owner": "Ejer", "creator": "Skaber.", "editor": "Editor.", "commenter": "Kommenter.", "viewer": "Viewer.", "orgLevelCreator": "Skaberen på organisationsniveau", "orgLevelViewer": "Visning på organisationsniveau" }, "sqlVIew": "SQL-visning" }, "datatype": { "ID": "ID.", "ForeignKey": "Fremmed nøgle", "SingleLineText": "Single Line Text.", "LongText": "Lang tekst.", "Attachment": "Vedhæftet fil", "Checkbox": "Afkrydsningsfelt", "MultiSelect": "Multi Select.", "SingleSelect": "Single Select.", "Collaborator": "Samarbejdspartner", "Date": "Dato", "Year": "År", "Time": "Tid", "PhoneNumber": "Telefonnummer", "Email": "Email.", "URL": "URL.", "Number": "Nummer", "Decimal": "Decimal", "Currency": "betalingsmiddel", "Percent": "Procentdel", "Duration": "Varighed", "GeoData": "GeoData", "Rating": "Bedømmelse", "Formula": "Formel", "Rollup": "Rul op", "Count": "Tælle", "Lookup": "Kig op", "DateTime": "Dato tid", "CreateTime": "Opret tid", "LastModifiedTime": "Sidste ændret tid", "AutoNumber": "Auto nummer.", "Barcode": "Stregkode.", "Button": "Knap", "Password": "Adgangskode", "relationProperties": { "noAction": "Ingen handling", "cascade": "Cascade.", "restrict": "Begrænse", "setNull": "Set null.", "setDefault": "Sæt standard" } }, "filterOperation": { "isEqual": "er ligning", "isNotEqual": "er ikke lige", "isLike": "er ligesom", "isNot like": "er ikke lignende", "isEmpty": "er tom", "isNotEmpty": "er ikke tomt", "isNull": "er null.", "isNotNull": "er ikke null." }, "title": { "erdView": "ERD-visning", "newProj": "Nyt projekt", "myProject": "Mine projekter", "formTitle": "Form titel", "collabView": "Collaborative View.", "lockedView": "Låst udsigt", "personalView": "Personlig visning", "appStore": "App butik", "teamAndAuth": "Team & Auth.", "rolesUserMgmt": "Roller & Brugere Management", "userMgmt": "Bruger Management", "apiTokenMgmt": "API TOKENS MANAGEMENT", "rolesMgmt": "Roller Management.", "projMeta": "Projektmetadata.", "metaMgmt": "Meta Management.", "metadata": "Metadata.", "exportImportMeta": "Eksport / Import Metadata", "uiACL": "Adgangskontrol af brugergrænsefladen", "metaOperations": "Metadata-operationer", "audit": "Revidere", "auditLogs": "Audit log", "sqlMigrations": "SQL Migrations.", "dbCredentials": "Database legitimationsoplysninger.", "advancedParameters": "SSL & Avancerede parametre", "headCreateProject": "Opret projekt | Nocodb.", "headLogin": "Log ind | Nocodb.", "resetPassword": "Nulstil din adgangskode", "teamAndSettings": "Hold og indstillinger", "apiDocs": "API-dokumenter", "importFromAirtable": "Import fra Airtable", "generateToken": "Generer et symbol", "APIsAndSupport": "API'er og support", "helpCenter": "Hjælp-center", "swaggerDocumentation": "Swagger-dokumentation", "quickImportFrom": "Hurtig import fra", "quickImport": "Hurtig import", "advancedSettings": "Avancerede indstillinger", "codeSnippet": "Kodeuddrag", "keyboardShortcut": "Tastaturgenveje", "generateRandomName": "Generér Tilfældigt Navn", "findRowByScanningCode": "Find row by scanning a QR or Barcode" }, "labels": { "createdBy": "Oprettet af", "notifyVia": "Bemærk Via.", "projName": "Projekt navn", "tableName": "Tabelnavn.", "viewName": "Se navn", "viewLink": "Vis Link", "columnName": "Kolonne navn", "columnToScanFor": "Column to scan", "columnType": "Kolonne type", "roleName": "Rolle navn", "roleDescription": "Rollebeskrivelsen", "databaseType": "Indtast database", "lengthValue": "Længde / værdi.", "dbType": "Database type", "sqliteFile": "SQLITE FILE.", "hostAddress": "Værtsadresse.", "port": "Port nummer.", "username": "Brugernavn.", "password": "Adgangskode", "schemaName": "Skema-navn", "database": "Database", "action": "Handling", "actions": "Handlinger", "operation": "Operation", "operationSub": "Underordnet operation", "operationType": "Driftstype", "operationSubType": "Drift Undertype", "description": "Beskrivelse", "authentication": "Godkendelse", "token": "Polet", "where": "Hvor", "cache": "Cache", "chat": "Snak", "email": "E-mail.", "storage": "Opbevaring", "uiAcl": "UI-ACL", "models": "Modeller.", "syncState": "Synkroniser tilstand", "created": "Oprettet", "sqlOutput": "SQL Output.", "addOption": "Tilføj option", "qrCodeValueColumn": "Kolonne med QR-kodeværdi", "barcodeValueColumn": "Kolonne med stregkodeværdi", "barcodeFormat": "Stregkodeformat", "qrCodeValueTooLong": "For mange tegn til en QR-kode", "barcodeValueTooLong": "For mange tegn til en stregkode", "currentLocation": "Current Location", "lng": "Lng", "lat": "Lat", "aggregateFunction": "Aggregate Function.", "dbCreateIfNotExists": "DATABASE: Opret, hvis ikke eksisterer", "clientKey": "Klientnøgle", "clientCert": "Klient cert.", "serverCA": "Server ca.", "requriedCa": "Påkrævet-ca.", "requriedIdentity": "Påkrævet-identitet", "inflection": { "tableName": "Bøjning - Bordnavn", "columnName": "Bøjning - kolonne navn" }, "community": { "starUs1": "Stjerne", "starUs2": "os på github.", "bookDemo": "Book en gratis demo", "getAnswered": "Få dine spørgsmål besvaret", "joinDiscord": "Deltag Diskord", "joinCommunity": "Tilmeld dig NocoDB-fællesskabet", "joinReddit": "Deltag /r/NocoDB", "followNocodb": "Følg NocoDB" }, "docReference": "Dokumentreference.", "selectUserRole": "Vælg brugerrolle", "childTable": "Undertabel", "childColumn": "Underkolonner", "linkToAnotherRecord": "Link til en anden post", "onUpdate": "På opdatering", "onDelete": "På Delete.", "account": "Konto", "language": "Sprog", "primaryColor": "Primær farve", "accentColor": "Accentfarve", "customTheme": "Brugerdefineret tema", "requestDataSource": "Har du brug for en datakilde, du har brug for?", "apiKey": "API-nøgle", "sharedBase": "Fælles base", "importData": "Import af data", "importSecondaryViews": "Import af sekundære visninger", "importRollupColumns": "Import af kolonner i rulleskemaer", "importLookupColumns": "Import af opslagssøjler", "importAttachmentColumns": "Import af kolonner til vedhæftede filer", "importFormulaColumns": "Import af formelkolonner", "noData": "Ingen data", "goToDashboard": "Gå til Dashboard", "importing": "Import af", "flattenNested": "Flade, indlejrede", "downloadAllowed": "Download tilladt", "weAreHiring": "Vi ansætter!", "primaryKey": "Primærnøgle", "hasMany": "har mange", "belongsTo": "hører til", "manyToMany": "har mange til mange relationer", "extraConnectionParameters": "Ekstra forbindelsesparametre", "commentsOnly": "Kun kommentarer", "documentation": "Dokumentation", "subscribeNewsletter": "Tilmeld dig vores ugentlige nyhedsbrev", "signUpWithProvider": "Tilmeld dig hos {provider}", "signInWithProvider": "Log på med {provider}", "agreeToTos": "Ved at tilmelde dig accepterer du vilkårene for service", "welcomeToNc": "Velkommen til NocoDB!", "inviteOnlySignup": "Tillad kun tilmelding ved hjælp af inviteret url", "nextRow": "Næste række", "prevRow": "Forrige række" }, "activity": { "createProject": "Opret projekt", "importProject": "Import Project.", "searchProject": "Søg projekt", "editProject": "Rediger projekt", "stopProject": "Stop Project.", "startProject": "Start Project.", "restartProject": "Genstart Project.", "deleteProject": "Slet projekt", "refreshProject": "Opdater projekter", "saveProject": "Gem projekt", "deleteKanbanStack": "Slet stakken?", "createProjectExtended": { "extDB": "Opret ved at forbinde <br> til en ekstern database", "excel": "Opret projekt fra Excel", "template": "Opret projekt fra skabelon" }, "OkSaveProject": "OK & Gem projekt", "upgrade": { "available": "Opgrader tilgængelig", "releaseNote": "Udgivelses noter", "howTo": "Sådan opgraderes?" }, "translate": "Hjælp Translate", "account": { "authToken": "Kopier Auth Token", "swagger": "Swagger: REST API'er", "projInfo": "Kopier projekt info.", "themes": "Temaer." }, "sort": "Sortere", "addSort": "Tilføj sorteringsindstilling", "filter": "Filter", "addFilter": "Tilføj filter", "share": "Del", "shareBase": { "disable": "Deaktiver delt base", "enable": "Nogen med linket", "link": "Shared Base Link." }, "invite": "Invitere", "inviteMore": "Inviter mere", "inviteTeam": "Inviter Team.", "inviteUser": "Inviter bruger", "inviteToken": "Inviter token", "newUser": "Ny bruger", "editUser": "Rediger bruger", "deleteUser": "Fjern bruger fra projektet", "resendInvite": "Genoplevelse Inviter e-mail på", "copyInviteURL": "Kopier Inviter URL", "copyPasswordResetURL": "Kopier URL til nulstilling af adgangskode", "newRole": "Ny rolle", "reloadRoles": "Genindlæs roller", "nextPage": "Næste side", "prevPage": "Forrige side", "nextRecord": "Næste post", "previousRecord": "Forrige post", "copyApiURL": "COPY API URL.", "createTable": "Create New Table", "refreshTable": "Genopfrisk Tabeller", "renameTable": "Rename Table", "deleteTable": "Delete Table", "addField": "Tilføj nyt felt til denne tabel", "setDisplay": "Sæt som visningsværdi", "addRow": "Tilføj ny post", "saveRow": "Gem række", "saveAndExit": "Gem og afslutning", "saveAndStay": "Gem og bliv", "insertRow": "Indsæt ny række", "duplicateRow": "Dupliker Række", "deleteRow": "Slet Række", "deleteSelectedRow": "Slet de valgte rækker", "importExcel": "Import Excel.", "importCSV": "Import CSV.", "downloadCSV": "Download som CSV.", "downloadExcel": "Download som XLSX", "uploadCSV": "Upload CSV.", "import": "Import", "importMetadata": "Import metadata.", "exportMetadata": "Eksport metadata.", "clearMetadata": "Klare metadata.", "exportToFile": "Eksporter til filer", "changePwd": "Skift kodeord", "createView": "Opret en visning", "shareView": "Del Visning", "findRowByCodeScan": "Find row by scan", "fillByCodeScan": "Fill by scan", "listSharedView": "Shared View List.", "ListView": "Visninger List", "copyView": "Kopi visning", "renameView": "Omdøb visning", "deleteView": "Slet visning", "createGrid": "Opret gridvisning", "createGallery": "Opret Gallery View.", "createCalendar": "Opret kalendervisning", "createKanban": "Opret Kanban View.", "createForm": "Opret formularvisning", "showSystemFields": "Vis systemfelter", "copyUrl": "Kopier URL.", "openTab": "Åbn ny fane.", "iFrame": "Kopier Embeddable HTML-kode", "addWebhook": "Tilføj nyt webhook.", "enableWebhook": "Enable Webhook", "testWebhook": "Test Webhook", "copyWebhook": "Copy Webhook", "deleteWebhook": "Delete Webhook", "newToken": "Tilføj nyt token", "exportZip": "Eksporter zip", "importZip": "Import Zip.", "metaSync": "Synkroniser nu", "settings": "Indstillinger.", "previewAs": "Forhåndsvisning som", "resetReview": "Nulstil forhåndsvisning", "testDbConn": "Test Database Forbindelse", "removeDbFromEnv": "Fjern databasen fra miljøet", "editConnJson": "Rediger forbindelse JSON", "sponsorUs": "Sponsorer os", "sendEmail": "SEND E-MAIL", "addUserToProject": "Tilføj bruger til projekt", "getApiSnippet": "Hent API-snippet", "clearCell": "Ryd celle", "addFilterGroup": "Tilføj filtergruppe", "linkRecord": "Link record", "addNewRecord": "Tilføj ny post", "useConnectionUrl": "Brug forbindelses-URL", "toggleCommentsDraw": "Toggle kommentarer tegne", "expandRecord": "Udvid optegnelse", "deleteRecord": "Slet Post", "erd": { "showColumns": "Vis kolonner", "showPkAndFk": "Vis primære og fremmede nøgler", "showSqlViews": "Vis SQL-visninger", "showMMTables": "Vis mange til mange-tabeller", "showJunctionTableNames": "Vis navne på krydsningstabeller" }, "kanban": { "collapseStack": "Kollaps af stak", "deleteStack": "Slet stak", "stackedBy": "Stablet af", "chooseGroupingField": "Vælg et grupperingsfelt", "addOrEditStack": "Tilføj / Rediger stak" }, "map": { "mappedBy": "Kortlagt af", "chooseMappingField": "Vælg et kortlægningsfelt", "openInGoogleMaps": "Google Maps", "openInOpenStreetMap": "OSM" }, "toggleMobileMode": "Toggle Mobile Mode" }, "tooltip": { "saveChanges": "Gem ændringer", "xcDB": "Opret et nyt projekt", "extDB": "Understøtter MySQL, PostgreSQL, SQL Server & SQLITE", "apiRest": "Tilgængelig via hvile API'er", "apiGQL": "Tilgængelig via GraphQL Apis", "theme": { "dark": "Det kommer i sort (^ ⇧b)", "light": "Kommer det i sort? (^ ⇧b)" }, "addTable": "Tilføj nyt tabel", "inviteMore": "Inviter flere brugere", "toggleNavDraw": "Toggle navigation skuffe", "reloadApiToken": "Genindlæs API Tokens", "generateNewApiToken": "Generere nye API-token", "addRole": "Tilføj ny rolle", "reloadList": "Reload List.", "metaSync": "SYNC METADATA.", "sqlMigration": "Genindlæs migreringer.", "updateRestart": "Opdatering og genstart", "cancelReturn": "Annuller og returnerer", "exportMetadata": "Eksporter alle metadata fra metabordene til metatirectory.", "importMetadata": "Importer alle metadata fra metatappen til metaborde.", "clearMetadata": "Ryd alle metadata fra metaborde.", "clientKey": "Vælg .Key File.", "clientCert": "Vælg .cert File.", "clientCA": "Vælg CA File." }, "placeholder": { "projName": "Indtast projektnavn", "password": { "enter": "Indtast adgangskoden", "current": "Nuværende kodeord", "new": "Nyt kodeord", "save": "Gem adgangskode.", "confirm": "Bekræft ny adgangskode" }, "searchProjectTree": "Søg tabeller", "searchFields": "Søgefelter.", "searchColumn": "Søg {Søg} kolonne", "searchApps": "Søg apps.", "searchModels": "Søgemodeller.", "noItemsFound": "Ingen varer fundet", "defaultValue": "Standard værdi", "filterByEmail": "Filtrer efter e-mail", "filterQuery": "Filter forespørgsel", "selectField": "Vælg felt" }, "msg": { "warning": { "barcode": { "renderError": "Stregkodefejl - kontroller kompatibiliteten mellem input og stregkodetype" }, "nonEditableFields": { "computedFieldUnableToClear": "Advarsel: Beregnet felt - ikke i stand til at slette teksten", "qrFieldsCannotBeDirectlyChanged": "Advarsel: QR-felter kan ikke ændres direkte." } }, "info": { "pasteNotSupported": "Indsæt er ikke understøttet på den aktive celle", "roles": { "orgCreator": "Skaberen kan oprette nye projekter og få adgang til alle inviterede projekter.", "orgViewer": "Seeren har ikke lov til at oprette nye projekter, men kan få adgang til alle inviterede projekter." }, "codeScanner": { "loadingScanner": "Loading the scanner...", "selectColumn": "Select a column (QR code or Barcode) that you want to use for finding a row by scanning.", "moreThanOneRowFoundForCode": "More than one row found for this code. Currently only unique codes are supported.", "noRowFoundForCode": "No row found for this code for the selected column" }, "map": { "overLimit": "Du er over grænsen.", "closeLimit": "Du nærmer dig grænsen.", "limitNumber": "Grænsen for antallet af markeringer, der vises i en kortvisning, er 1000 poster." }, "footerInfo": "Rækker per side", "upload": "Vælg fil for at uploade", "upload_sub": "eller træk og slip filen", "excelSupport": "Støttet: .xls, .xlsx, .xlsm, .ods, .Oer", "excelURL": "Indtast Excel-fil-URL", "csvURL": "Indtast CSV-fil-URL", "footMsg": "# af rækker til at analysere for at udlede datatype", "excelImport": "ark (r) er tilgængelige for import", "exportMetadata": "Ønsker du at eksportere metadata fra metaborde?", "importMetadata": "Vil du importere metadata fra metaborde?", "clearMetadata": "Vil du rydde metadata fra metaborde?", "projectEmptyMessage": "Kom i gang ved at oprette et nyt projekt", "stopProject": "Ønsker du at stoppe projektet?", "startProject": "Ønsker du at starte projektet?", "restartProject": "Ønsker du at genstarte projektet?", "deleteProject": "Ønsker du at slette projektet?", "shareBasePrivate": "Generer offentligt delbart readonly base", "shareBasePublic": "Enhver på internettet med dette link kan se", "userInviteNoSMTP": "Ser ud som om du ikke har konfigureret mailer endnu! Kopier venligst ovenstående invitation link og send det til", "dragDropHide": "Træk og slip felter her for at skjule", "formInput": "Indtast formularindgangsmærke", "formHelpText": "Tilføj nogle hjælpetekst", "onlyCreator": "Kun synlig for skaberen", "formDesc": "Tilføj form Beskrivelse.", "beforeEnablePwd": "Begræns adgang med et kodeord", "afterEnablePwd": "Adgang er adgangskode begrænset", "privateLink": "Denne visning deles via et privat link", "privateLinkAdditionalInfo": "Folk med privat link kan kun se celler synlige i denne opfattelse", "afterFormSubmitted": "Efter formularen er indsendt", "apiOptions": "Access Project Via.", "submitAnotherForm": "Vis 'Indsend en anden formular' -knap", "showBlankForm": "Vis en blank form efter 5 sekunder", "emailForm": "E-mail mig på", "showSysFields": "Vis systemfelter", "filterAutoApply": "Auto Application", "showMessage": "Vis denne besked", "viewNotShared": "Nuværende visning er ikke delt!", "showAllViews": "Vis alle fælles visninger af denne tabel", "collabView": "Samarbejdspartnere med redigeringstilladelser eller højere kan ændre visningskonfigurationen.", "lockedView": "Ingen kan redigere visningskonfigurationen, indtil den er låst op.", "personalView": "Kun du kan redigere visningskonfigurationen. Andre samarbejdspartnere 'Personlige synspunkter er gemt som standard.", "ownerDesc": "Kan tilføje / fjerne skabere. Og Full Edit Database Structures & Fields.", "creatorDesc": "Kan fuldt ud redigere databasestruktur og værdier.", "editorDesc": "Kan redigere poster, men kan ikke ændre strukturen af ​​database / felter.", "commenterDesc": "Kan se og kommentere posterne, men kan ikke redigere noget", "viewerDesc": "Kan se posterne, men kan ikke redigere noget", "addUser": "Tilføj ny bruger", "staticRoleInfo": "Systemdefinerede roller kan ikke redigeres", "exportZip": "Eksporter Project Meta til ZIP-fil og download.", "importZip": "Import Project Meta Zip-fil og genstart.", "importText": "Import Nocodb-projekt ved at uploade Metadata Zip-filen", "metaNoChange": "Ingen ændring identificeret", "sqlMigration": "Schema Migrations vil blive oprettet automatisk. Opret et bord og opdater denne side.", "dbConnectionStatus": "Miljø valideret", "dbConnected": "Forbindelsen var succesfuld", "notifications": { "no_new": "Ingen nye meddelelser.", "clear": "Klar" }, "sponsor": { "header": "Du kan hjælpe os!", "message": "Vi er et lille team, der arbejder på fuld tid for at lave NOCODB OPEN-SOURCE. Vi mener, at et værktøj som Nocodb skal være tilgængeligt frit til alle problemløser på internettet." }, "loginMsg": "Log ind på NOCODB", "passwordRecovery": { "message_1": "Angiv venligst den e-mail-adresse, du brugte, når du tilmeldte dig.", "message_2": "Vi sender dig en email med et link for at nulstille dit kodeord.", "success": "Tjek venligst din email for at nulstille adgangskoden" }, "signUp": { "superAdmin": "Du vil være 'super admin'", "alreadyHaveAccount": "Har du allerede en bruger ?", "workEmail": "Indtast din arbejds-email", "enterPassword": "Skriv dit kodeord", "forgotPassword": "Glemt din adgangskode ?", "dontHaveAccount": "Har du ikke en konto?" }, "addView": { "grid": "Tilføj gridvisning", "gallery": "Tilføj Gallery View.", "form": "Tilføj formularvisning", "kanban": "Tilføj Kanban View.", "map": "Tilføj Kortvisning", "calendar": "Tilføj kalendervisning" }, "tablesMetadataInSync": "Tabeller Metadata er synkroniseret", "addMultipleUsers": "Du kan tilføje flere komma (,) adskilte e-mails", "enterTableName": "Indtast tabelnavn", "addDefaultColumns": "Tilføj standard kolonner", "tableNameInDb": "Tabelnavn som gemt i databasen", "airtable": { "credentials": "Hvor kan man finde det?" }, "import": { "clickOrDrag": "Klik eller træk filen til dette område for at uploade" }, "metaDataRecreated": "Tabelmetadata genskabt med succes", "invalidCredentials": "Ugyldige legitimationsoplysninger", "downloadingMoreFiles": "Hentning af flere filer", "copiedToClipboard": "Kopieret til udklipsholderen", "requriedFieldsCantBeMoved": "Krævet felt kan ikke flyttes", "updateNotAllowedWithoutPK": "Opdatering ikke tilladt for tabel, som ikke har primærnøgle", "autoIncFieldNotEditable": "Feltet for automatisk forøgelse kan ikke redigeres", "editingPKnotSupported": "Redigering af primærnøgle understøttes ikke", "deletedCache": "Slettet cache med succes", "cacheEmpty": "Cachen er tom", "exportedCache": "Cache eksporteret med succes", "valueAlreadyInList": "Denne værdi findes allerede på listen", "noColumnsToUpdate": "Ingen kolonner, der skal opdateres", "tableDeleted": "Slettet tabel med succes", "generatePublicShareableReadonlyBase": "Generer en offentlig delbar skrivebeskyttet base", "deleteViewConfirmation": "Er du sikker på, at du vil slette denne visning?", "deleteTableConfirmation": "Ønsker du at slette tabellen", "showM2mTables": "Vis M2M-tabeller", "showM2mTablesDesc": "Mange-til-mange-relationer understøttes via en sammenknytnings-tabel (junction table) og er skjult som standard. Aktiver denne indstilling for at få vist alle sådanne tabeller sammen med eksisterende tabeller.", "showNullInCells": "Vis NULL i celler", "showNullInCellsDesc": "Display 'NULL' tag in cells holding NULL value. This helps differentiate against cells holding EMPTY string.", "showNullAndEmptyInFilter": "Vis NULL og EMPTY i Filter", "showNullAndEmptyInFilterDesc": "Aktiver \"yderligere\" filtre for at skelne mellem felter, der indeholder NULL og tomme strenge. Standardunderstøttelse for Blank behandler både NULL- og tomme strenge ens.", "deleteKanbanStackConfirmation": "Hvis du sletter denne stak, fjernes også valgmuligheden `{stackToBeDeleted}` fra `{groupingField}`. Posterne vil blive flyttet til stakken \"uncategorized\".", "computedFieldEditWarning": "Beregnet felt: indholdet er skrivebeskyttet. Brug kolonne-redigeringsmenuen til at omkonfigurere", "computedFieldDeleteWarning": "Beregnet felt: indholdet er skrivebeskyttet. Det er ikke muligt at slette indholdet.", "noMoreRecords": "Ikke flere optegnelser" }, "error": { "searchProject": "Din søgning efter {Søg} viste ingen resultater", "invalidChar": "Ugyldig tegn i mappebanen.", "invalidDbCredentials": "Ugyldige databaseoplysninger.", "unableToConnectToDb": "Kan ikke oprette forbindelse til databasen, tjek venligst din database er op.", "userDoesntHaveSufficientPermission": "Brugeren eksisterer ikke eller har tilstrækkelig tilladelse til at skabe skema.", "dbConnectionStatus": "Ugyldige databaseparametre", "dbConnectionFailed": "Forbindelsesfejl:", "signUpRules": { "emailReqd": "E-mail er påkrævet", "emailInvalid": "E-mail skal være gyldig", "passwdRequired": "adgangskode er påkrævet", "passwdLength": "Din adgangskode skal være mindst 8 tegn", "passwdMismatch": "Kodeordene er ikke ens", "completeRuleSet": "Mindst 8 tegn med én stor bogstav, ét tal og ét specialtegn", "atLeast8Char": "Mindst 8 tegn", "atLeastOneUppercase": "Et stort bogstav", "atLeastOneNumber": "Et nummer", "atLeastOneSpecialChar": "Et specialtegn", "allowedSpecialCharList": "Liste over tilladte specialtegn" }, "invalidURL": "Ugyldig URL", "invalidEmail": "Invalid Email", "internalError": "Der er opstået en intern fejl", "templateGeneratorNotFound": "Template Generator kan ikke findes!", "fileUploadFailed": "Det er ikke lykkedes at uploade filen", "primaryColumnUpdateFailed": "Det lykkedes ikke at opdatere primær kolonne", "formDescriptionTooLong": "Data for lange til formularen Beskrivelse", "columnsRequired": "Følgende kolonner er påkrævet", "selectAtleastOneColumn": "Mindst én kolonne skal være valgt", "columnDescriptionNotFound": "Kan ikke finde destinationskolonnen for", "duplicateMappingFound": "Der er fundet en dobbelttilknytning, fjern venligst en af tilknytningerne", "nullValueViolatesNotNull": "Nul-værdi overtræder not-null-begrænsning", "sourceHasInvalidNumbers": "Kildedata indeholder nogle ugyldige tal", "sourceHasInvalidBoolean": "Kildedata indeholder nogle ugyldige boolske værdier", "invalidForm": "Ugyldig formular", "formValidationFailed": "Validering af formularen mislykkedes", "youHaveBeenSignedOut": "Du er blevet logget ud", "failedToLoadList": "Det er ikke lykkedes at indlæse listen", "failedToLoadChildrenList": "Det lykkedes ikke at indlæse listen over børn", "deleteFailed": "Sletning mislykkedes", "unlinkFailed": "Afbrydelse af forbindelsen mislykkedes", "rowUpdateFailed": "Opdatering af række mislykkedes", "deleteRowFailed": "Det er ikke lykkedes at slette en række", "setFormDataFailed": "Det lykkedes ikke at indstille formulardata", "formViewUpdateFailed": "Opdatering af formularvisning mislykkedes", "tableNameRequired": "Navnet på tabellen er påkrævet", "nameShouldStartWithAnAlphabetOr_": "Navnet skal starte med et alfabet eller _", "followingCharactersAreNotAllowed": "Følgende tegn er ikke tilladt", "columnNameRequired": "Kolonnens navn er påkrævet", "columnNameExceedsCharacters": "Længden af kolonnenavnet overstiger maks. {value} tegn", "projectNameExceeds50Characters": "Projektnavnet overstiger 50 tegn", "projectNameCannotStartWithSpace": "Projektnavnet kan ikke begynde med et mellemrum", "requiredField": "Obligatorisk felt", "ipNotAllowed": "IP ikke tilladt", "targetFileIsNotAnAcceptedFileType": "Målfilen er ikke en accepteret filtype", "theAcceptedFileTypeIsCsv": "Den accepterede filtype er .csv", "theAcceptedFileTypesAreXlsXlsxXlsmOdsOts": "De accepterede filtyper er .xls, .xlsx, .xlsm, .ods, .ots", "parameterKeyCannotBeEmpty": "Parameternøglen kan ikke være tom", "duplicateParameterKeysAreNotAllowed": "Det er ikke tilladt at duplikere parameternøgler", "fieldRequired": "{value} kan ikke være tom.", "projectNotAccessible": "Projektet er ikke tilgængeligt", "copyToClipboardError": "Kopiering til udklipsholderen mislykkedes" }, "toast": { "exportMetadata": "Project Metadata eksporteres med succes", "importMetadata": "Projektmetadata importeret med succes", "clearMetadata": "Projektmetadata ryddet med succes", "stopProject": "Projektet stoppet med succes", "startProject": "Projektet startede med succes", "restartProject": "Projekt genstartet med succes", "deleteProject": "Projekt slettet succes", "authToken": "Auth Token kopieret til udklipsholder", "projInfo": "Kopieret projektinfo til udklipsholder", "inviteUrlCopy": "Kopieret invitere url til udklipsholder", "createView": "View oprettet succes", "formEmailSMTP": "Aktivér venligst SMTP-plugin i App Store for at muliggøre e-mail-besked", "collabView": "Succesfuldt skiftet til samarbejdsvisning", "lockedView": "Succesfuldt skiftet til låst visning", "futureRelease": "Kommer snart!" }, "success": { "columnDuplicated": "Kolonne duplikeret med succes", "rowDuplicatedWithoutSavedYet": "Række duplikeret (ikke gemt)", "updatedUIACL": "Opdateret UI ACL for tabeller med succes", "pluginUninstalled": "Plugin afinstalleret med succes", "pluginSettingsSaved": "Plugin-indstillingerne er gemt med succes", "pluginTested": "Succesfuldt testet plugin-indstillinger", "tableRenamed": "Det er lykkedes at omdøbe tabellen", "viewDeleted": "Vis slettet med succes", "primaryColumnUpdated": "Succesfuldt opdateret som primær kolonne", "tableDataExported": "Det er lykkedes at eksportere alle tabeldata", "updated": "Succesfuldt opdateret", "sharedViewDeleted": "Slettet delt visning med succes", "userDeleted": "Bruger slettet med succes", "viewRenamed": "Visning omdøbt med succes", "tokenGenerated": "Token genereret med succes", "tokenDeleted": "Token slettet med succes", "userAddedToProject": "Det er lykkedes at tilføje en bruger til projektet", "userAdded": "Tilføjet bruger med succes", "userDeletedFromProject": "Det er lykkedes at slette brugeren fra projektet", "inviteEmailSent": "E-mail med invitation sendt med succes", "inviteURLCopied": "Inviter URL kopieret til udklipsholderen", "commentCopied": "Comment copied to clipboard", "passwordResetURLCopied": "URL til nulstilling af adgangskode kopieret til udklipsholderen", "shareableURLCopied": "Kopieret delbar basis-URL til udklipsholderen!", "embeddableHTMLCodeCopied": "Kopieret HTML-kode, der kan indlejres!", "userDetailsUpdated": "Det er lykkedes at opdatere brugeroplysningerne", "tableDataImported": "Det er lykkedes at importere tabeldata", "webhookUpdated": "Webhook-detaljerne er blevet opdateret med succes", "webhookDeleted": "Hook slettet med succes", "webhookTested": "Webhook testet med succes", "columnUpdated": "Kolonne opdateret", "columnCreated": "Oprettet kolonne", "passwordChanged": "Adgangskode ændret med succes. Log venligst ind igen.", "settingsSaved": "Indstillingerne er gemt med succes", "roleUpdated": "Rolle opdateret med succes" } } }
packages/nc-gui/lang/da.json
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00017994528752751648, 0.0001756921410560608, 0.00016630403115414083, 0.00017577543621882796, 0.0000019678498119901633 ]
{ "id": 6, "code_window": [ " :disabled=\"readOnly || !editAllowed || isLockedMode\"\n", " :show-arrow=\"hasEditRoles && !(readOnly || isLockedMode) && active && vModel === null\"\n", " :dropdown-class-name=\"`nc-dropdown-single-select-cell ${isOpen && active ? 'active' : ''}`\"\n", " :show-search=\"isOpen && active\"\n", " @select=\"onSelect\"\n", " @keydown=\"onKeydown($event)\"\n", " @search=\"search\"\n", " >\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " :show-search=\"!isMobileMode && isOpen && active\"\n" ], "file_path": "packages/nc-gui/components/cell/SingleSelect.vue", "type": "replace", "edit_start_line_idx": 296 }
import type { Knex } from 'knex'; import { MetaTable } from '~/utils/globals'; const up = async (knex: Knex) => { await knex.schema.alterTable(MetaTable.GRID_VIEW, (table) => { table.integer('row_height'); }); }; const down = async (knex) => { await knex.schema.alterTable(MetaTable.GRID_VIEW, (table) => { table.dropColumns('row_height'); }); }; export { up, down };
packages/nocodb/src/meta/migrations/v2/nc_025_add_row_height.ts
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00017834083701018244, 0.00017306787776760757, 0.0001677949185250327, 0.00017306787776760757, 0.000005272959242574871 ]
{ "id": 7, "code_window": [ " </a-select>\n", "</template>\n", "\n", "<style lang=\"scss\">\n", ".nc-select.ant-select {\n", " height: fit-content;\n", " .ant-select-selector {\n", " box-shadow: 0px 5px 3px -2px rgba(0, 0, 0, 0.02), 0px 3px 1px -2px rgba(0, 0, 0, 0.06);\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ ".ant-select-item {\n", " @apply !xs:h-13;\n", "}\n", ".ant-select-item-option-content {\n", " @apply !xs:mt-2.5;\n", "}\n", ".ant-select-item-option-state {\n", " @apply !xs:mt-1.75;\n", "}\n", "\n" ], "file_path": "packages/nc-gui/components/nc/Select.vue", "type": "add", "edit_start_line_idx": 57 }
<script lang="ts" setup> import { onUnmounted } from '@vue/runtime-core' import { message } from 'ant-design-vue' import tinycolor from 'tinycolor2' import type { Select as AntSelect } from 'ant-design-vue' import type { SelectOptionType } from 'nocodb-sdk' import { ActiveCellInj, CellClickHookInj, ColumnInj, EditColumnInj, EditModeInj, IsFormInj, IsKanbanInj, ReadonlyInj, computed, enumColor, extractSdkResponseErrorMsg, iconMap, inject, isDrawerOrModalExist, ref, useBase, useEventListener, useRoles, useSelectedCellKeyupListener, watch, } from '#imports' interface Props { modelValue?: string | undefined rowIndex?: number disableOptionCreation?: boolean } const { modelValue, disableOptionCreation } = defineProps<Props>() const emit = defineEmits(['update:modelValue']) const column = inject(ColumnInj)! const readOnly = inject(ReadonlyInj)! const isLockedMode = inject(IsLockedInj, ref(false)) const isEditable = inject(EditModeInj, ref(false)) const activeCell = inject(ActiveCellInj, ref(false)) // use both ActiveCellInj or EditModeInj to determine the active state // since active will be false in case of form view const active = computed(() => activeCell.value || isEditable.value) const aselect = ref<typeof AntSelect>() const isOpen = ref(false) const isKanban = inject(IsKanbanInj, ref(false)) const isPublic = inject(IsPublicInj, ref(false)) const isEditColumn = inject(EditColumnInj, ref(false)) const isForm = inject(IsFormInj, ref(false)) const { $api } = useNuxtApp() const searchVal = ref() const { getMeta } = useMetas() const { isUIAllowed } = useRoles() const { isPg, isMysql } = useBase() // a variable to keep newly created option value // temporary until it's add the option to column meta const tempSelectedOptState = ref<string>() const isNewOptionCreateEnabled = computed(() => !isPublic.value && !disableOptionCreation && isUIAllowed('fieldEdit')) const options = computed<(SelectOptionType & { value: string })[]>(() => { if (column?.value.colOptions) { const opts = column.value.colOptions ? // todo: fix colOptions type, options does not exist as a property (column.value.colOptions as any).options.filter((el: SelectOptionType) => el.title !== '') || [] : [] for (const op of opts.filter((el: any) => el.order === null)) { op.title = op.title.replace(/^'/, '').replace(/'$/, '') } return opts.map((o: any) => ({ ...o, value: o.title })) } return [] }) const isOptionMissing = computed(() => { return (options.value ?? []).every((op) => op.title !== searchVal.value) }) const hasEditRoles = computed(() => isUIAllowed('dataEdit')) const editAllowed = computed(() => (hasEditRoles.value || isForm.value) && active.value) const vModel = computed({ get: () => tempSelectedOptState.value ?? modelValue?.trim(), set: (val) => { if (val && isNewOptionCreateEnabled.value && (options.value ?? []).every((op) => op.title !== val)) { tempSelectedOptState.value = val return addIfMissingAndSave() } emit('update:modelValue', val || null) }, }) watch(isOpen, (n, _o) => { if (editAllowed.value) { if (!n) { aselect.value?.$el?.querySelector('input')?.blur() } else { aselect.value?.$el?.querySelector('input')?.focus() } } }) useSelectedCellKeyupListener(activeCell, (e) => { switch (e.key) { case 'Escape': isOpen.value = false break case 'Enter': if (editAllowed.value && active.value && !isOpen.value) { isOpen.value = true } break // skip space bar key press since it's used for expand row case ' ': break default: if (!editAllowed.value) { e.preventDefault() break } // toggle only if char key pressed if (!(e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) && e.key?.length === 1 && !isDrawerOrModalExist()) { e.stopPropagation() isOpen.value = true } break } }) // close dropdown list on escape useSelectedCellKeyupListener(isOpen, (e) => { if (e.key === 'Escape') isOpen.value = false }) async function addIfMissingAndSave() { if (!tempSelectedOptState.value || isPublic.value) return false const newOptValue = tempSelectedOptState.value searchVal.value = '' tempSelectedOptState.value = undefined if (newOptValue && !options.value.some((o) => o.title === newOptValue)) { try { options.value.push({ title: newOptValue, value: newOptValue, color: enumColor.light[(options.value.length + 1) % enumColor.light.length], }) column.value.colOptions = { options: options.value.map(({ value: _, ...rest }) => rest) } const updatedColMeta = { ...column.value } // todo: refactor and avoid repetition if (updatedColMeta.cdf) { // Postgres returns default value wrapped with single quotes & casted with type so we have to get value between single quotes to keep it unified for all databases if (isPg(column.value.source_id)) { updatedColMeta.cdf = updatedColMeta.cdf.substring( updatedColMeta.cdf.indexOf(`'`) + 1, updatedColMeta.cdf.lastIndexOf(`'`), ) } // Mysql escapes single quotes with backslash so we keep quotes but others have to unescaped if (!isMysql(column.value.source_id) && !isPg(column.value.source_id)) { updatedColMeta.cdf = updatedColMeta.cdf.replace(/''/g, "'") } } await $api.dbTableColumn.update( (column.value as { fk_column_id?: string })?.fk_column_id || (column.value?.id as string), updatedColMeta, ) vModel.value = newOptValue await getMeta(column.value.fk_model_id!, true) } catch (e: any) { console.log(e) message.error(await extractSdkResponseErrorMsg(e)) } } } const search = () => { searchVal.value = aselect.value?.$el?.querySelector('.ant-select-selection-search-input')?.value } // prevent propagation of keydown event if select is open const onKeydown = (e: KeyboardEvent) => { if (isOpen.value && active.value) { e.stopPropagation() } if (e.key === 'Enter') { e.stopPropagation() } } const onSelect = () => { isOpen.value = false isEditable.value = false } const cellClickHook = inject(CellClickHookInj, null) const toggleMenu = (e: Event) => { // todo: refactor // check clicked element is clear icon if ( (e.target as HTMLElement)?.classList.contains('ant-select-clear') || (e.target as HTMLElement)?.closest('.ant-select-clear') ) { vModel.value = '' return e.stopPropagation() } if (cellClickHook) return isOpen.value = editAllowed.value && !isOpen.value } const cellClickHookHandler = () => { isOpen.value = editAllowed.value && !isOpen.value } onMounted(() => { cellClickHook?.on(cellClickHookHandler) }) onUnmounted(() => { cellClickHook?.on(cellClickHookHandler) }) const handleClose = (e: MouseEvent) => { if (isOpen.value && aselect.value && !aselect.value.$el.contains(e.target)) { isOpen.value = false } } useEventListener(document, 'click', handleClose, true) const selectedOpt = computed(() => { return options.value.find((o) => o.value === vModel.value) }) </script> <template> <div class="h-full w-full flex items-center nc-single-select" :class="{ 'read-only': readOnly || isLockedMode }" @click="toggleMenu" > <div v-if="!(active || isEditable)"> <a-tag v-if="selectedOpt" class="rounded-tag" :color="selectedOpt.color"> <span :style="{ 'color': tinycolor.isReadable(selectedOpt.color || '#ccc', '#fff', { level: 'AA', size: 'large' }) ? '#fff' : tinycolor.mostReadable(selectedOpt.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '13px', }" :class="{ 'text-sm': isKanban }" > {{ selectedOpt.title }} </span> </a-tag> </div> <a-select v-else ref="aselect" v-model:value="vModel" class="w-full overflow-hidden" :class="{ 'caret-transparent': !hasEditRoles }" :placeholder="isEditColumn ? $t('labels.optional') : ''" :allow-clear="!column.rqd && editAllowed" :bordered="false" :open="isOpen && editAllowed" :disabled="readOnly || !editAllowed || isLockedMode" :show-arrow="hasEditRoles && !(readOnly || isLockedMode) && active && vModel === null" :dropdown-class-name="`nc-dropdown-single-select-cell ${isOpen && active ? 'active' : ''}`" :show-search="isOpen && active" @select="onSelect" @keydown="onKeydown($event)" @search="search" > <a-select-option v-for="op of options" :key="op.title" :value="op.title" :data-testid="`select-option-${column.title}-${rowIndex}`" :class="`nc-select-option-${column.title}-${op.title}`" @click.stop > <a-tag class="rounded-tag" :color="op.color"> <span :style="{ 'color': tinycolor.isReadable(op.color || '#ccc', '#fff', { level: 'AA', size: 'large' }) ? '#fff' : tinycolor.mostReadable(op.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '13px', }" :class="{ 'text-sm': isKanban }" > {{ op.title }} </span> </a-tag> </a-select-option> <a-select-option v-if="searchVal && isOptionMissing && isNewOptionCreateEnabled" :key="searchVal" :value="searchVal"> <div class="flex gap-2 text-gray-500 items-center h-full"> <component :is="iconMap.plusThick" class="min-w-4" /> <div class="text-xs whitespace-normal"> {{ $t('msg.selectOption.createNewOptionNamed') }} <strong>{{ searchVal }}</strong> </div> </div> </a-select-option> </a-select> </div> </template> <style scoped lang="scss"> .rounded-tag { @apply py-0 px-[12px] rounded-[12px]; } :deep(.ant-tag) { @apply "rounded-tag" my-[2px]; } :deep(.ant-select-clear) { opacity: 1; } .nc-single-select:not(.read-only) { :deep(.ant-select-selector), :deep(.ant-select-selector input) { @apply !cursor-pointer; } } :deep(.ant-select-selector) { @apply !px-0; } :deep(.ant-select-selection-search-input) { @apply !text-xs; } :deep(.ant-select-clear > span) { @apply block; } </style>
packages/nc-gui/components/cell/SingleSelect.vue
1
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.059520501643419266, 0.0034955148585140705, 0.00016527017578482628, 0.00017157367256004363, 0.010883516632020473 ]
{ "id": 7, "code_window": [ " </a-select>\n", "</template>\n", "\n", "<style lang=\"scss\">\n", ".nc-select.ant-select {\n", " height: fit-content;\n", " .ant-select-selector {\n", " box-shadow: 0px 5px 3px -2px rgba(0, 0, 0, 0.02), 0px 3px 1px -2px rgba(0, 0, 0, 0.06);\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ ".ant-select-item {\n", " @apply !xs:h-13;\n", "}\n", ".ant-select-item-option-content {\n", " @apply !xs:mt-2.5;\n", "}\n", ".ant-select-item-option-state {\n", " @apply !xs:mt-1.75;\n", "}\n", "\n" ], "file_path": "packages/nc-gui/components/nc/Select.vue", "type": "add", "edit_start_line_idx": 57 }
import path from 'path'; import * as Sentry from '@sentry/node'; import { Logger } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import clear from 'clear'; import * as express from 'express'; import NcToolGui from 'nc-lib-gui'; import { T } from 'nc-help'; import { v4 as uuidv4 } from 'uuid'; import dotenv from 'dotenv'; import { IoAdapter } from '@nestjs/platform-socket.io'; import requestIp from 'request-ip'; import cookieParser from 'cookie-parser'; import type { MetaService } from '~/meta/meta.service'; import type { IEventEmitter } from '~/modules/event-emitter/event-emitter.interface'; import type { Express } from 'express'; // import type * as http from 'http'; import type http from 'http'; import { MetaTable } from '~/utils/globals'; import { AppModule } from '~/app.module'; import { isEE } from '~/utils'; dotenv.config(); export default class Noco { private static _this: Noco; private static ee: boolean; public static readonly env: string = '_noco'; private static _httpServer: http.Server; private static _server: Express; private static logger = new Logger(Noco.name); public static get dashboardUrl(): string { const siteUrl = `http://localhost:${process.env.PORT || 8080}`; return `${siteUrl}${Noco._this?.config?.dashboardPath}`; } public static config: any; public static eventEmitter: IEventEmitter; public readonly router: express.Router; public readonly baseRouter: express.Router; public static _ncMeta: any; public readonly metaMgr: any; public readonly metaMgrv2: any; public env: string; private config: any; private requestContext: any; constructor() { process.env.PORT = process.env.PORT || '8080'; // todo: move // if env variable NC_MINIMAL_DBS is set, then disable base creation with external sources if (process.env.NC_MINIMAL_DBS === 'true') { process.env.NC_CONNECT_TO_EXTERNAL_DB_DISABLED = 'true'; } this.router = express.Router(); this.baseRouter = express.Router(); clear(); /******************* prints : end *******************/ } public getConfig(): any { return this.config; } public getToolDir(): string { return this.getConfig()?.toolDir; } public addToContext(context: any) { this.requestContext = context; } public static get ncMeta(): MetaService { return this._ncMeta; } public get ncMeta(): any { return Noco._ncMeta; } public static getConfig(): any { return Noco.config; } public static isEE(): boolean { return Noco.ee || process.env.NC_CLOUD === 'true'; } public static async loadEEState(): Promise<boolean> { try { return (Noco.ee = isEE); } catch {} return (Noco.ee = false); } static async init(param: any, httpServer: http.Server, server: Express) { const nestApp = await NestFactory.create( AppModule, // new ExpressAdapter(server), ); if (process.env.NC_WORKER_CONTAINER === 'true') { if (!process.env.NC_REDIS_URL) { throw new Error('NC_REDIS_URL is required'); } process.env.NC_DISABLE_TELE = 'true'; nestApp.init(); } else { nestApp.useWebSocketAdapter(new IoAdapter(httpServer)); this._httpServer = nestApp.getHttpAdapter().getInstance(); this._server = server; nestApp.use(requestIp.mw()); nestApp.use(cookieParser()); this.initSentry(nestApp); nestApp.useWebSocketAdapter(new IoAdapter(httpServer)); nestApp.use( express.json({ limit: process.env.NC_REQUEST_BODY_SIZE || '50mb' }), ); await nestApp.init(); const dashboardPath = process.env.NC_DASHBOARD_URL ?? '/dashboard'; server.use(NcToolGui.expressMiddleware(dashboardPath)); server.use(express.static(path.join(__dirname, 'public'))); if (dashboardPath !== '/' && dashboardPath !== '') { server.get('/', (_req, res) => res.redirect(dashboardPath)); } this.initSentryErrorHandler(server); return nestApp.getHttpAdapter().getInstance(); } } public static get httpServer(): http.Server { return Noco._httpServer; } public static get server(): Express { return Noco._server; } public static async initJwt(): Promise<any> { if (this.config?.auth?.jwt) { if (!this.config.auth.jwt.secret) { let secret = ( await Noco._ncMeta.metaGet('', '', MetaTable.STORE, { key: 'nc_auth_jwt_secret', }) )?.value; if (!secret) { await Noco._ncMeta.metaInsert('', '', MetaTable.STORE, { key: 'nc_auth_jwt_secret', value: (secret = uuidv4()), }); } this.config.auth.jwt.secret = secret; } this.config.auth.jwt.options = this.config.auth.jwt.options || {}; if (!this.config.auth.jwt.options?.expiresIn) { this.config.auth.jwt.options.expiresIn = process.env.NC_JWT_EXPIRES_IN ?? '10h'; } } let serverId = ( await Noco._ncMeta.metaGet('', '', MetaTable.STORE, { key: 'nc_server_id', }) )?.value; if (!serverId) { await Noco._ncMeta.metaInsert('', '', MetaTable.STORE, { key: 'nc_server_id', value: (serverId = T.id), }); } process.env.NC_SERVER_UUID = serverId; } private static initSentryErrorHandler(router) { if (process.env.NC_SENTRY_DSN) { router.use(Sentry.Handlers.errorHandler()); } } private static initSentry(router) { if (process.env.NC_SENTRY_DSN) { Sentry.init({ dsn: process.env.NC_SENTRY_DSN }); // The request handler must be the first middleware on the app router.use(Sentry.Handlers.requestHandler()); } } }
packages/nocodb/src/Noco.ts
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00024503187160007656, 0.0001841128832893446, 0.00016403022164013237, 0.0001741737505653873, 0.00002175083864131011 ]
{ "id": 7, "code_window": [ " </a-select>\n", "</template>\n", "\n", "<style lang=\"scss\">\n", ".nc-select.ant-select {\n", " height: fit-content;\n", " .ant-select-selector {\n", " box-shadow: 0px 5px 3px -2px rgba(0, 0, 0, 0.02), 0px 3px 1px -2px rgba(0, 0, 0, 0.06);\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ ".ant-select-item {\n", " @apply !xs:h-13;\n", "}\n", ".ant-select-item-option-content {\n", " @apply !xs:mt-2.5;\n", "}\n", ".ant-select-item-option-state {\n", " @apply !xs:mt-1.75;\n", "}\n", "\n" ], "file_path": "packages/nc-gui/components/nc/Select.vue", "type": "add", "edit_start_line_idx": 57 }
import { createI18n } from 'vue-i18n' import { isClient } from '@vueuse/core' import { LanguageAlias, applyLanguageDirection, defineNuxtPlugin, isEeUI, isRtlLang, nextTick } from '#imports' import type { Language, NocoI18n } from '#imports' let globalI18n: NocoI18n export const createI18nPlugin = async (): Promise<NocoI18n> => createI18n({ locale: 'en', // Set the initial locale fallbackLocale: 'en', // Set the fallback locale in case the current locale can't be found legacy: false, // disable legacy API (we use the composition API and inject utilities) globalInjection: true, // enable global injection, so all utilities are injected into all components }) export const getI18n = () => globalI18n export async function setI18nLanguage(locale: keyof typeof Language, i18n = globalI18n) { if (!i18n.global.availableLocales.includes(locale)) { await loadLocaleMessages(locale) } i18n.global.locale.value = locale if (isClient) applyLanguageDirection(isRtlLang(locale) ? 'rtl' : 'ltr') } export async function loadLocaleMessages( locale: keyof typeof Language | keyof typeof LanguageAlias, i18n: NocoI18n = globalI18n, ) { if (Object.keys(LanguageAlias).includes(locale)) locale = LanguageAlias[locale as keyof typeof LanguageAlias] // load locale messages with dynamic import const messages = await import(`../lang/${locale}.json`) // set locale and locale message i18n.global.setLocaleMessage(locale, messages.default) return nextTick() } const i18nPlugin = async (nuxtApp) => { globalI18n = await createI18nPlugin() nuxtApp.vueApp.i18n = globalI18n nuxtApp.vueApp.use(globalI18n) } export default defineNuxtPlugin(async function (nuxtApp) { if (!isEeUI) return await i18nPlugin(nuxtApp) }) export { i18nPlugin }
packages/nc-gui/plugins/a.i18n.ts
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00017334584845229983, 0.00016768340719863772, 0.0001648568722885102, 0.0001670800120336935, 0.000002736984924922581 ]
{ "id": 7, "code_window": [ " </a-select>\n", "</template>\n", "\n", "<style lang=\"scss\">\n", ".nc-select.ant-select {\n", " height: fit-content;\n", " .ant-select-selector {\n", " box-shadow: 0px 5px 3px -2px rgba(0, 0, 0, 0.02), 0px 3px 1px -2px rgba(0, 0, 0, 0.06);\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ ".ant-select-item {\n", " @apply !xs:h-13;\n", "}\n", ".ant-select-item-option-content {\n", " @apply !xs:mt-2.5;\n", "}\n", ".ant-select-item-option-state {\n", " @apply !xs:mt-1.75;\n", "}\n", "\n" ], "file_path": "packages/nc-gui/components/nc/Select.vue", "type": "add", "edit_start_line_idx": 57 }
import path from 'path'; import { Body, Controller, Get, HttpCode, Param, Post, Request, Response, UploadedFiles, UseGuards, UseInterceptors, } from '@nestjs/common'; import hash from 'object-hash'; import moment from 'moment'; import { AnyFilesInterceptor } from '@nestjs/platform-express'; import { GlobalGuard } from '~/guards/global/global.guard'; import { AttachmentsService } from '~/services/attachments.service'; import { PresignedUrl } from '~/models'; import { UploadAllowedInterceptor } from '~/interceptors/is-upload-allowed/is-upload-allowed.interceptor'; import { MetaApiLimiterGuard } from '~/guards/meta-api-limiter.guard'; @Controller() export class AttachmentsSecureController { constructor(private readonly attachmentsService: AttachmentsService) {} @UseGuards(MetaApiLimiterGuard, GlobalGuard) @Post(['/api/v1/db/storage/upload', '/api/v2/storage/upload']) @HttpCode(200) @UseInterceptors(UploadAllowedInterceptor, AnyFilesInterceptor()) async upload(@UploadedFiles() files: Array<any>, @Request() req) { const path = `${moment().format('YYYY/MM/DD')}/${hash(req.user.id)}`; const attachments = await this.attachmentsService.upload({ files: files, path: path, }); return attachments; } @Post(['/api/v1/db/storage/upload-by-url', '/api/v2/storage/upload-by-url']) @HttpCode(200) @UseInterceptors(UploadAllowedInterceptor) @UseGuards(MetaApiLimiterGuard, GlobalGuard) async uploadViaURL(@Body() body: any, @Request() req) { const path = `${moment().format('YYYY/MM/DD')}/${hash(req.user.id)}`; const attachments = await this.attachmentsService.uploadViaURL({ urls: body, path, }); return attachments; } @Get('/dltemp/:param(*)') async fileReadv3(@Param('param') param: string, @Response() res) { try { const fpath = await PresignedUrl.getPath(`dltemp/${param}`); const { img } = await this.attachmentsService.fileRead({ path: path.join('nc', 'uploads', fpath), }); res.sendFile(img); } catch (e) { res.status(404).send('Not found'); } } }
packages/nocodb/src/controllers/attachments-secure.controller.ts
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.0001758479920681566, 0.00017321109771728516, 0.00016776035772636533, 0.00017435321933589876, 0.0000024726887204451486 ]
{ "id": 8, "code_window": [ " </template>\n", " <template v-else>\n", " <SmartsheetDivDataCell\n", " v-if=\"col.title\"\n", " :ref=\"i ? null : (el: any) => (cellWrapperEl = el)\"\n", " class=\"!bg-white rounded-lg !w-[20rem] !xs:w-full border-1 border-gray-200 overflow-hidden px-1 min-h-[35px] flex items-center relative\"\n", " >\n", " <LazySmartsheetVirtualCell v-if=\"isVirtualCol(col)\" v-model=\"_row.row[col.title]\" :row=\"_row\" :column=\"col\" />\n", "\n", " <LazySmartsheetCell\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " class=\"!bg-white rounded-lg !w-[20rem] !xs:w-full border-1 border-gray-200 overflow-hidden px-1 sm:min-h-[35px] xs:min-h-13 flex items-center relative\"\n" ], "file_path": "packages/nc-gui/components/smartsheet/expanded-form/index.vue", "type": "replace", "edit_start_line_idx": 618 }
<script lang="ts" setup> import { onUnmounted } from '@vue/runtime-core' import { message } from 'ant-design-vue' import tinycolor from 'tinycolor2' import type { Select as AntSelect } from 'ant-design-vue' import type { SelectOptionType } from 'nocodb-sdk' import { ActiveCellInj, CellClickHookInj, ColumnInj, EditColumnInj, EditModeInj, IsFormInj, IsKanbanInj, ReadonlyInj, computed, enumColor, extractSdkResponseErrorMsg, iconMap, inject, isDrawerOrModalExist, ref, useBase, useEventListener, useRoles, useSelectedCellKeyupListener, watch, } from '#imports' interface Props { modelValue?: string | undefined rowIndex?: number disableOptionCreation?: boolean } const { modelValue, disableOptionCreation } = defineProps<Props>() const emit = defineEmits(['update:modelValue']) const column = inject(ColumnInj)! const readOnly = inject(ReadonlyInj)! const isLockedMode = inject(IsLockedInj, ref(false)) const isEditable = inject(EditModeInj, ref(false)) const activeCell = inject(ActiveCellInj, ref(false)) // use both ActiveCellInj or EditModeInj to determine the active state // since active will be false in case of form view const active = computed(() => activeCell.value || isEditable.value) const aselect = ref<typeof AntSelect>() const isOpen = ref(false) const isKanban = inject(IsKanbanInj, ref(false)) const isPublic = inject(IsPublicInj, ref(false)) const isEditColumn = inject(EditColumnInj, ref(false)) const isForm = inject(IsFormInj, ref(false)) const { $api } = useNuxtApp() const searchVal = ref() const { getMeta } = useMetas() const { isUIAllowed } = useRoles() const { isPg, isMysql } = useBase() // a variable to keep newly created option value // temporary until it's add the option to column meta const tempSelectedOptState = ref<string>() const isNewOptionCreateEnabled = computed(() => !isPublic.value && !disableOptionCreation && isUIAllowed('fieldEdit')) const options = computed<(SelectOptionType & { value: string })[]>(() => { if (column?.value.colOptions) { const opts = column.value.colOptions ? // todo: fix colOptions type, options does not exist as a property (column.value.colOptions as any).options.filter((el: SelectOptionType) => el.title !== '') || [] : [] for (const op of opts.filter((el: any) => el.order === null)) { op.title = op.title.replace(/^'/, '').replace(/'$/, '') } return opts.map((o: any) => ({ ...o, value: o.title })) } return [] }) const isOptionMissing = computed(() => { return (options.value ?? []).every((op) => op.title !== searchVal.value) }) const hasEditRoles = computed(() => isUIAllowed('dataEdit')) const editAllowed = computed(() => (hasEditRoles.value || isForm.value) && active.value) const vModel = computed({ get: () => tempSelectedOptState.value ?? modelValue?.trim(), set: (val) => { if (val && isNewOptionCreateEnabled.value && (options.value ?? []).every((op) => op.title !== val)) { tempSelectedOptState.value = val return addIfMissingAndSave() } emit('update:modelValue', val || null) }, }) watch(isOpen, (n, _o) => { if (editAllowed.value) { if (!n) { aselect.value?.$el?.querySelector('input')?.blur() } else { aselect.value?.$el?.querySelector('input')?.focus() } } }) useSelectedCellKeyupListener(activeCell, (e) => { switch (e.key) { case 'Escape': isOpen.value = false break case 'Enter': if (editAllowed.value && active.value && !isOpen.value) { isOpen.value = true } break // skip space bar key press since it's used for expand row case ' ': break default: if (!editAllowed.value) { e.preventDefault() break } // toggle only if char key pressed if (!(e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) && e.key?.length === 1 && !isDrawerOrModalExist()) { e.stopPropagation() isOpen.value = true } break } }) // close dropdown list on escape useSelectedCellKeyupListener(isOpen, (e) => { if (e.key === 'Escape') isOpen.value = false }) async function addIfMissingAndSave() { if (!tempSelectedOptState.value || isPublic.value) return false const newOptValue = tempSelectedOptState.value searchVal.value = '' tempSelectedOptState.value = undefined if (newOptValue && !options.value.some((o) => o.title === newOptValue)) { try { options.value.push({ title: newOptValue, value: newOptValue, color: enumColor.light[(options.value.length + 1) % enumColor.light.length], }) column.value.colOptions = { options: options.value.map(({ value: _, ...rest }) => rest) } const updatedColMeta = { ...column.value } // todo: refactor and avoid repetition if (updatedColMeta.cdf) { // Postgres returns default value wrapped with single quotes & casted with type so we have to get value between single quotes to keep it unified for all databases if (isPg(column.value.source_id)) { updatedColMeta.cdf = updatedColMeta.cdf.substring( updatedColMeta.cdf.indexOf(`'`) + 1, updatedColMeta.cdf.lastIndexOf(`'`), ) } // Mysql escapes single quotes with backslash so we keep quotes but others have to unescaped if (!isMysql(column.value.source_id) && !isPg(column.value.source_id)) { updatedColMeta.cdf = updatedColMeta.cdf.replace(/''/g, "'") } } await $api.dbTableColumn.update( (column.value as { fk_column_id?: string })?.fk_column_id || (column.value?.id as string), updatedColMeta, ) vModel.value = newOptValue await getMeta(column.value.fk_model_id!, true) } catch (e: any) { console.log(e) message.error(await extractSdkResponseErrorMsg(e)) } } } const search = () => { searchVal.value = aselect.value?.$el?.querySelector('.ant-select-selection-search-input')?.value } // prevent propagation of keydown event if select is open const onKeydown = (e: KeyboardEvent) => { if (isOpen.value && active.value) { e.stopPropagation() } if (e.key === 'Enter') { e.stopPropagation() } } const onSelect = () => { isOpen.value = false isEditable.value = false } const cellClickHook = inject(CellClickHookInj, null) const toggleMenu = (e: Event) => { // todo: refactor // check clicked element is clear icon if ( (e.target as HTMLElement)?.classList.contains('ant-select-clear') || (e.target as HTMLElement)?.closest('.ant-select-clear') ) { vModel.value = '' return e.stopPropagation() } if (cellClickHook) return isOpen.value = editAllowed.value && !isOpen.value } const cellClickHookHandler = () => { isOpen.value = editAllowed.value && !isOpen.value } onMounted(() => { cellClickHook?.on(cellClickHookHandler) }) onUnmounted(() => { cellClickHook?.on(cellClickHookHandler) }) const handleClose = (e: MouseEvent) => { if (isOpen.value && aselect.value && !aselect.value.$el.contains(e.target)) { isOpen.value = false } } useEventListener(document, 'click', handleClose, true) const selectedOpt = computed(() => { return options.value.find((o) => o.value === vModel.value) }) </script> <template> <div class="h-full w-full flex items-center nc-single-select" :class="{ 'read-only': readOnly || isLockedMode }" @click="toggleMenu" > <div v-if="!(active || isEditable)"> <a-tag v-if="selectedOpt" class="rounded-tag" :color="selectedOpt.color"> <span :style="{ 'color': tinycolor.isReadable(selectedOpt.color || '#ccc', '#fff', { level: 'AA', size: 'large' }) ? '#fff' : tinycolor.mostReadable(selectedOpt.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '13px', }" :class="{ 'text-sm': isKanban }" > {{ selectedOpt.title }} </span> </a-tag> </div> <a-select v-else ref="aselect" v-model:value="vModel" class="w-full overflow-hidden" :class="{ 'caret-transparent': !hasEditRoles }" :placeholder="isEditColumn ? $t('labels.optional') : ''" :allow-clear="!column.rqd && editAllowed" :bordered="false" :open="isOpen && editAllowed" :disabled="readOnly || !editAllowed || isLockedMode" :show-arrow="hasEditRoles && !(readOnly || isLockedMode) && active && vModel === null" :dropdown-class-name="`nc-dropdown-single-select-cell ${isOpen && active ? 'active' : ''}`" :show-search="isOpen && active" @select="onSelect" @keydown="onKeydown($event)" @search="search" > <a-select-option v-for="op of options" :key="op.title" :value="op.title" :data-testid="`select-option-${column.title}-${rowIndex}`" :class="`nc-select-option-${column.title}-${op.title}`" @click.stop > <a-tag class="rounded-tag" :color="op.color"> <span :style="{ 'color': tinycolor.isReadable(op.color || '#ccc', '#fff', { level: 'AA', size: 'large' }) ? '#fff' : tinycolor.mostReadable(op.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '13px', }" :class="{ 'text-sm': isKanban }" > {{ op.title }} </span> </a-tag> </a-select-option> <a-select-option v-if="searchVal && isOptionMissing && isNewOptionCreateEnabled" :key="searchVal" :value="searchVal"> <div class="flex gap-2 text-gray-500 items-center h-full"> <component :is="iconMap.plusThick" class="min-w-4" /> <div class="text-xs whitespace-normal"> {{ $t('msg.selectOption.createNewOptionNamed') }} <strong>{{ searchVal }}</strong> </div> </div> </a-select-option> </a-select> </div> </template> <style scoped lang="scss"> .rounded-tag { @apply py-0 px-[12px] rounded-[12px]; } :deep(.ant-tag) { @apply "rounded-tag" my-[2px]; } :deep(.ant-select-clear) { opacity: 1; } .nc-single-select:not(.read-only) { :deep(.ant-select-selector), :deep(.ant-select-selector input) { @apply !cursor-pointer; } } :deep(.ant-select-selector) { @apply !px-0; } :deep(.ant-select-selection-search-input) { @apply !text-xs; } :deep(.ant-select-clear > span) { @apply block; } </style>
packages/nc-gui/components/cell/SingleSelect.vue
1
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.0008860665839165449, 0.00021557665604632348, 0.00016243656864389777, 0.0001675327366683632, 0.0001532697060611099 ]
{ "id": 8, "code_window": [ " </template>\n", " <template v-else>\n", " <SmartsheetDivDataCell\n", " v-if=\"col.title\"\n", " :ref=\"i ? null : (el: any) => (cellWrapperEl = el)\"\n", " class=\"!bg-white rounded-lg !w-[20rem] !xs:w-full border-1 border-gray-200 overflow-hidden px-1 min-h-[35px] flex items-center relative\"\n", " >\n", " <LazySmartsheetVirtualCell v-if=\"isVirtualCol(col)\" v-model=\"_row.row[col.title]\" :row=\"_row\" :column=\"col\" />\n", "\n", " <LazySmartsheetCell\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " class=\"!bg-white rounded-lg !w-[20rem] !xs:w-full border-1 border-gray-200 overflow-hidden px-1 sm:min-h-[35px] xs:min-h-13 flex items-center relative\"\n" ], "file_path": "packages/nc-gui/components/smartsheet/expanded-form/index.vue", "type": "replace", "edit_start_line_idx": 618 }
/* Manrope */ @font-face { font-display: swap; /* Check https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display for other options. */ font-family: 'Manrope'; src: url('./manrope/Manrope-VariableFont_wght.ttf') format('truetype') } /* // href: 'https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20,200,0,-25', */ @font-face { font-family: 'Material Symbols'; font-style: normal; font-weight: 300; src: url(./material.woff2) format('woff2'); } .material-symbols { font-family: 'Material Symbols'; font-weight: normal; font-style: normal; line-height: 1; letter-spacing: normal; text-transform: none; display: inline-block; white-space: nowrap; word-wrap: normal; direction: ltr; font-weight: 300; -webkit-font-feature-settings: 'liga'; -webkit-font-smoothing: antialiased; font-size: 1rem; user-select: none; } .nc-fonts-not-loaded { .material-symbols { opacity: 0; width: 0 !important; } }
packages/nc-gui/assets/style/fonts.css
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.0001746039342833683, 0.000171269552083686, 0.00016744903405196965, 0.00017330799892079085, 0.0000030912049169273814 ]
{ "id": 8, "code_window": [ " </template>\n", " <template v-else>\n", " <SmartsheetDivDataCell\n", " v-if=\"col.title\"\n", " :ref=\"i ? null : (el: any) => (cellWrapperEl = el)\"\n", " class=\"!bg-white rounded-lg !w-[20rem] !xs:w-full border-1 border-gray-200 overflow-hidden px-1 min-h-[35px] flex items-center relative\"\n", " >\n", " <LazySmartsheetVirtualCell v-if=\"isVirtualCol(col)\" v-model=\"_row.row[col.title]\" :row=\"_row\" :column=\"col\" />\n", "\n", " <LazySmartsheetCell\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " class=\"!bg-white rounded-lg !w-[20rem] !xs:w-full border-1 border-gray-200 overflow-hidden px-1 sm:min-h-[35px] xs:min-h-13 flex items-center relative\"\n" ], "file_path": "packages/nc-gui/components/smartsheet/expanded-form/index.vue", "type": "replace", "edit_start_line_idx": 618 }
import { PluginCategory } from 'nocodb-sdk'; import { NcError } from './catchError'; import type { IEmailAdapter, IStorageAdapterV2, IWebhookNotificationAdapter, // XcEmailPlugin, // XcPlugin, // XcStoragePlugin, // XcWebhookNotificationPlugin } from 'nc-plugin'; import BackblazePluginConfig from '~/plugins/backblaze'; import DiscordPluginConfig from '~/plugins/discord'; import GcsPluginConfig from '~/plugins/gcs'; import LinodePluginConfig from '~/plugins/linode'; import MattermostPluginConfig from '~/plugins/mattermost'; import MinioPluginConfig from '~/plugins/mino'; import OvhCloudPluginConfig from '~/plugins/ovhCloud'; import S3PluginConfig from '~/plugins/s3'; import ScalewayPluginConfig from '~/plugins/scaleway'; import SlackPluginConfig from '~/plugins/slack'; import SMTPPluginConfig from '~/plugins/smtp'; import MailerSendConfig from '~/plugins/mailerSend'; import SpacesPluginConfig from '~/plugins/spaces'; import TeamsPluginConfig from '~/plugins/teams'; import TwilioPluginConfig from '~/plugins/twilio'; import TwilioWhatsappPluginConfig from '~/plugins/twilioWhatsapp'; import UpcloudPluginConfig from '~/plugins/upcloud'; import VultrPluginConfig from '~/plugins/vultr'; import SESPluginConfig from '~/plugins/ses'; import Noco from '~/Noco'; import Local from '~/plugins/storage/Local'; import { MetaTable } from '~/utils/globals'; import Plugin from '~/models/Plugin'; const defaultPlugins = [ SlackPluginConfig, TeamsPluginConfig, DiscordPluginConfig, TwilioWhatsappPluginConfig, TwilioPluginConfig, S3PluginConfig, MinioPluginConfig, GcsPluginConfig, MattermostPluginConfig, SpacesPluginConfig, BackblazePluginConfig, VultrPluginConfig, OvhCloudPluginConfig, LinodePluginConfig, UpcloudPluginConfig, SMTPPluginConfig, MailerSendConfig, ScalewayPluginConfig, SESPluginConfig, ]; class NcPluginMgrv2 { /* active plugins */ // constructor(app: Noco, ncMeta: NcMetaIO) { // this.app = app; // this.ncMeta = ncMeta; // this.activePlugins = []; // } public static async init(ncMeta = Noco.ncMeta): Promise<void> { /* Populate rows into nc_plugins table if not present */ for (const plugin of defaultPlugins) { const pluginConfig = await ncMeta.metaGet(null, null, MetaTable.PLUGIN, { title: plugin.title, }); if (!pluginConfig) { await ncMeta.metaInsert2(null, null, MetaTable.PLUGIN, { title: plugin.title, version: plugin.version, logo: plugin.logo, description: plugin.description, tags: plugin.tags, category: plugin.category, input_schema: JSON.stringify(plugin.inputs), }); } else if (pluginConfig.version !== plugin.version) { await ncMeta.metaUpdate( null, null, MetaTable.PLUGIN, { title: plugin.title, version: plugin.version, logo: plugin.logo, description: plugin.description, tags: plugin.tags, category: plugin.category, input_schema: JSON.stringify(plugin.inputs), }, pluginConfig.id, ); } } await this.initPluginsFromEnv(); } private static async initPluginsFromEnv() { /* * NC_S3_BUCKET_NAME * NC_S3_REGION * NC_S3_ACCESS_KEY * NC_S3_ACCESS_SECRET * */ if ( process.env.NC_S3_BUCKET_NAME && process.env.NC_S3_REGION && process.env.NC_S3_ACCESS_KEY && process.env.NC_S3_ACCESS_SECRET ) { const s3Plugin = await Plugin.getPluginByTitle(S3PluginConfig.title); await Plugin.update(s3Plugin.id, { active: true, input: JSON.stringify({ bucket: process.env.NC_S3_BUCKET_NAME, region: process.env.NC_S3_REGION, access_key: process.env.NC_S3_ACCESS_KEY, access_secret: process.env.NC_S3_ACCESS_SECRET, }), }); } if ( process.env.NC_SMTP_FROM && process.env.NC_SMTP_HOST && process.env.NC_SMTP_PORT ) { const smtpPlugin = await Plugin.getPluginByTitle(SMTPPluginConfig.title); await Plugin.update(smtpPlugin.id, { active: true, input: JSON.stringify({ from: process.env.NC_SMTP_FROM, host: process.env.NC_SMTP_HOST, port: process.env.NC_SMTP_PORT, username: process.env.NC_SMTP_USERNAME, password: process.env.NC_SMTP_PASSWORD, secure: process.env.NC_SMTP_SECURE, ignoreTLS: process.env.NC_SMTP_IGNORE_TLS, }), }); } } public static async storageAdapter( ncMeta = Noco.ncMeta, ): Promise<IStorageAdapterV2> { const pluginData = await ncMeta.metaGet2(null, null, MetaTable.PLUGIN, { category: PluginCategory.STORAGE, active: true, }); if (!pluginData) return new Local(); const pluginConfig = defaultPlugins.find( (c) => c.title === pluginData.title && c.category === PluginCategory.STORAGE, ); const plugin = new pluginConfig.builder(ncMeta, pluginData); if (pluginData?.input) { pluginData.input = JSON.parse(pluginData.input); } await plugin.init(pluginData?.input); return plugin.getAdapter(); } public static async emailAdapter( isUserInvite = true, ncMeta = Noco.ncMeta, ): Promise<IEmailAdapter> { const pluginData = await ncMeta.metaGet2(null, null, MetaTable.PLUGIN, { category: PluginCategory.EMAIL, active: true, }); if (!pluginData) { // return null to show the invite link in UI if (isUserInvite) return null; // for webhooks, throw the error throw new Error('Plugin not configured / active'); } const pluginConfig = defaultPlugins.find( (c) => c.title === pluginData.title && c.category === PluginCategory.EMAIL, ); const plugin = new pluginConfig.builder(ncMeta, pluginData); if (pluginData?.input) { pluginData.input = JSON.parse(pluginData.input); } await plugin.init(pluginData?.input); return plugin.getAdapter(); } public static async webhookNotificationAdapters( title: string, ncMeta = Noco.ncMeta, ): Promise<IWebhookNotificationAdapter> { const pluginData = await ncMeta.metaGet2(null, null, MetaTable.PLUGIN, { title, active: true, }); if (!pluginData) throw new Error('Plugin not configured / active'); const pluginConfig = defaultPlugins.find( (c) => c.title === pluginData.title, ); const plugin = new pluginConfig.builder(ncMeta, pluginData); if (pluginData?.input) { pluginData.input = JSON.parse(pluginData.input); } await plugin.init(pluginData?.input); return plugin.getAdapter() as IWebhookNotificationAdapter; // return this.activePlugins?.reduce((obj, plugin) => { // if (plugin instanceof XcWebhookNotificationPlugin) { // obj[ // plugin?.config?.title // ] = (plugin as XcWebhookNotificationPlugin)?.getAdapter(); // } // return obj; // }, {}); } public static async test(args): Promise<boolean> { args.input = typeof args?.input === 'string' ? JSON.parse(args?.input) : args?.input; switch (args.category) { case 'Storage': { const plugin = defaultPlugins.find( (pluginConfig) => pluginConfig?.title === args.title, ); const tempPlugin = new plugin.builder(Noco.ncMeta, plugin); await tempPlugin.init(args?.input); if (!tempPlugin?.getAdapter()?.test) NcError.notImplemented('Plugin test is not implemented'); return tempPlugin?.getAdapter()?.test?.(); } break; case 'Email': { const plugin = defaultPlugins.find( (pluginConfig) => pluginConfig?.title === args.title, ); const tempPlugin = new plugin.builder(Noco.ncMeta, plugin); await tempPlugin.init(args?.input); if (!tempPlugin?.getAdapter()?.test) NcError.notImplemented('Plugin test is not implemented'); return tempPlugin?.getAdapter()?.test?.(); } break; default: { const plugin = defaultPlugins.find( (pluginConfig) => pluginConfig?.title === args.title, ); const tempPlugin = new plugin.builder(Noco.ncMeta, plugin); await tempPlugin.init(args?.input); if (!tempPlugin?.getAdapter()?.test) NcError.notImplemented('Plugin test is not implemented'); return tempPlugin?.getAdapter()?.test?.(); } } } } export default NcPluginMgrv2;
packages/nocodb/src/helpers/NcPluginMgrv2.ts
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00019126910774502903, 0.0001692200603429228, 0.0001620566181372851, 0.00016803090693429112, 0.0000060728139033017214 ]
{ "id": 8, "code_window": [ " </template>\n", " <template v-else>\n", " <SmartsheetDivDataCell\n", " v-if=\"col.title\"\n", " :ref=\"i ? null : (el: any) => (cellWrapperEl = el)\"\n", " class=\"!bg-white rounded-lg !w-[20rem] !xs:w-full border-1 border-gray-200 overflow-hidden px-1 min-h-[35px] flex items-center relative\"\n", " >\n", " <LazySmartsheetVirtualCell v-if=\"isVirtualCol(col)\" v-model=\"_row.row[col.title]\" :row=\"_row\" :column=\"col\" />\n", "\n", " <LazySmartsheetCell\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " class=\"!bg-white rounded-lg !w-[20rem] !xs:w-full border-1 border-gray-200 overflow-hidden px-1 sm:min-h-[35px] xs:min-h-13 flex items-center relative\"\n" ], "file_path": "packages/nc-gui/components/smartsheet/expanded-form/index.vue", "type": "replace", "edit_start_line_idx": 618 }
DB_USER=postgres DB_PASSWORD=password DB_PORT=5432 DB_HOST=localhost DB_CLIENT=pg
packages/nocodb/tests/unit/.pg.env
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00016126569244079292, 0.00016126569244079292, 0.00016126569244079292, 0.00016126569244079292, 0 ]
{ "id": 9, "code_window": [ " <LazySmartsheetDivDataCell\n", " v-if=\"col.title\"\n", " :ref=\"i ? null : (el: any) => (cellWrapperEl = el)\"\n", " class=\"!bg-white rounded-lg !w-[20rem] border-1 overflow-hidden border-gray-200 px-1 min-h-[35px] flex items-center relative\"\n", " >\n", " <LazySmartsheetVirtualCell\n", " v-if=\"isVirtualCol(col)\"\n", " v-model=\"_row.row[col.title]\"\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " class=\"!bg-white rounded-lg !w-[20rem] border-1 overflow-hidden border-gray-200 px-1 sm:min-h-[35px] xs:min-h-13 flex items-center relative\"\n" ], "file_path": "packages/nc-gui/components/smartsheet/expanded-form/index.vue", "type": "replace", "edit_start_line_idx": 676 }
<script setup lang="ts"> import type { TableType, ViewType } from 'nocodb-sdk' import { ViewTypes, isLinksOrLTAR, isSystemColumn, isVirtualCol } from 'nocodb-sdk' import type { Ref } from 'vue' import MdiChevronDown from '~icons/mdi/chevron-down' import { CellClickHookInj, FieldsInj, IsExpandedFormOpenInj, IsKanbanInj, IsPublicInj, MetaInj, ReloadRowDataHookInj, computedInject, createEventHook, iconMap, inject, message, provide, ref, toRef, useActiveKeyupListener, useProvideExpandedFormStore, useProvideSmartsheetStore, useRoles, useRouter, useVModel, watch, } from '#imports' interface Props { modelValue?: boolean state?: Record<string, any> | null meta: TableType loadRow?: boolean useMetaFields?: boolean row?: Row rowId?: string view?: ViewType showNextPrevIcons?: boolean firstRow?: boolean lastRow?: boolean } const props = defineProps<Props>() const emits = defineEmits(['update:modelValue', 'cancel', 'next', 'prev']) const { activeView } = storeToRefs(useViewsStore()) const key = ref(0) const wrapper = ref() const { dashboardUrl } = useDashboard() const { copy } = useClipboard() const { isMobileMode } = useGlobal() const { t } = useI18n() const rowId = toRef(props, 'rowId') const row = toRef(props, 'row') const state = toRef(props, 'state') const meta = toRef(props, 'meta') const islastRow = toRef(props, 'lastRow') const isFirstRow = toRef(props, 'firstRow') const route = useRoute() const router = useRouter() const isPublic = inject(IsPublicInj, ref(false)) // to check if a expanded form which is not yet saved exist or not const isUnsavedFormExist = ref(false) const isRecordLinkCopied = ref(false) const { isUIAllowed } = useRoles() const reloadTrigger = inject(ReloadRowDataHookInj, createEventHook()) const { addOrEditStackRow } = useKanbanViewStoreOrThrow() // override cell click hook to avoid unexpected behavior at form fields provide(CellClickHookInj, undefined) const fields = computedInject(FieldsInj, (_fields) => { if (props.useMetaFields) { return (meta.value.columns ?? []).filter((col) => !isSystemColumn(col)) } return _fields?.value ?? [] }) const hiddenFields = computed(() => { return (meta.value.columns ?? []).filter((col) => !fields.value?.includes(col)).filter((col) => !isSystemColumn(col)) }) const showHiddenFields = ref(false) const toggleHiddenFields = () => { showHiddenFields.value = !showHiddenFields.value } const isKanban = inject(IsKanbanInj, ref(false)) provide(MetaInj, meta) const isLoading = ref(true) const { commentsDrawer, changedColumns, deleteRowById, displayValue, state: rowState, isNew, loadRow: _loadRow, primaryKey, saveRowAndStay, row: _row, syncLTARRefs, save: _save, loadCommentsAndLogs, clearColumns, } = useProvideExpandedFormStore(meta, row) const duplicatingRowInProgress = ref(false) useProvideSmartsheetStore(ref({}) as Ref<ViewType>, meta) watch( state, () => { if (state.value) { rowState.value = state.value } else { rowState.value = {} } }, { immediate: true }, ) const isExpanded = useVModel(props, 'modelValue', emits, { defaultValue: false, }) const onClose = () => { if (changedColumns.value.size > 0) { isCloseModalOpen.value = true } else { if (_row.value?.rowMeta?.new) emits('cancel') isExpanded.value = false } } const onDuplicateRow = () => { duplicatingRowInProgress.value = true isUnsavedFormExist.value = true const oldRow = { ..._row.value.row } delete oldRow.ncRecordId const newRow = Object.assign( {}, { row: oldRow, oldRow: {}, rowMeta: { new: true }, }, ) setTimeout(async () => { _row.value = newRow duplicatingRowInProgress.value = false message.success(t('msg.success.rowDuplicatedWithoutSavedYet')) }, 500) } const save = async () => { if (isNew.value) { const data = await _save(rowState.value) await syncLTARRefs(data) reloadTrigger?.trigger() } else { let kanbanClbk if (activeView.value?.type === ViewTypes.KANBAN) { kanbanClbk = (row: any, isNewRow: boolean) => { addOrEditStackRow(row, isNewRow) } } await _save(undefined, undefined, { kanbanClbk, }) reloadTrigger?.trigger() } isUnsavedFormExist.value = false } const isPreventChangeModalOpen = ref(false) const isCloseModalOpen = ref(false) const discardPreventModal = () => { // when user click on next or previous button if (isPreventChangeModalOpen.value) { emits('next') if (_row.value?.rowMeta?.new) emits('cancel') isPreventChangeModalOpen.value = false } // when user click on close button if (isCloseModalOpen.value) { isCloseModalOpen.value = false if (_row.value?.rowMeta?.new) emits('cancel') isExpanded.value = false } // clearing all new modifed change on close clearColumns() } const onNext = async () => { if (changedColumns.value.size > 0) { isPreventChangeModalOpen.value = true return } emits('next') } const copyRecordUrl = async () => { await copy( encodeURI( `${dashboardUrl?.value}#/${route.params.typeOrId}/${route.params.baseId}/${meta.value?.id}${ props.view ? `/${props.view.title}` : '' }?rowId=${primaryKey.value}`, ), ) isRecordLinkCopied.value = true } const saveChanges = async () => { if (isPreventChangeModalOpen.value) { isUnsavedFormExist.value = false await save() emits('next') isPreventChangeModalOpen.value = false } if (isCloseModalOpen.value) { isCloseModalOpen.value = false await save() isExpanded.value = false } } const reloadParentRowHook = inject(ReloadRowDataHookInj, createEventHook()) // override reload trigger and use it to reload grid and the form itself const reloadHook = createEventHook() reloadHook.on(() => { reloadParentRowHook?.trigger(false) if (isNew.value) return _loadRow() }) provide(ReloadRowDataHookInj, reloadHook) if (isKanban.value) { // adding column titles to changedColumns if they are preset for (const [k, v] of Object.entries(_row.value.row)) { if (v) { changedColumns.value.add(k) } } } provide(IsExpandedFormOpenInj, isExpanded) const cellWrapperEl = ref() onMounted(async () => { isRecordLinkCopied.value = false isLoading.value = true if (props.loadRow) { await _loadRow() await loadCommentsAndLogs() } if (props.rowId) { try { await _loadRow(props.rowId) await loadCommentsAndLogs() } catch (e: any) { if (e.response?.status === 404) { // todo: i18n message.error('Record not found') router.replace({ query: {} }) } else throw e } } isLoading.value = false setTimeout(() => { cellWrapperEl.value?.$el?.querySelector('input,select,textarea')?.focus() }, 300) }) const addNewRow = () => { setTimeout(async () => { _row.value = { row: {}, oldRow: {}, rowMeta: { new: true }, } rowState.value = {} key.value++ isExpanded.value = true }, 500) } // attach keyboard listeners to switch between rows // using alt + left/right arrow keys useActiveKeyupListener( isExpanded, async (e: KeyboardEvent) => { if (!e.altKey) return if (e.key === 'ArrowLeft') { e.stopPropagation() emits('prev') } else if (e.key === 'ArrowRight') { e.stopPropagation() onNext() } // on alt + s save record else if (e.code === 'KeyS') { // remove focus from the active input if any ;(document.activeElement as HTMLElement)?.blur() e.stopPropagation() if (isNew.value) { const data = await _save(rowState.value) await syncLTARRefs(data) reloadHook?.trigger(null) } else { await save() reloadHook?.trigger(null) } if (!saveRowAndStay.value) { onClose() } // on alt + n create new record } else if (e.code === 'KeyN') { // remove focus from the active input if any to avoid unwanted input ;(document.activeElement as HTMLInputElement)?.blur?.() if (changedColumns.value.size > 0) { await Modal.confirm({ title: 'Do you want to save the changes?', okText: 'Save', cancelText: 'Discard', onOk: async () => { await save() reloadHook?.trigger(null) addNewRow() }, onCancel: () => { addNewRow() }, }) } else if (isNew.value) { await Modal.confirm({ title: 'Do you want to save the record?', okText: 'Save', cancelText: 'Discard', onOk: async () => { const data = await _save(rowState.value) await syncLTARRefs(data) reloadHook?.trigger(null) addNewRow() }, onCancel: () => { addNewRow() }, }) } else { addNewRow() } } }, { immediate: true }, ) const showDeleteRowModal = ref(false) const onDeleteRowClick = () => { showDeleteRowModal.value = true } const onConfirmDeleteRowClick = async () => { showDeleteRowModal.value = false await deleteRowById(primaryKey.value) message.success('Record deleted') reloadTrigger.trigger() onClose() showDeleteRowModal.value = false } watch(rowId, async (nRow) => { await _loadRow(nRow) await loadCommentsAndLogs() }) const showRightSections = computed(() => { return !isNew.value && commentsDrawer.value && isUIAllowed('commentList') }) const preventModalStatus = computed(() => isCloseModalOpen.value || isPreventChangeModalOpen.value) </script> <script lang="ts"> export default { name: 'ExpandedForm', } </script> <template> <NcModal v-model:visible="isExpanded" :footer="null" :width="commentsDrawer && isUIAllowed('commentList') ? 'min(80vw,1280px)' : 'min(80vw,1280px)'" :body-style="{ padding: 0 }" :closable="false" size="small" class="nc-drawer-expanded-form" :class="{ active: isExpanded }" > <div class="h-[85vh] xs:(max-h-full) max-h-215 flex flex-col p-6"> <div class="flex h-8 flex-shrink-0 w-full items-center nc-expanded-form-header relative mb-4 justify-between"> <template v-if="!isMobileMode"> <div class="flex gap-3 w-100"> <div class="flex gap-2"> <NcButton v-if="props.showNextPrevIcons" :disabled="isFirstRow" type="secondary" class="nc-prev-arrow !w-10" @click="$emit('prev')" > <MdiChevronUp class="text-md" /> </NcButton> <NcButton v-if="props.showNextPrevIcons" :disabled="islastRow" type="secondary" class="nc-next-arrow !w-10" @click="onNext" > <MdiChevronDown class="text-md" /> </NcButton> </div> <div v-if="isLoading"> <a-skeleton-input class="!h-8 !sm:mr-14 !w-52 mt-1 !rounded-md !overflow-hidden" active size="small" /> </div> <div v-else-if="displayValue && !row.rowMeta?.new" class="flex items-center font-bold text-gray-800 text-xl w-64"> <span class="truncate"> {{ displayValue }} </span> </div> <div v-if="row.rowMeta?.new" class="flex items-center truncate font-bold text-gray-800 text-xl">New Record</div> </div> <div class="flex gap-2"> <NcButton v-if="!isNew" type="secondary" class="!xs:hidden text-gray-700" @click="!isNew ? copyRecordUrl() : () => {}" > <div v-e="['c:row-expand:copy-url']" data-testid="nc-expanded-form-copy-url" class="flex gap-2 items-center"> <component :is="iconMap.check" v-if="isRecordLinkCopied" class="cursor-pointer nc-duplicate-row" /> <component :is="iconMap.link" v-else class="cursor-pointer nc-duplicate-row" /> {{ isRecordLinkCopied ? $t('labels.copiedRecordURL') : $t('labels.copyRecordURL') }} </div> </NcButton> <NcDropdown v-if="!isNew"> <NcButton type="secondary" class="nc-expand-form-more-actions w-10"> <GeneralIcon icon="threeDotVertical" class="text-md text-gray-700" /> </NcButton> <template #overlay> <NcMenu> <NcMenuItem v-if="!isNew" class="text-gray-700" @click="_loadRow()"> <div v-e="['c:row-expand:reload']" class="flex gap-2 items-center" data-testid="nc-expanded-form-reload"> <component :is="iconMap.reload" class="cursor-pointer" /> {{ $t('general.reload') }} </div> </NcMenuItem> <NcMenuItem v-if="!isNew && isMobileMode" class="text-gray-700" @click="!isNew ? copyRecordUrl() : () => {}"> <div v-e="['c:row-expand:copy-url']" data-testid="nc-expanded-form-copy-url" class="flex gap-2 items-center"> <component :is="iconMap.link" class="cursor-pointer nc-duplicate-row" /> {{ $t('labels.copyRecordURL') }} </div> </NcMenuItem> <NcMenuItem v-if="isUIAllowed('dataEdit') && !isNew" class="text-gray-700" @click="!isNew ? onDuplicateRow() : () => {}" > <div v-e="['c:row-expand:duplicate']" data-testid="nc-expanded-form-duplicate" class="flex gap-2 items-center" > <component :is="iconMap.copy" class="cursor-pointer nc-duplicate-row" /> <span class="-ml-0.25"> {{ $t('labels.duplicateRecord') }} </span> </div> </NcMenuItem> <NcDivider v-if="isUIAllowed('dataEdit') && !isNew" /> <NcMenuItem v-if="isUIAllowed('dataEdit') && !isNew" v-e="['c:row-expand:delete']" class="!text-red-500 !hover:bg-red-50" @click="!isNew && onDeleteRowClick()" > <component :is="iconMap.delete" data-testid="nc-expanded-form-delete" class="cursor-pointer nc-delete-row" /> <span class="-ml-0.5"> {{ $t('activity.deleteRecord') }} </span> </NcMenuItem> </NcMenu> </template> </NcDropdown> <NcButton type="secondary" class="nc-expand-form-close-btn w-10" data-testid="nc-expanded-form-close" @click="onClose" > <GeneralIcon icon="close" class="text-md text-gray-700" /> </NcButton> </div> </template> <template v-else> <div class="flex flex-row w-full"> <NcButton v-if="props.showNextPrevIcons" v-e="['c:row-expand:prev']" type="secondary" class="nc-prev-arrow !w-10" @click="$emit('prev')" > <GeneralIcon icon="arrowLeft" class="text-lg text-gray-700" /> </NcButton> <div class="flex flex-grow justify-center items-center font-semibold text-lg"> <div>{{ meta.title }}</div> </div> <NcButton v-if="props.showNextPrevIcons && !props.lastRow" v-e="['c:row-expand:next']" type="secondary" class="nc-next-arrow !w-10" @click="onNext" > <GeneralIcon icon="arrowRight" class="text-lg text-gray-700" /> </NcButton> </div> </template> </div> <div ref="wrapper" class="flex flex-grow flex-row h-[calc(100%-4rem)] w-full gap-4"> <div class="flex xs:w-full flex-col border-1 rounded-xl overflow-hidden border-gray-200 xs:(border-0 rounded-none)" :class="{ 'w-full': !showRightSections, 'w-2/3': showRightSections, }" > <div class="flex flex-col flex-grow mt-2 h-full max-h-full nc-scrollbar-md !pb-2 items-center w-full bg-white p-4 xs:p-0" > <div v-for="(col, i) of fields" v-show="isFormula(col) || !isVirtualCol(col) || !isNew || isLinksOrLTAR(col)" :key="col.title" class="nc-expanded-form-row mt-2 py-2 xs:w-full" :class="`nc-expand-col-${col.title}`" :col-id="col.id" :data-testid="`nc-expand-col-${col.title}`" > <div class="flex items-start flex-row sm:(gap-x-6) xs:(flex-col w-full) nc-expanded-cell min-h-10"> <div class="w-[12rem] xs:(w-full) mt-0.25 !h-[35px]"> <LazySmartsheetHeaderVirtualCell v-if="isVirtualCol(col)" class="nc-expanded-cell-header h-full !text-gray-500" :column="col" /> <LazySmartsheetHeaderCell v-else class="nc-expanded-cell-header !text-gray-500" :column="col" /> </div> <template v-if="isLoading"> <div v-if="isMobileMode" class="!h-8.5 !xs:h-12 !xs:bg-white !sm:mr-21 !w-60 mt-0.75 !rounded-lg !overflow-hidden" ></div> <a-skeleton-input v-else class="!h-8.5 !xs:h-9.5 !xs:bg-white !sm:mr-21 !w-60 mt-0.75 !rounded-lg !overflow-hidden" active size="small" /> </template> <template v-else> <SmartsheetDivDataCell v-if="col.title" :ref="i ? null : (el: any) => (cellWrapperEl = el)" class="!bg-white rounded-lg !w-[20rem] !xs:w-full border-1 border-gray-200 overflow-hidden px-1 min-h-[35px] flex items-center relative" > <LazySmartsheetVirtualCell v-if="isVirtualCol(col)" v-model="_row.row[col.title]" :row="_row" :column="col" /> <LazySmartsheetCell v-else v-model="_row.row[col.title]" :column="col" :edit-enabled="true" :active="true" :read-only="isPublic" @update:model-value="changedColumns.add(col.title)" /> </SmartsheetDivDataCell> </template> </div> </div> <div v-if="hiddenFields.length > 0" class="flex w-full px-12 items-center py-3"> <div class="flex-grow h-px mr-1 bg-gray-100"></div> <NcButton type="secondary" size="small" class="flex-shrink-1 !text-sm" @click="toggleHiddenFields"> {{ showHiddenFields ? `Hide ${hiddenFields.length} hidden` : `Show ${hiddenFields.length} hidden` }} {{ hiddenFields.length > 1 ? `fields` : `field` }} <MdiChevronDown class="ml-1" :class="showHiddenFields ? 'transform rotate-180' : ''" /> </NcButton> <div class="flex-grow h-px ml-1 bg-gray-100"></div> </div> <div v-if="hiddenFields.length > 0 && showHiddenFields" class="mb-3"> <div v-for="(col, i) of hiddenFields" v-show="isFormula(col) || !isVirtualCol(col) || !isNew || isLinksOrLTAR(col)" :key="col.title" class="mt-2 py-2" :class="`nc-expand-col-${col.title}`" :data-testid="`nc-expand-col-${col.title}`" > <div class="flex flex-row items-start min-h-10"> <div class="w-[12rem] scale-110 !h-[35px] mt-2.5"> <LazySmartsheetHeaderVirtualCell v-if="isVirtualCol(col)" :column="col" class="!text-gray-600" /> <LazySmartsheetHeaderCell v-else class="!text-gray-600" :column="col" /> </div> <template v-if="isLoading"> <div v-if="isMobileMode" class="!h-8.5 !xs:h-9.5 !xs:bg-white !sm:mr-21 !w-60 mt-0.75 !rounded-lg !overflow-hidden" ></div> <a-skeleton-input v-else class="!h-8.5 !xs:h-12 !xs:bg-white !sm:mr-21 !w-60 mt-0.75 !rounded-lg !overflow-hidden" active size="small" /> </template> <template v-else> <LazySmartsheetDivDataCell v-if="col.title" :ref="i ? null : (el: any) => (cellWrapperEl = el)" class="!bg-white rounded-lg !w-[20rem] border-1 overflow-hidden border-gray-200 px-1 min-h-[35px] flex items-center relative" > <LazySmartsheetVirtualCell v-if="isVirtualCol(col)" v-model="_row.row[col.title]" :row="_row" :column="col" /> <LazySmartsheetCell v-else v-model="_row.row[col.title]" :column="col" :edit-enabled="true" :active="true" :read-only="isPublic" @update:model-value="changedColumns.add(col.title)" /> </LazySmartsheetDivDataCell> </template> </div> </div> </div> </div> <div v-if="isUIAllowed('dataEdit')" class="w-full h-16 border-t-1 border-gray-200 bg-white flex items-center justify-end p-3 xs:(p-0 mt-4 border-t-0 gap-x-4 justify-between)" > <NcDropdown v-if="!isNew && isMobileMode"> <NcButton type="secondary" class="nc-expand-form-more-actions w-10"> <GeneralIcon icon="threeDotVertical" class="text-md text-gray-700" /> </NcButton> <template #overlay> <NcMenu> <NcMenuItem v-if="!isNew" class="text-gray-700" @click="_loadRow()"> <div v-e="['c:row-expand:reload']" class="flex gap-2 items-center" data-testid="nc-expanded-form-reload"> <component :is="iconMap.reload" class="cursor-pointer" /> {{ $t('general.reload') }} </div> </NcMenuItem> <NcDivider /> <NcMenuItem v-if="isUIAllowed('dataEdit') && !isNew" v-e="['c:row-expand:delete']" class="!text-red-500 !hover:bg-red-50" @click="!isNew && onDeleteRowClick()" > <div data-testid="nc-expanded-form-delete"> <component :is="iconMap.delete" class="cursor-pointer nc-delete-row" /> Delete record </div> </NcMenuItem> </NcMenu> </template> </NcDropdown> <div class="flex flex-row gap-x-3"> <NcButton v-if="isMobileMode" type="secondary" size="medium" data-testid="nc-expanded-form-save" class="nc-expand-form-save-btn !xs:(text-base)" @click="onClose" > <div class="px-1">Close</div> </NcButton> <NcButton v-e="['c:row-expand:save']" data-testid="nc-expanded-form-save" type="primary" size="medium" class="nc-expand-form-save-btn !xs:(text-base)" :disabled="changedColumns.size === 0 && !isUnsavedFormExist" @click="save" > <div class="xs:px-1">Save</div> </NcButton> </div> </div> </div> <div v-if="showRightSections" class="nc-comments-drawer border-1 relative border-gray-200 w-1/3 max-w-125 bg-gray-50 rounded-xl min-w-0 overflow-hidden h-full xs:hidden" :class="{ active: commentsDrawer && isUIAllowed('commentList') }" > <SmartsheetExpandedFormComments /> </div> </div> </div> </NcModal> <GeneralDeleteModal v-model:visible="showDeleteRowModal" entity-name="Record" :on-delete="() => onConfirmDeleteRowClick()"> <template #entity-preview> <span> <div class="flex flex-row items-center py-2.25 px-2.5 bg-gray-50 rounded-lg text-gray-700 mb-4"> <div class="capitalize text-ellipsis overflow-hidden select-none w-full pl-1.75 break-keep whitespace-nowrap"> {{ displayValue }} </div> </div> </span> </template> </GeneralDeleteModal> <!-- Prevent unsaved change modal --> <NcModal v-model:visible="preventModalStatus" size="small"> <div class=""> <div class="flex flex-row items-center gap-x-2 text-base font-bold"> {{ $t('tooltip.saveChanges') }} </div> <div class="flex font-medium mt-2"> {{ $t('activity.doYouWantToSaveTheChanges') }} </div> <div class="flex flex-row justify-end gap-x-2 mt-5"> <NcButton type="secondary" @click="discardPreventModal">{{ $t('labels.discard') }}</NcButton> <NcButton key="submit" type="primary" label="Rename Table" loading-label="Renaming Table" @click="saveChanges"> {{ $t('tooltip.saveChanges') }} </NcButton> </div> </div> </NcModal> </template> <style lang="scss"> .nc-drawer-expanded-form { @apply xs:my-0; } .nc-expanded-cell { input { @apply xs:(h-12 text-base); } } .nc-expanded-cell-header { @apply w-full text-gray-700 xs:mb-2; } .nc-expanded-cell-header > :nth-child(2) { @apply !text-sm !xs:text-base; } .nc-expanded-cell-header > :first-child { @apply !text-xl; } .nc-drawer-expanded-form .nc-modal { @apply !p-0; } </style>
packages/nc-gui/components/smartsheet/expanded-form/index.vue
1
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.984747052192688, 0.029329972341656685, 0.00016202448750846088, 0.0001899297203635797, 0.15142780542373657 ]
{ "id": 9, "code_window": [ " <LazySmartsheetDivDataCell\n", " v-if=\"col.title\"\n", " :ref=\"i ? null : (el: any) => (cellWrapperEl = el)\"\n", " class=\"!bg-white rounded-lg !w-[20rem] border-1 overflow-hidden border-gray-200 px-1 min-h-[35px] flex items-center relative\"\n", " >\n", " <LazySmartsheetVirtualCell\n", " v-if=\"isVirtualCol(col)\"\n", " v-model=\"_row.row[col.title]\"\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " class=\"!bg-white rounded-lg !w-[20rem] border-1 overflow-hidden border-gray-200 px-1 sm:min-h-[35px] xs:min-h-13 flex items-center relative\"\n" ], "file_path": "packages/nc-gui/components/smartsheet/expanded-form/index.vue", "type": "replace", "edit_start_line_idx": 676 }
<h1 align="center" style="border-bottom: none"> <b> <a href="https://www.nocodb.com">NocoDB</a><br> </b> ✨ Airtable 대체 오픈소스 ✨ <br> </h1> <p align="center"> MySQL, PostgreSQL, SQL Server, SQLite, MariaDB를 스마트 스프레드시트로 바꿔줍니다. </p> <div align="center"> [![Build Status](https://travis-ci.org/dwyl/esta.svg?branch=master)](https://travis-ci.com/github/NocoDB/NocoDB) [![Node version](https://img.shields.io/badge/node-%3E%3D%2014.18.0-brightgreen)](http://nodejs.org/download/) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-green.svg)](https://conventionalcommits.org) </div> <p align="center"> <a href="http://www.nocodb.com"><b>Website</b></a> • <a href="https://discord.gg/5RgZmkW"><b>Discord</b></a> • <a href="https://twitter.com/nocodb"><b>Twitter</b></a> • <a href="https://www.reddit.com/r/NocoDB/"><b>Reddit</b></a> • <a href="https://docs.nocodb.com/"><b>Documentation</b></a> </p> ![OpenSourceAirtableAlternative](https://user-images.githubusercontent.com/5435402/133762127-e94da292-a1c3-4458-b09a-02cd5b57be53.png) <img src="https://static.scarf.sh/a.png?x-pxid=c12a77cc-855e-4602-8a0f-614b2d0da56a" /> <p align="center"> <a href="https://www.producthunt.com/posts/nocodb?utm_source=badge-featured&utm_medium=badge&utm_souce=badge-nocodb" target="_blank"><img src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=297536&theme=dark" alt="NocoDB - The Open Source Airtable alternative | Product Hunt" style="width: 250px; height: 54px;" width="250" height="54" /></a> </p> # 빠른 시도 ### Docker 사용 ```bash docker run -d --name nocodb -p 8080:8080 nocodb/nocodb:latest ``` - NocoDB needs a database as input : See [Production Setup](https://github.com/nocodb/nocodb/blob/master/README.md#production-setup). - 데이터를 계속 저장하려면 반드시 `/usr/app/data/`에 볼륨을 마운트해야 합니다 Example: ``` docker run -d -p 8080:8080 --name nocodb -v "$(pwd)"/nocodb:/usr/app/data/ nocodb/nocodb: ### npm 사용 ``` npx create-nocodb-app ``` ### Git 사용 ``` git clone https://github.com/nocodb/nocodb-seed cd nocodb-seed npm install npm start ``` ### GUI 대시보드 접근 : [http://localhost:8080/dashboard](http://localhost:8080/dashboard) # 커뮤니티 가입 <a href="https://discord.gg/5RgZmkW"> <img src="https://invidget.switchblade.xyz/5RgZmkW" alt="NocoDB 디스코드 들어오기" > </a> <br> # 스크린샷 ![1](https://user-images.githubusercontent.com/86527202/136069919-4ea818df-2b05-4038-890d-f329773b8967.png) <br> ![2](https://user-images.githubusercontent.com/86527202/136069938-f0ab0ee3-2b8f-44d8-a82a-1d800b69cabe.png) <br> ![5](https://user-images.githubusercontent.com/86527202/136069943-2baf7a53-53f2-494c-8108-b81841df7bb4.png) <br> ![6](https://user-images.githubusercontent.com/86527202/136069946-eb33a828-5911-49f9-a862-ca2d497f8c5a.png) <br> ![7](https://user-images.githubusercontent.com/86527202/136069949-5fd6fe37-c52b-43f1-ac70-aad057f24fe5.png) <br> ![8](https://user-images.githubusercontent.com/86527202/136069954-7968a745-ce54-48cc-ab8d-337ccdaf5eee.png) <br> ![9](https://user-images.githubusercontent.com/86527202/136069958-287c1085-d983-467f-880b-a900a1a5aecb.png) <br> ![9a](https://user-images.githubusercontent.com/86527202/136069962-4c79c51b-2dc9-4839-8521-baaa6e2bc0f8.png) <br> ![9b](https://user-images.githubusercontent.com/86527202/136069965-e61ed8d3-9842-4eac-9423-f3c3321e8651.png) <br> ![10](https://user-images.githubusercontent.com/86527202/136069967-4697ee78-d156-44bb-bc04-5dd43d23e694.png) <br> ![11](https://user-images.githubusercontent.com/86527202/136069971-402bb0fe-af19-439b-9fb8-c2a882f5d35a.png) <br> # 기능 ### 스프레드시트 인터페이스 - ⚡ 기본 오퍼레이션: 테이블, 칼럼, 로우 CRUD - ⚡ 필드 오퍼레이션: 정렬, 필터, 칼럼 보기/숨기기 - ⚡ 뷰 타입: 그리드, 갤러리, 칸반, 간트 차트, 양식(Form) - ⚡ 공유: 공개 / 비공개 뷰 (비밀 번호 설정) - ⚡ 다양한 셀 타입: ID, LinkToAnotherRecord, Lookup, Rollup, SingleLine Text, Attachment, Currency, Formula 등 - ⚡ 역할에 따른 접근 제한: 다양한 수준의 세분화된 액세스 제어 ### 워크플로 자동화를 위한 앱스토어 크게 채팅, 이메일, 저장소 세 가지 카테고리에 대한 통합을 제공합니다. 자세한 사항은 <a href="https://docs.nocodb.com/setup-and-usages/app-store" target="_blank">App Store</a> 를 참고하세요. - ⚡ 채팅: MS 팀즈, 슬랙, 디스코드, 매터모스트 - ⚡ 이메일: SMTP, SES, MailChimp - ⚡ SMS: Twilio - ⚡ 왓츠앱 - ⚡ 그 외에 여러 서드파티 API ### 외부 API 접근 - ⚡ REST API (Swagger) - ⚡ GraphQL API - ⚡ JWT 인증 및 SNS 로그인 - ⚡ Zapier 및 Integromat 통합을 위한 API 토큰 # 운영 환경에 설치하기 NocoDB는 스프레드시트 뷰 메타데이터와 외부 데이터베이스 정보를 저장하기 위한 데이터베이스를 필요로 합니다. 그리고 이 데이터베이스 연결을 위한 정보는 `NC_DB` 환경변수에 담습니다. ## Docker #### MySQL 예제 ``` docker run -d -p 8080:8080 \ -e NC_DB="mysql2://host.docker.internal:3306?u=root&p=password&d=d1" \ -e NC_AUTH_JWT_SECRET="569a1821-0a93-45e8-87ab-eb857f20a010" \ nocodb/nocodb:latest ``` #### PostgreSQL 예제 ``` docker run -d -p 8080:8080 \ -e NC_DB="pg://host:port?u=user&p=password&d=database" \ -e NC_AUTH_JWT_SECRET="569a1821-0a93-45e8-87ab-eb857f20a010" \ nocodb/nocodb:latest ``` #### SQL Server 예제 ``` docker run -d -p 8080:8080 \ -e NC_DB="mssql://host:port?u=user&p=password&d=database" \ -e NC_AUTH_JWT_SECRET="569a1821-0a93-45e8-87ab-eb857f20a010" \ nocodb/nocodb:latest ``` ## Docker Compose ``` git clone https://github.com/nocodb/nocodb cd nocodb cd docker-compose cd mysql or pg or mssql docker-compose up -d ``` ## 환경변수 여기서 확인해주세요. [환경변수 ](https://docs.nocodb.com/getting-started/environment-variables) # 개발 환경에 설치 여기서 확인해주세요. [개발 환경에 설치하는 법](https://docs.nocodb.com/engineering/development-setup) # 기여 여기서 확인해주세요. [기여 가이드라인](https://github.com/nocodb/nocodb/blob/master/.github/CONTRIBUTING.md). # 왜 이걸 만들었나요? 대부분의 인터넷 비즈니스는 업무상의 요구사항을 해결하기 위해 스프레드시트 또는 데이터베이스를 사용합니다. 스프레드시트는 매일 하루에 수십억 명 이상이 함께 사용합니다. 그러나 우리는 컴퓨팅에 관한 한 훨씬 강력한 도구인 데이터베이스는 별로 그만큼 사용하고 있지 않습니다. 이 문제를 SaaS로 해결하려는 시도는 끔찍한 접근 통제, 특정 업체 종속, 데이터 종속, 급격한 가격 변동, 그리고 무엇보다도 미래의 가능성을 스스로 가둬버리는 것을 의미합니다. # 우리의 사명 우리의 사명은 이 세상의 모든 인터넷 비즈니스를 위해 가장 강력한 노코드(No-Code) 데이터베이스 인터페이스를 오픈소스로 제공하는 것입니다. 이는 단지 강력한 컴퓨팅 도구를 대중화하는 데 그치는 것이 아니라, 인터넷 상에서 뭐든 이어붙이고 만들 수 있는 급진적인 능력을 수십억 사람들에게 가져다주게 될 것입니다.
markdown/readme/languages/korean.md
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00031194684561342, 0.00018384230497758836, 0.00016433832934126258, 0.00016970757860690355, 0.000040530871046939865 ]
{ "id": 9, "code_window": [ " <LazySmartsheetDivDataCell\n", " v-if=\"col.title\"\n", " :ref=\"i ? null : (el: any) => (cellWrapperEl = el)\"\n", " class=\"!bg-white rounded-lg !w-[20rem] border-1 overflow-hidden border-gray-200 px-1 min-h-[35px] flex items-center relative\"\n", " >\n", " <LazySmartsheetVirtualCell\n", " v-if=\"isVirtualCol(col)\"\n", " v-model=\"_row.row[col.title]\"\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " class=\"!bg-white rounded-lg !w-[20rem] border-1 overflow-hidden border-gray-200 px-1 sm:min-h-[35px] xs:min-h-13 flex items-center relative\"\n" ], "file_path": "packages/nc-gui/components/smartsheet/expanded-form/index.vue", "type": "replace", "edit_start_line_idx": 676 }
{ "general": { "home": "Start", "load": "Laden", "open": "Öffnen", "close": "Schließen", "yes": "Ja", "no": "Nein", "ok": "Ok", "and": "Und", "or": "Oder", "add": "Hinzufügen", "edit": "Bearbeiten", "remove": "Entfernen", "save": "Speichern", "cancel": "Abbrechen", "submit": "Übertragen", "create": "Erstellen", "duplicate": "Duplizieren", "insert": "Einfügen", "delete": "Löschen", "update": "Aktualisieren", "rename": "Umbenennen", "reload": "Neu laden", "reset": "Zurücksetzen", "install": "Installieren", "show": "Anzeigen", "hide": "Verstecken", "showAll": "Alles anzeigen", "hideAll": "Alles verstecken", "showMore": "Mehr anzeigen", "showOptions": "Optionen einblenden", "hideOptions": "Optionen ausblenden", "showMenu": "Menü einblenden", "hideMenu": "Menü ausblenden", "addAll": "Alles hinzufügen", "removeAll": "Alles entfernen", "signUp": "Anmelden", "signIn": "Einloggen", "signOut": "Ausloggen", "required": "Erforderlich", "enableScanner": "Enable Scanner for filling", "preferred": "Bevorzugt", "mandatory": "Verpflichtend", "loading": "Wird geladen ...", "title": "Titel", "upload": "Hochladen", "download": "Herunterladen", "default": "Standard", "more": "Mehr", "less": "Weniger", "event": "Ereignis", "condition": "Bedingung", "after": "Nach dem", "before": "Vor", "search": "Suche", "notification": "Benachrichtigung", "reference": "Referenz", "function": "Funktion", "confirm": "Bestätigen", "generate": "Generieren", "copy": "Kopieren", "misc": "Sonstiges", "lock": "Sperren", "unlock": "Entsperren", "credentials": "Anmeldeinformationen", "help": "Hilfe", "questions": "Fragen", "reachOut": "Erreichen sie uns hier", "betaNote": "Diese Funktion befindet sich derzeit in der Beta.", "moreInfo": "Mehr Informationen können hier gefunden werden", "logs": "Protokolle", "groupingField": "Gruppierungsfeld", "insertAfter": "danach einfügen", "insertBefore": "davor einfügen", "hideField": "Feld ausblenden", "sortAsc": "Aufsteigend sortieren", "sortDesc": "Absteigend sortieren", "geoDataField": "GeoData Field" }, "objects": { "project": "Projekt", "projects": "Projekte", "table": "Tabelle", "tables": "Tabellen", "field": "Feld", "fields": "Felder", "column": "Spalte", "columns": "Spalten", "page": "Seite", "pages": "Seiten", "record": "Aufzeichnen", "records": "Aufzeichnungen", "webhook": "Webhook", "webhooks": "Webhooks", "view": "Ansicht", "views": "Ansichten", "viewType": { "grid": "Gitter", "gallery": "Galerie", "form": "Formular", "kanban": "Kanban", "calendar": "Kalender", "map": "Map" }, "user": "Nutzer", "users": "Benutzer", "role": "Rolle", "roles": "Rollen", "roleType": { "owner": "Eigentümer", "creator": "Ersteller", "editor": "Bearbeiter", "commenter": "Kommentator", "viewer": "Zuschauer", "orgLevelCreator": "Organisationsebene Schöpfer", "orgLevelViewer": "Betrachter der Organisationsebene" }, "sqlVIew": "SQL Ansicht" }, "datatype": { "ID": "Nummer", "ForeignKey": "Unbekannter Schlüssel", "SingleLineText": "Einzeiliger Text", "LongText": "Langer Text", "Attachment": "Anhang", "Checkbox": "Kontrollkästchen", "MultiSelect": "Mehrfachauswahl", "SingleSelect": "Einfache Auswahl", "Collaborator": "Mitarbeiter", "Date": "Datum", "Year": "Jahr", "Time": "Zeit", "PhoneNumber": "Telefonnummer", "Email": "Email", "URL": "URL", "Number": "Nummer", "Decimal": "Dezimal", "Currency": "Währung", "Percent": "Prozent", "Duration": "Dauer", "GeoData": "GeoData", "Rating": "Klassifizierung", "Formula": "Formel", "Rollup": "Zusammenfassung", "Count": "Zählen", "Lookup": "Nachschlagen", "DateTime": "Datum/Zeit", "CreateTime": "Zeit erstellen", "LastModifiedTime": "Zuletzt bearbeitet", "AutoNumber": "Auto-Nummerierung", "Barcode": "Barcode", "Button": "Taste", "Password": "Passwort", "relationProperties": { "noAction": "Keine Aktion", "cascade": "Kaskade", "restrict": "Beschränken", "setNull": "Auf Null setzen", "setDefault": "Auf Standard setzen" } }, "filterOperation": { "isEqual": "ist gleich", "isNotEqual": "ist nicht gleich", "isLike": "ist wie", "isNot like": "ist nicht wie", "isEmpty": "ist leer", "isNotEmpty": "ist nicht leer", "isNull": "ist Null", "isNotNull": "ist nicht Null" }, "title": { "erdView": "ERD Ansicht", "newProj": "Neues Projekt", "myProject": "Meine Projekte", "formTitle": "Formular Titel", "collabView": "Mitarbeiteransicht", "lockedView": "Gesperrte Ansicht", "personalView": "Persönliche Ansicht", "appStore": "App-Store", "teamAndAuth": "Team & Authentifizierung", "rolesUserMgmt": "Rollen- & Benutzermanagement", "userMgmt": "Benutzermanagement", "apiTokenMgmt": "API-Tokens-Management", "rolesMgmt": "Rollenmanagement", "projMeta": "Projektmetadaten", "metaMgmt": "Meta-Management", "metadata": "Metadaten", "exportImportMeta": "Metadaten exportieren / importieren", "uiACL": "UI-Zugangskontrolle", "metaOperations": "Metadatenoperationen", "audit": "Revisionen", "auditLogs": "Audit-Log", "sqlMigrations": "SQL-Migrationen", "dbCredentials": "Datenbank-Anmeldeinformationen", "advancedParameters": "SSL & Erweiterte Parameter", "headCreateProject": "Projekt erstellen | NocoDB", "headLogin": "Anmelden | NocoDB", "resetPassword": "Passwort zurücksetzen", "teamAndSettings": "Team & Einstellungen", "apiDocs": "API Dokumentation", "importFromAirtable": "Import aus Airtable", "generateToken": "Token generieren", "APIsAndSupport": "APIs & Support", "helpCenter": "Hilfecenter", "swaggerDocumentation": "Swagger Dokumentation", "quickImportFrom": "Schnell importieren von", "quickImport": "Schnell Importieren", "advancedSettings": "Erweiterte Einstellungen", "codeSnippet": "Code Ausschnitt", "keyboardShortcut": "Tastenkürzel", "generateRandomName": "Generate Random Name", "findRowByScanningCode": "Find row by scanning a QR or Barcode" }, "labels": { "createdBy": "Erstellt von", "notifyVia": "Benachrichtigen mit", "projName": "Projektname", "tableName": "Tabellenname", "viewName": "Namen anzeigen", "viewLink": "Link anzeigen", "columnName": "Spaltenname", "columnToScanFor": "Column to scan", "columnType": "Spaltentyp", "roleName": "Rollenname", "roleDescription": "Rollenbeschreibung", "databaseType": "Typ in der Datenbank", "lengthValue": "Länge / Wert", "dbType": "Datenbanktyp", "sqliteFile": "SQLite-Datei", "hostAddress": "Host-Adresse", "port": "Port-Nummer", "username": "Benutzername", "password": "Passwort", "schemaName": "Name des Schemas", "database": "Datenbank", "action": "Aktion", "actions": "Aktionen", "operation": "Vorgang", "operationSub": "Sub Operation", "operationType": "Vorgangstyp", "operationSubType": "Vorgangsuntertyp", "description": "Beschreibung", "authentication": "Authentifizierung", "token": "Token", "where": "Wo", "cache": "Zwischenspeicher", "chat": "Chat", "email": "Email", "storage": "Speicher", "uiAcl": "Oberflächenzugriffskontrollliste", "models": "Modelle", "syncState": "Sync-Status", "created": "Erstellt", "sqlOutput": "SQL-Ausgabe", "addOption": "Option hinzufügen", "qrCodeValueColumn": "Spalte mit QR-Code", "barcodeValueColumn": "Spalte mit Barcode-Wert", "barcodeFormat": "Barcode-Format", "qrCodeValueTooLong": "Zu viele Zeichen für einen QR-Code", "barcodeValueTooLong": "Zu viele Zeichen für einen Barcode", "currentLocation": "Current Location", "lng": "Lng", "lat": "Lat", "aggregateFunction": "Globale Funktion", "dbCreateIfNotExists": "Datenbank: Erstellen, falls nicht vorhanden", "clientKey": "Client-Schlüssel", "clientCert": "Client Zertifikat", "serverCA": "Server CA", "requriedCa": "Erforderliches CA", "requriedIdentity": "Erforderliche Identität", "inflection": { "tableName": "Flexion - Tabellenname", "columnName": "Flexion - Spaltenname" }, "community": { "starUs1": "Stern", "starUs2": "uns auf Github", "bookDemo": "Eine kostenlose Demo buchen", "getAnswered": "Erhalten Sie Antworten auf Ihre Fragen", "joinDiscord": "Discord beitreten", "joinCommunity": "NocoDB Community beitreten", "joinReddit": "/r/NocoDB beitreten", "followNocodb": "Folgen Sie NocoDB" }, "docReference": "Dokumentenverweis", "selectUserRole": "Benutzerrolle auswählen", "childTable": "Child-Tabelle", "childColumn": "Child-Spalte", "linkToAnotherRecord": "Link zu einem anderen Datensatz", "onUpdate": "Update", "onDelete": "Löschen", "account": "Benutzerkonto", "language": "Sprache", "primaryColor": "Primärfarbe", "accentColor": "Akzentfarbe", "customTheme": "Benutzerdefiniertes Theme", "requestDataSource": "Eine benötigte Datenquelle anfragen?", "apiKey": "API Schlüssel", "sharedBase": "Geteilte Basis", "importData": "Daten Importieren", "importSecondaryViews": "Sekundäre Ansichten importieren", "importRollupColumns": "Rollup-Spalten importieren", "importLookupColumns": "Suchspalten importieren", "importAttachmentColumns": "Spalten für Anhänge importieren", "importFormulaColumns": "Formelspalten importieren", "noData": "Keine Daten", "goToDashboard": "Zum Dashboard gehen", "importing": "Wird importiert", "flattenNested": "Verflachen Verschachtelt", "downloadAllowed": "Download erlaubt", "weAreHiring": "Wir stellen ein!", "primaryKey": "Primärschlüssel", "hasMany": "hat viele", "belongsTo": "gehört zu", "manyToMany": "haben M:N-Beziehnungen", "extraConnectionParameters": "Zusätzliche Verbindungsparameter", "commentsOnly": "Nur Kommentare", "documentation": "Dokumentation", "subscribeNewsletter": "Abonnieren Sie unseren wöchentlichen Newsletter", "signUpWithProvider": "Mit {provider} anmelden", "signInWithProvider": "Mit {provider} einloggen", "agreeToTos": "Mit Ihrer Anmeldung stimmen Sie den allgemeinen Nutzungsbedingungen zu", "welcomeToNc": "Willkommen bei NocoDB!", "inviteOnlySignup": "Anmeldung nur über Einladungs-URL zulassen", "nextRow": "Nächste Reihe", "prevRow": "Vorherige Reihe" }, "activity": { "createProject": "Projekt erstellen", "importProject": "Projekt importieren", "searchProject": "Projekt suchen", "editProject": "Projekt bearbeiten", "stopProject": "Projekt stoppen", "startProject": "Projekt starten", "restartProject": "Projekt neu starten", "deleteProject": "Projekt löschen", "refreshProject": "Projekte aktualisieren", "saveProject": "Projekt speichern", "deleteKanbanStack": "Stapel löschen?", "createProjectExtended": { "extDB": "Erstellen durch Verbinden <br>mit einer externen Datenbank", "excel": "Projekt aus Excel erstellen", "template": "Projekt aus Vorlage erstellen" }, "OkSaveProject": "OK & Projekt speichern", "upgrade": { "available": "Upgrade verfügbar", "releaseNote": "Versionshinweise", "howTo": "Wie wird aktualisiert?" }, "translate": "Übersetzen helfen", "account": { "authToken": "Auth-Token kopieren", "swagger": "Swagger: REST APIs", "projInfo": "Projektinfo kopieren", "themes": "Themen" }, "sort": "Sortieren", "addSort": "Sortieroption hinzufügen", "filter": "Filter", "addFilter": "Filter hinzufügen", "share": "Teilen", "shareBase": { "disable": "Freigegebene Datenbank deaktivieren", "enable": "Jeder mit dem Link", "link": "Freigegebene Datenbank-Link" }, "invite": "Einladen", "inviteMore": "Mehr einladen", "inviteTeam": "Team einladen", "inviteUser": "Benutzer einladen", "inviteToken": "Token einladen", "newUser": "Neuer Benutzer", "editUser": "Benutzer bearbeiten", "deleteUser": "Benutzer vom Projekt entfernen", "resendInvite": "Einladungs-Email erneut versenden", "copyInviteURL": "Einladungs-URL kopieren", "copyPasswordResetURL": "Kopieren Sie die URL zum Zurücksetzen des Passworts", "newRole": "Neue Rolle", "reloadRoles": "Rollen neu laden", "nextPage": "Nächste Seite", "prevPage": "Vorherige Seite", "nextRecord": "Nächster Eintrag", "previousRecord": "Vorheriger Eintrag", "copyApiURL": "API-URL kopieren", "createTable": "Create New Table", "refreshTable": "Tabellen aktualisieren", "renameTable": "Rename Table", "deleteTable": "Delete Table", "addField": "Neues Feld zu dieser Tabelle hinzufügen", "setDisplay": "Set as Display value", "addRow": "Neue Zeile hinzufügen", "saveRow": "Zeile speichern", "saveAndExit": "Speichern & Verlassen", "saveAndStay": "Speichern & Bleiben", "insertRow": "Neue Zeile einfügen", "duplicateRow": "Duplicate Row", "deleteRow": "Zeile löschen", "deleteSelectedRow": "Ausgewählte Zeilen löschen", "importExcel": "Excel-Datei importieren", "importCSV": "CSV-Datei importieren", "downloadCSV": "Download als CSV", "downloadExcel": "Download als XLSX", "uploadCSV": "Hochladen CSV", "import": "Importieren", "importMetadata": "Metadaten importieren", "exportMetadata": "Metadaten exportieren", "clearMetadata": "Metadaten löschen", "exportToFile": "Export in Datei", "changePwd": "Kennwort ändern", "createView": "Ansicht erstellen", "shareView": "Ansicht teilen", "findRowByCodeScan": "Find row by scan", "fillByCodeScan": "Fill by scan", "listSharedView": "Geteilte Ansichtenliste", "ListView": "Ansichtenliste", "copyView": "Ansicht kopieren", "renameView": "Ansicht umbenennen", "deleteView": "Ansicht löschen", "createGrid": "Gitter-Ansicht erstellen", "createGallery": "Galerie-Ansicht erstellen", "createCalendar": "Kalender-Ansicht erstellen", "createKanban": "Kanban-Ansicht erstellen", "createForm": "Formular-Ansicht erstellen", "showSystemFields": "Systemfelder anzeigen", "copyUrl": "URL kopieren", "openTab": "Neue Registerkarte öffnen", "iFrame": "Eingebetteten HTML-Code kopieren", "addWebhook": "Neuen Webhook hinzufügen", "enableWebhook": "Enable Webhook", "testWebhook": "Test Webhook", "copyWebhook": "Copy Webhook", "deleteWebhook": "Delete Webhook", "newToken": "Neuen Token hinzufügen", "exportZip": "Zip-Datei exportieren", "importZip": "Zip-Datei importieren", "metaSync": "Jetzt synchronisieren", "settings": "Einstellungen", "previewAs": "Vorschau anzeigen als", "resetReview": "Vorschau zurücksetzen", "testDbConn": "Datenbankverbindung testen", "removeDbFromEnv": "Datenbank aus der Umgebung entfernen", "editConnJson": "Verbindung JSON bearbeiten", "sponsorUs": "Sponsor uns", "sendEmail": "E-MAIL SENDEN", "addUserToProject": "Benutzer zum Projekt hinzufügen", "getApiSnippet": "zeige API Snippet", "clearCell": "Zelle leeren", "addFilterGroup": "Filtergruppe hinzufügen", "linkRecord": "Link-Datensatz", "addNewRecord": "Neuen Datensatz hinzufügen", "useConnectionUrl": "Verbindungs-URL verwenden", "toggleCommentsDraw": "Kommentare umschalten zeichnen", "expandRecord": "Datensatz erweitern", "deleteRecord": "Datensatz löschen", "erd": { "showColumns": "Spalten anzeigen", "showPkAndFk": "Primäre und fremde Schlüssel anzeigen", "showSqlViews": "SQL-Ansichten anzeigen", "showMMTables": "Viele-zu-viele-Tabellen anzeigen", "showJunctionTableNames": "Namen der Kreuzungstabellen anzeigen" }, "kanban": { "collapseStack": "Stapel einklappen", "deleteStack": "Stapel löschen", "stackedBy": "Gestapelt von", "chooseGroupingField": "Wählen Sie ein Gruppierungsfeld", "addOrEditStack": "Stapel hinzufügen / bearbeiten" }, "map": { "mappedBy": "Mapped By", "chooseMappingField": "Choose a Mapping Field", "openInGoogleMaps": "Google Maps", "openInOpenStreetMap": "OSM" }, "toggleMobileMode": "Toggle Mobile Mode" }, "tooltip": { "saveChanges": "Änderungen speichern", "xcDB": "Neues Projekt erstellen", "extDB": "Unterstützt MySQL, PostgreSQL, SQL Server & SQLite", "apiRest": "Zugänglich über Rest APIs", "apiGQL": "Zugänglich über Graphql-APIs", "theme": { "dark": "Es kommt in Schwarz (^ ⇧b)", "light": "Kommt es in schwarz? (^ ⇧b)" }, "addTable": "Neue Tabelle hinzufügen", "inviteMore": "Mehr Benutzer einladen", "toggleNavDraw": "Navigationsbereich umschalten", "reloadApiToken": "API-Token neu laden", "generateNewApiToken": "Neuen API-Token generieren", "addRole": "Neue Rolle hinzufügen", "reloadList": "Liste neu laden", "metaSync": "Metadaten synchronisieren", "sqlMigration": "Migrationen neu laden", "updateRestart": "Update & Neustart", "cancelReturn": "Abbrechen und Zurück", "exportMetadata": "Alle Metadaten von Metatabellen in Meta-Verzeichnis exportieren.", "importMetadata": "Alle Metadaten vom Meta-Verzeichnis in Metatabellen importieren.", "clearMetadata": "Alle Metadaten aus Meta-Tabellen löschen.", "clientKey": "Auswahl .key-Datei", "clientCert": "Auswahl .cert-Datei", "clientCA": "Auswahl CA-Datei" }, "placeholder": { "projName": "Projektnamen eingeben", "password": { "enter": "Passwort eingeben", "current": "Aktuelles Passwort", "new": "Neues Passwort", "save": "Passwort speichern", "confirm": "Neues Passwort bestätigen" }, "searchProjectTree": "Tabellen suchen", "searchFields": "Felder suchen", "searchColumn": "Spalten suchen {search}", "searchApps": "Apps suchen", "searchModels": "Modelle suchen", "noItemsFound": "Keine Elemente gefunden", "defaultValue": "Standardwert", "filterByEmail": "Filtern nach E-Mail", "filterQuery": "Filter-Abfrage", "selectField": "Feld wählen" }, "msg": { "warning": { "barcode": { "renderError": "Barcode-Fehler - bitte überprüfen Sie die Kompatibilität zwischen Eingabe und Barcode-Typ" }, "nonEditableFields": { "computedFieldUnableToClear": "Warnung: Berechnetes Feld - Text kann nicht gelöscht werden", "qrFieldsCannotBeDirectlyChanged": "Warnung: QR-Felder können nicht direkt geändert werden." } }, "info": { "pasteNotSupported": "Der Vorgang Einfügen wird auf der aktiven Zelle nicht unterstützt", "roles": { "orgCreator": "Der Ersteller kann neue Projekte erstellen und auf alle eingeladenen Projekte zugreifen.", "orgViewer": "Betrachter können keine neuen Projekte erstellen, aber sie können auf alle eingeladenen Projekte zugreifen." }, "codeScanner": { "loadingScanner": "Loading the scanner...", "selectColumn": "Select a column (QR code or Barcode) that you want to use for finding a row by scanning.", "moreThanOneRowFoundForCode": "More than one row found for this code. Currently only unique codes are supported.", "noRowFoundForCode": "No row found for this code for the selected column" }, "map": { "overLimit": "You're over the limit.", "closeLimit": "You're getting close to the limit.", "limitNumber": "The limit of markers shown in a Map View is 1000 records." }, "footerInfo": "Zeilen pro Seite", "upload": "Datei zum Hochladen auswählen", "upload_sub": "oder Drag & Drop Datei", "excelSupport": "Unterstützt: .xls ,.xlsx ,.xlsm, .ods, .ots", "excelURL": "Excel-Datei-URL eingeben", "csvURL": "CSV-Datei-URL eingeben", "footMsg": "Anzahl der Zeilen, um den Datentyp analysieren zu können", "excelImport": "Blatt/Blätter stehen für den Import zur Verfügung", "exportMetadata": "Möchten Sie Metadaten von Meta-Tabellen exportieren?", "importMetadata": "Möchten Sie Metadaten von Metatabellen importieren?", "clearMetadata": "Möchten Sie Metadaten von Meta-Tabellen löschen?", "projectEmptyMessage": "Mit dem Erstellen eines neuen Projektes beginnen", "stopProject": "Möchten Sie das Projekt beenden?", "startProject": "Möchten Sie das Projekt starten?", "restartProject": "Möchten Sie das Projekt neu starten?", "deleteProject": "Möchten Sie das Projekt löschen?", "shareBasePrivate": "Öffentlich freigegebene Nur-Lese-Datenbank generieren", "shareBasePublic": "Für Jeden im Internet mit diesem Link sichtbar", "userInviteNoSMTP": "Es sieht so aus, als hätten Sie den Mailer noch nicht konfiguriert! Bitte kopieren Sie den obigen Einladungs-Link und senden Sie ihn an", "dragDropHide": "Ziehen Sie die Felder hierher, um sie zu verstecken", "formInput": "Formularbezeichnung eingeben", "formHelpText": "Einen Hilfs-Text hinzufügen", "onlyCreator": "Nur für den Ersteller sichtbar", "formDesc": "Formularbeschreibung hinzufügen", "beforeEnablePwd": "Den Zugriff mit einem Passwort einschränken", "afterEnablePwd": "Zugriff ist Passwort-geschützt", "privateLink": "Diese Ansicht wird durch einen persönlichen Link geteilt", "privateLinkAdditionalInfo": "Personen mit einem persönlichen Link können nur Zellen sehen, die in dieser Ansicht angezeigt werden", "afterFormSubmitted": "Nachdem das Formular übermittelt wurde", "apiOptions": "Zugriff auf das Projekt via", "submitAnotherForm": "Weiteres Formular übermitteln'-Button anzeigen", "showBlankForm": "Ein leeres Formular nach 5 Sekunden anzeigen", "emailForm": "E-Mail an mich unter", "showSysFields": "Systemfelder anzeigen", "filterAutoApply": "Automatisch anwenden", "showMessage": "Diese Nachricht anzeigen", "viewNotShared": "Aktuelle Ansicht wird nicht geteilt!", "showAllViews": "Alle geteilten Ansichten dieser Tabelle anzeigen", "collabView": "Mitarbeitern mit Bearbeitungsberechtigung oder höher können die Ansichtenkonfiguration ändern", "lockedView": "Niemand kann die Ansichtenkonfiguration bearbeiten, bis sie freigeschaltet ist.", "personalView": "Nur Sie können die Ansichtenkonfiguration bearbeiten. Weitere Mitarbeiter-Ansichten sind standardmäßig ausgeblendet.", "ownerDesc": "Kann Ersteller hinzufügen / entfernen und Datenbankstrukturen und -felder voll bearbeiten.", "creatorDesc": "Kann Datenbankstrukturen und Werte vollständig bearbeiten.", "editorDesc": "Kann Datensätze bearbeiten, aber die Struktur von Datenbanken / Feldern nicht ändern.", "commenterDesc": "Kann die Datensätze anzeigen und kommentieren, aber nicht bearbeiten", "viewerDesc": "Kann die Einträge anzeigen, aber nicht bearbeiten", "addUser": "Neuen Benutzer hinzufügen", "staticRoleInfo": "Systemdefinierte Rollen können nicht bearbeitet werden", "exportZip": "Projekt-Meta in ZIP-Datei exportieren und downloaden", "importZip": "Projekt Meta-ZIP-Datei importieren und neu starten.", "importText": "Importieren von NocoDB-Projekt durch Hochladen von Metadaten-ZIP-Datei", "metaNoChange": "Keine Änderung identifiziert", "sqlMigration": "Schemen-Migrationen werden automatisch erstellt. Tabelle erstellen und diese Seite aktualisieren.", "dbConnectionStatus": "Umgebung validiert", "dbConnected": "Verbindung war erfolgreich", "notifications": { "no_new": "Keine neuen Benachrichtigungen", "clear": "Leeren" }, "sponsor": { "header": "Sie können uns helfen!", "message": "Wir sind ein winziges Team, welches Vollzeit arbeitet, um NocoDB Open-Source zu machen. Wir glauben, daß ein Werkzeug wie NocoDB für jeden Problemlöser im Internet frei verfügbar sein sollte." }, "loginMsg": "In NocoDB einloggen", "passwordRecovery": { "message_1": "Bitte geben Sie die E-Mail-Adresse an, die Sie bei der Anmeldung verwendet haben.", "message_2": "Wir senden Ihnen eine E-Mail mit einem Link, um das Passwort zurückzusetzen.", "success": "Bitte überprüfen Sie Ihre E-Mail, um das Passwort zurückzusetzen" }, "signUp": { "superAdmin": "Sie werden der \"Super Admin\" sein", "alreadyHaveAccount": "Sie haben bereits ein Konto ?", "workEmail": "Geben Sie Ihre Arbeits-E-Mail ein", "enterPassword": "Geben Sie Ihr Passwort ein", "forgotPassword": "Passwort vergessen ?", "dontHaveAccount": "Sie haben kein Konto?" }, "addView": { "grid": "Gitter-Ansicht hinzufügen", "gallery": "Galerie-Ansicht hinzufügen", "form": "Formular-Ansicht hinzufügen", "kanban": "Kanban-Ansicht hinzufügen", "map": "Add Map View", "calendar": "Kalender-Ansicht hinzufügen" }, "tablesMetadataInSync": "Tabellen-Metadaten sind synchron", "addMultipleUsers": "Sie können mehrere kommagetrennte (,) E-Mails hinzufügen", "enterTableName": "Geben Sie den Tabellennamen ein", "addDefaultColumns": "Standardspalten hinzufügen", "tableNameInDb": "Tabellenname wie in der Datenbank gespeichert", "airtable": { "credentials": "Wo zu finden?" }, "import": { "clickOrDrag": "Klicken oder ziehen Sie die Datei zum Hochladen in diesen Bereich" }, "metaDataRecreated": "Metadaten der Tabelle erfolgreich neu erstellt", "invalidCredentials": "Ungültige Anmeldeinformationen", "downloadingMoreFiles": "Herunterladen weiterer Dateien", "copiedToClipboard": "In die Zwischenablage kopiert", "requriedFieldsCantBeMoved": "Erforderliches Feld kann nicht verschoben werden", "updateNotAllowedWithoutPK": "Update nicht erlaubt für Tabelle ohne Primärschlüssel", "autoIncFieldNotEditable": "Das Feld für die automatische Erhöhung ist nicht editierbar", "editingPKnotSupported": "Bearbeiten des Primärschlüssels nicht unterstützt", "deletedCache": "Cache erfolgreich gelöscht", "cacheEmpty": "Cache ist leer", "exportedCache": "Cache erfolgreich exportiert", "valueAlreadyInList": "Dieser Wert ist bereits in der Liste vorhanden", "noColumnsToUpdate": "Keine Spalten zu aktualisieren", "tableDeleted": "Tabelle erfolgreich gelöscht", "generatePublicShareableReadonlyBase": "Öffentlich lesbare Basis generieren", "deleteViewConfirmation": "Sind Sie sicher, dass Sie diese Ansicht löschen möchten?", "deleteTableConfirmation": "Möchten Sie die Tabelle löschen", "showM2mTables": "M2M Tabellen anzeigen", "showM2mTablesDesc": "Many-to-many relation is supported via a junction table & is hidden by default. Enable this option to list all such tables along with existing tables.", "showNullInCells": "Show NULL in Cells", "showNullInCellsDesc": "Display 'NULL' tag in cells holding NULL value. This helps differentiate against cells holding EMPTY string.", "showNullAndEmptyInFilter": "Show NULL and EMPTY in Filter", "showNullAndEmptyInFilterDesc": "Enable 'additional' filters to differentiate fields containing NULL & Empty Strings. Default support for Blank treats both NULL & Empty strings alike.", "deleteKanbanStackConfirmation": "Wenn Sie diesen Stapel löschen, wird auch die Auswahloption \"{stackToBeDeleted}\" von der Seite \"{groupingField}\" entfernt. Die Datensätze werden in den nicht kategorisierten Stapel verschoben.", "computedFieldEditWarning": "Berechnetes Feld: Der Inhalt ist schreibgeschützt. Verwenden Sie das Menü \"Spalten bearbeiten\", um das Feld neu zu konfigurieren.", "computedFieldDeleteWarning": "Berechnetes Feld: Inhalt ist schreibgeschützt. Inhalt kann nicht gelöscht werden.", "noMoreRecords": "Keine weiteren Aufzeichnungen" }, "error": { "searchProject": "Ihre Suche nach {search} fand keine Ergebnisse", "invalidChar": "Ungültiges Zeichen im Ordnerpfad.", "invalidDbCredentials": "Ungültige Datenbankanmeldeinformationen.", "unableToConnectToDb": "Es kann keine Verbindung zur Datenbank hergestellt werden, bitte überprüfen Sie Ihre Datenbank.", "userDoesntHaveSufficientPermission": "Den Benutzer gibt es nicht oder er hat keine ausreichenden Rechte, um das Schema zu erstellen.", "dbConnectionStatus": "Ungültige Datenbankparameter", "dbConnectionFailed": "Verbindungsfehler:", "signUpRules": { "emailReqd": "E-Mail ist erforderlich", "emailInvalid": "Email muß gültig sein", "passwdRequired": "Passwort ist erforderlich", "passwdLength": "Ihr Passwort muß mindestens 8 Zeichen haben", "passwdMismatch": "Passwörter stimmen nicht überein", "completeRuleSet": "Mindestens 8 Zeichen mit einem Großbuchstaben, einer Zahl und einem Sonderzeichen", "atLeast8Char": "Mindestens 8 Zeichen", "atLeastOneUppercase": "Ein Großbuchstaben", "atLeastOneNumber": "Eine Nummer", "atLeastOneSpecialChar": "Ein Sonderzeichen", "allowedSpecialCharList": "Erlaubte Sonderzeichenliste" }, "invalidURL": "Ungültige URL", "invalidEmail": "Invalid Email", "internalError": "Interner Fehler aufgetreten", "templateGeneratorNotFound": "Template-Generator kann nicht gefunden werden!", "fileUploadFailed": "Fehler beim Hochladen der Datei", "primaryColumnUpdateFailed": "Aktualisierung der Primärspalte fehlgeschlagen", "formDescriptionTooLong": "Daten zu lang für Formular Beschreibung", "columnsRequired": "Die folgenden Spalten sind erforderlich", "selectAtleastOneColumn": "Mindestens eine Spalte muss ausgewählt werden", "columnDescriptionNotFound": "Kann die Zielspalte nicht finden für", "duplicateMappingFound": "Doppelte Zuordnung gefunden, bitte entfernen Sie eine der Zuordnungen", "nullValueViolatesNotNull": "Nullwert verstößt gegen Nicht-Null-Beschränkung", "sourceHasInvalidNumbers": "Quelldaten enthalten einige ungültige Zahlen", "sourceHasInvalidBoolean": "Quelldaten enthalten einige ungültige boolesche Werte", "invalidForm": "Ungültiges Formular", "formValidationFailed": "Formularüberprüfung fehlgeschlagen", "youHaveBeenSignedOut": "Sie sind abgemeldet worden", "failedToLoadList": "Liste konnte nicht geladen werden", "failedToLoadChildrenList": "Liste der Kinder konnte nicht geladen werden", "deleteFailed": "Löschen fehlgeschlagen", "unlinkFailed": "Unlink fehlgeschlagen", "rowUpdateFailed": "Zeilenaktualisierung fehlgeschlagen", "deleteRowFailed": "Fehler beim Löschen der Zeile", "setFormDataFailed": "Formulardaten konnten nicht gesetzt werden", "formViewUpdateFailed": "Fehler beim Aktualisieren der Formularansicht", "tableNameRequired": "Tabellenname ist erforderlich", "nameShouldStartWithAnAlphabetOr_": "Name muss mit einem Buchstaben oder _ beginnen", "followingCharactersAreNotAllowed": "Folgende Zeichen sind nicht erlaubt", "columnNameRequired": "Spaltenname ist erforderlich", "columnNameExceedsCharacters": "The length of column name exceeds the max {value} characters", "projectNameExceeds50Characters": "Projektname überschreitet 50 Zeichen", "projectNameCannotStartWithSpace": "Projektname darf nicht mit einem Leerzeichen beginnen", "requiredField": "Pflichtfeld", "ipNotAllowed": "IP nicht erlaubt", "targetFileIsNotAnAcceptedFileType": "Zieldatei ist kein akzeptierter Dateityp", "theAcceptedFileTypeIsCsv": "Der akzeptierte Dateityp ist .csv", "theAcceptedFileTypesAreXlsXlsxXlsmOdsOts": "Die akzeptierten Dateitypen sind .xls, .xlsx, .xlsm, .ods, .ots", "parameterKeyCannotBeEmpty": "Parameterschlüssel darf nicht leer sein", "duplicateParameterKeysAreNotAllowed": "Doppelte Parameterschlüssel sind nicht erlaubt", "fieldRequired": "{value} kann nicht leer sein.", "projectNotAccessible": "Projekt nicht zugänglich", "copyToClipboardError": "Kopieren in die Zwischenablage fehlgeschlagen" }, "toast": { "exportMetadata": "Projektmetadaten erfolgreich exportiert", "importMetadata": "Projektmetadaten erfolgreich importiert", "clearMetadata": "Projektmetadaten erfolgreich gelöscht", "stopProject": "Projekt wurde erfolgreich gestoppt", "startProject": "Projekt erfolgreich gestartet", "restartProject": "Projekt neu gestartet", "deleteProject": "Projekt erfolgreich gelöscht", "authToken": "Auth-Token in die Zwischenablage kopiert", "projInfo": "Projektinformationen in die Zwischenablage kopiert", "inviteUrlCopy": "Einladungs-URL in die Zwischenablage kopiert", "createView": "Ansicht erfolgreich erstellt", "formEmailSMTP": "Bitte aktivieren Sie das SMTP-Plug-In im App-Store, um die E-Mail-Benachrichtigung zu aktivieren", "collabView": "Erfolgreich auf die kollaborative Ansicht gewechselt", "lockedView": "Erfolgreich auf gesperrte Ansicht gewechselt", "futureRelease": "Kommt bald!" }, "success": { "columnDuplicated": "Spalte erfolgreich dupliziert", "rowDuplicatedWithoutSavedYet": "Row duplicated (not saved)", "updatedUIACL": "UI ACL für Tabellen erfolgreich aktualisiert", "pluginUninstalled": "Plugin erfolgreich deinstalliert", "pluginSettingsSaved": "Plugin-Einstellungen erfolgreich gespeichert", "pluginTested": "Plugin-Einstellungen erfolgreich getestet", "tableRenamed": "Tabelle erfolgreich umbenannt", "viewDeleted": "Ansicht erfolgreich gelöscht", "primaryColumnUpdated": "Erfolgreich als Primärspalte aktualisiert", "tableDataExported": "Erfolgreich alle Tabellendaten exportiert", "updated": "Erfolgreich aktualisiert", "sharedViewDeleted": "Gemeinsame Ansicht erfolgreich gelöscht", "userDeleted": "Benutzer erfolgreich gelöscht", "viewRenamed": "Ansicht erfolgreich umbenannt", "tokenGenerated": "Token erfolgreich generiert", "tokenDeleted": "Token erfolgreich gelöscht", "userAddedToProject": "Benutzer erfolgreich zum Projekt hinzugefügt", "userAdded": "Erfolgreich hinzugefügter Benutzer", "userDeletedFromProject": "Benutzer erfolgreich aus dem Projekt gelöscht", "inviteEmailSent": "Einladungs-E-Mail erfolgreich gesendet", "inviteURLCopied": "Einladungslink wurde in Zwischenablage kopiert", "commentCopied": "Comment copied to clipboard", "passwordResetURLCopied": "URL zum Zurücksetzen des Passworts in die Zwischenablage kopiert", "shareableURLCopied": "Kopieren Sie die Basis-URL für die Freigabe in die Zwischenablage!", "embeddableHTMLCodeCopied": "Kopierter, einbettbarer HTML-Code!", "userDetailsUpdated": "Benutzerdaten erfolgreich aktualisiert", "tableDataImported": "Erfolgreich importierte Tabellendaten", "webhookUpdated": "Webhook-Details erfolgreich aktualisiert", "webhookDeleted": "Haken erfolgreich gelöscht", "webhookTested": "Webhook erfolgreich getestet", "columnUpdated": "Spalte aktualisiert", "columnCreated": "Spalte erstellt", "passwordChanged": "Kennwort erfolgreich geändert. Bitte melden Sie sich erneut an.", "settingsSaved": "Einstellungen erfolgreich gespeichert", "roleUpdated": "Rolle erfolgreich aktualisiert" } } }
packages/nc-gui/lang/de.json
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00017733579443302006, 0.00017200384172610939, 0.00016350414080079645, 0.00017275710706599057, 0.0000030182907266862458 ]
{ "id": 9, "code_window": [ " <LazySmartsheetDivDataCell\n", " v-if=\"col.title\"\n", " :ref=\"i ? null : (el: any) => (cellWrapperEl = el)\"\n", " class=\"!bg-white rounded-lg !w-[20rem] border-1 overflow-hidden border-gray-200 px-1 min-h-[35px] flex items-center relative\"\n", " >\n", " <LazySmartsheetVirtualCell\n", " v-if=\"isVirtualCol(col)\"\n", " v-model=\"_row.row[col.title]\"\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " class=\"!bg-white rounded-lg !w-[20rem] border-1 overflow-hidden border-gray-200 px-1 sm:min-h-[35px] xs:min-h-13 flex items-center relative\"\n" ], "file_path": "packages/nc-gui/components/smartsheet/expanded-form/index.vue", "type": "replace", "edit_start_line_idx": 676 }
charts/ Chart.lock
charts/nocodb/.gitignore
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00016813412366900593, 0.00016813412366900593, 0.00016813412366900593, 0.00016813412366900593, 0 ]
{ "id": 10, "code_window": [ "\n", ".nc-drawer-expanded-form .nc-modal {\n", " @apply !p-0;\n", "}\n", "</style>\n" ], "labels": [ "keep", "keep", "keep", "keep", "add" ], "after_edit": [ "\n", "<style lang=\"scss\" scoped>\n", ":deep(.ant-select-selector) {\n", " @apply !xs:(h-full);\n", "}\n", "\n", ":deep(.ant-select-selection-item) {\n", " @apply !xs:(mt-1.75 ml-1);\n", "}\n", "</style>" ], "file_path": "packages/nc-gui/components/smartsheet/expanded-form/index.vue", "type": "add", "edit_start_line_idx": 827 }
<script lang="ts" setup> import { onUnmounted } from '@vue/runtime-core' import { message } from 'ant-design-vue' import tinycolor from 'tinycolor2' import type { Select as AntSelect } from 'ant-design-vue' import type { SelectOptionType } from 'nocodb-sdk' import { ActiveCellInj, CellClickHookInj, ColumnInj, EditColumnInj, EditModeInj, IsFormInj, IsKanbanInj, ReadonlyInj, computed, enumColor, extractSdkResponseErrorMsg, iconMap, inject, isDrawerOrModalExist, ref, useBase, useEventListener, useRoles, useSelectedCellKeyupListener, watch, } from '#imports' interface Props { modelValue?: string | undefined rowIndex?: number disableOptionCreation?: boolean } const { modelValue, disableOptionCreation } = defineProps<Props>() const emit = defineEmits(['update:modelValue']) const column = inject(ColumnInj)! const readOnly = inject(ReadonlyInj)! const isLockedMode = inject(IsLockedInj, ref(false)) const isEditable = inject(EditModeInj, ref(false)) const activeCell = inject(ActiveCellInj, ref(false)) // use both ActiveCellInj or EditModeInj to determine the active state // since active will be false in case of form view const active = computed(() => activeCell.value || isEditable.value) const aselect = ref<typeof AntSelect>() const isOpen = ref(false) const isKanban = inject(IsKanbanInj, ref(false)) const isPublic = inject(IsPublicInj, ref(false)) const isEditColumn = inject(EditColumnInj, ref(false)) const isForm = inject(IsFormInj, ref(false)) const { $api } = useNuxtApp() const searchVal = ref() const { getMeta } = useMetas() const { isUIAllowed } = useRoles() const { isPg, isMysql } = useBase() // a variable to keep newly created option value // temporary until it's add the option to column meta const tempSelectedOptState = ref<string>() const isNewOptionCreateEnabled = computed(() => !isPublic.value && !disableOptionCreation && isUIAllowed('fieldEdit')) const options = computed<(SelectOptionType & { value: string })[]>(() => { if (column?.value.colOptions) { const opts = column.value.colOptions ? // todo: fix colOptions type, options does not exist as a property (column.value.colOptions as any).options.filter((el: SelectOptionType) => el.title !== '') || [] : [] for (const op of opts.filter((el: any) => el.order === null)) { op.title = op.title.replace(/^'/, '').replace(/'$/, '') } return opts.map((o: any) => ({ ...o, value: o.title })) } return [] }) const isOptionMissing = computed(() => { return (options.value ?? []).every((op) => op.title !== searchVal.value) }) const hasEditRoles = computed(() => isUIAllowed('dataEdit')) const editAllowed = computed(() => (hasEditRoles.value || isForm.value) && active.value) const vModel = computed({ get: () => tempSelectedOptState.value ?? modelValue?.trim(), set: (val) => { if (val && isNewOptionCreateEnabled.value && (options.value ?? []).every((op) => op.title !== val)) { tempSelectedOptState.value = val return addIfMissingAndSave() } emit('update:modelValue', val || null) }, }) watch(isOpen, (n, _o) => { if (editAllowed.value) { if (!n) { aselect.value?.$el?.querySelector('input')?.blur() } else { aselect.value?.$el?.querySelector('input')?.focus() } } }) useSelectedCellKeyupListener(activeCell, (e) => { switch (e.key) { case 'Escape': isOpen.value = false break case 'Enter': if (editAllowed.value && active.value && !isOpen.value) { isOpen.value = true } break // skip space bar key press since it's used for expand row case ' ': break default: if (!editAllowed.value) { e.preventDefault() break } // toggle only if char key pressed if (!(e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) && e.key?.length === 1 && !isDrawerOrModalExist()) { e.stopPropagation() isOpen.value = true } break } }) // close dropdown list on escape useSelectedCellKeyupListener(isOpen, (e) => { if (e.key === 'Escape') isOpen.value = false }) async function addIfMissingAndSave() { if (!tempSelectedOptState.value || isPublic.value) return false const newOptValue = tempSelectedOptState.value searchVal.value = '' tempSelectedOptState.value = undefined if (newOptValue && !options.value.some((o) => o.title === newOptValue)) { try { options.value.push({ title: newOptValue, value: newOptValue, color: enumColor.light[(options.value.length + 1) % enumColor.light.length], }) column.value.colOptions = { options: options.value.map(({ value: _, ...rest }) => rest) } const updatedColMeta = { ...column.value } // todo: refactor and avoid repetition if (updatedColMeta.cdf) { // Postgres returns default value wrapped with single quotes & casted with type so we have to get value between single quotes to keep it unified for all databases if (isPg(column.value.source_id)) { updatedColMeta.cdf = updatedColMeta.cdf.substring( updatedColMeta.cdf.indexOf(`'`) + 1, updatedColMeta.cdf.lastIndexOf(`'`), ) } // Mysql escapes single quotes with backslash so we keep quotes but others have to unescaped if (!isMysql(column.value.source_id) && !isPg(column.value.source_id)) { updatedColMeta.cdf = updatedColMeta.cdf.replace(/''/g, "'") } } await $api.dbTableColumn.update( (column.value as { fk_column_id?: string })?.fk_column_id || (column.value?.id as string), updatedColMeta, ) vModel.value = newOptValue await getMeta(column.value.fk_model_id!, true) } catch (e: any) { console.log(e) message.error(await extractSdkResponseErrorMsg(e)) } } } const search = () => { searchVal.value = aselect.value?.$el?.querySelector('.ant-select-selection-search-input')?.value } // prevent propagation of keydown event if select is open const onKeydown = (e: KeyboardEvent) => { if (isOpen.value && active.value) { e.stopPropagation() } if (e.key === 'Enter') { e.stopPropagation() } } const onSelect = () => { isOpen.value = false isEditable.value = false } const cellClickHook = inject(CellClickHookInj, null) const toggleMenu = (e: Event) => { // todo: refactor // check clicked element is clear icon if ( (e.target as HTMLElement)?.classList.contains('ant-select-clear') || (e.target as HTMLElement)?.closest('.ant-select-clear') ) { vModel.value = '' return e.stopPropagation() } if (cellClickHook) return isOpen.value = editAllowed.value && !isOpen.value } const cellClickHookHandler = () => { isOpen.value = editAllowed.value && !isOpen.value } onMounted(() => { cellClickHook?.on(cellClickHookHandler) }) onUnmounted(() => { cellClickHook?.on(cellClickHookHandler) }) const handleClose = (e: MouseEvent) => { if (isOpen.value && aselect.value && !aselect.value.$el.contains(e.target)) { isOpen.value = false } } useEventListener(document, 'click', handleClose, true) const selectedOpt = computed(() => { return options.value.find((o) => o.value === vModel.value) }) </script> <template> <div class="h-full w-full flex items-center nc-single-select" :class="{ 'read-only': readOnly || isLockedMode }" @click="toggleMenu" > <div v-if="!(active || isEditable)"> <a-tag v-if="selectedOpt" class="rounded-tag" :color="selectedOpt.color"> <span :style="{ 'color': tinycolor.isReadable(selectedOpt.color || '#ccc', '#fff', { level: 'AA', size: 'large' }) ? '#fff' : tinycolor.mostReadable(selectedOpt.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '13px', }" :class="{ 'text-sm': isKanban }" > {{ selectedOpt.title }} </span> </a-tag> </div> <a-select v-else ref="aselect" v-model:value="vModel" class="w-full overflow-hidden" :class="{ 'caret-transparent': !hasEditRoles }" :placeholder="isEditColumn ? $t('labels.optional') : ''" :allow-clear="!column.rqd && editAllowed" :bordered="false" :open="isOpen && editAllowed" :disabled="readOnly || !editAllowed || isLockedMode" :show-arrow="hasEditRoles && !(readOnly || isLockedMode) && active && vModel === null" :dropdown-class-name="`nc-dropdown-single-select-cell ${isOpen && active ? 'active' : ''}`" :show-search="isOpen && active" @select="onSelect" @keydown="onKeydown($event)" @search="search" > <a-select-option v-for="op of options" :key="op.title" :value="op.title" :data-testid="`select-option-${column.title}-${rowIndex}`" :class="`nc-select-option-${column.title}-${op.title}`" @click.stop > <a-tag class="rounded-tag" :color="op.color"> <span :style="{ 'color': tinycolor.isReadable(op.color || '#ccc', '#fff', { level: 'AA', size: 'large' }) ? '#fff' : tinycolor.mostReadable(op.color || '#ccc', ['#0b1d05', '#fff']).toHex8String(), 'font-size': '13px', }" :class="{ 'text-sm': isKanban }" > {{ op.title }} </span> </a-tag> </a-select-option> <a-select-option v-if="searchVal && isOptionMissing && isNewOptionCreateEnabled" :key="searchVal" :value="searchVal"> <div class="flex gap-2 text-gray-500 items-center h-full"> <component :is="iconMap.plusThick" class="min-w-4" /> <div class="text-xs whitespace-normal"> {{ $t('msg.selectOption.createNewOptionNamed') }} <strong>{{ searchVal }}</strong> </div> </div> </a-select-option> </a-select> </div> </template> <style scoped lang="scss"> .rounded-tag { @apply py-0 px-[12px] rounded-[12px]; } :deep(.ant-tag) { @apply "rounded-tag" my-[2px]; } :deep(.ant-select-clear) { opacity: 1; } .nc-single-select:not(.read-only) { :deep(.ant-select-selector), :deep(.ant-select-selector input) { @apply !cursor-pointer; } } :deep(.ant-select-selector) { @apply !px-0; } :deep(.ant-select-selection-search-input) { @apply !text-xs; } :deep(.ant-select-clear > span) { @apply block; } </style>
packages/nc-gui/components/cell/SingleSelect.vue
1
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.0006115862634032965, 0.000183630982064642, 0.00016563334793318063, 0.00017002715321723372, 0.00007171630568336695 ]
{ "id": 10, "code_window": [ "\n", ".nc-drawer-expanded-form .nc-modal {\n", " @apply !p-0;\n", "}\n", "</style>\n" ], "labels": [ "keep", "keep", "keep", "keep", "add" ], "after_edit": [ "\n", "<style lang=\"scss\" scoped>\n", ":deep(.ant-select-selector) {\n", " @apply !xs:(h-full);\n", "}\n", "\n", ":deep(.ant-select-selection-item) {\n", " @apply !xs:(mt-1.75 ml-1);\n", "}\n", "</style>" ], "file_path": "packages/nc-gui/components/smartsheet/expanded-form/index.vue", "type": "add", "edit_start_line_idx": 827 }
import { Test } from '@nestjs/testing'; import { OrgTokensService } from '../services/org-tokens.service'; import { OrgTokensController } from './org-tokens.controller'; import type { TestingModule } from '@nestjs/testing'; describe('OrgTokensController', () => { let controller: OrgTokensController; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ controllers: [OrgTokensController], providers: [OrgTokensService], }).compile(); controller = module.get<OrgTokensController>(OrgTokensController); }); it('should be defined', () => { expect(controller).toBeDefined(); }); });
packages/nocodb/src/controllers/org-tokens.controller.spec.ts
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00017896396457217634, 0.00017512957856524736, 0.00017266126815229654, 0.00017376351752318442, 0.000002748405222519068 ]
{ "id": 10, "code_window": [ "\n", ".nc-drawer-expanded-form .nc-modal {\n", " @apply !p-0;\n", "}\n", "</style>\n" ], "labels": [ "keep", "keep", "keep", "keep", "add" ], "after_edit": [ "\n", "<style lang=\"scss\" scoped>\n", ":deep(.ant-select-selector) {\n", " @apply !xs:(h-full);\n", "}\n", "\n", ":deep(.ant-select-selection-item) {\n", " @apply !xs:(mt-1.75 ml-1);\n", "}\n", "</style>" ], "file_path": "packages/nc-gui/components/smartsheet/expanded-form/index.vue", "type": "add", "edit_start_line_idx": 827 }
// import ses from '../../v1-legacy/plugins/ses'; import type { Knex } from 'knex'; import { MetaTable, MetaTableOldV2 } from '~/utils/globals'; const up = async (knex: Knex) => { console.time( `Removed foreign keys and created index for columns in '${MetaTableOldV2.BASES}'`, ); await knex.schema.alterTable(MetaTableOldV2.BASES, (table) => { table.dropForeign('project_id'); table.index('project_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTableOldV2.BASES}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.MODELS}'`, ); await knex.schema.alterTable(MetaTable.MODELS, (table) => { table.dropForeign('base_id'); table.index('base_id'); table.dropForeign('project_id'); table.index('project_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.MODELS}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.COLUMNS}'`, ); await knex.schema.alterTable(MetaTable.COLUMNS, (table) => { table.dropForeign('fk_model_id'); table.index('fk_model_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.COLUMNS}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.COL_RELATIONS}'`, ); await knex.schema.alterTable(MetaTable.COL_RELATIONS, (table) => { table.dropForeign('fk_column_id'); table.index('fk_column_id'); table.dropForeign('fk_related_model_id'); table.index('fk_related_model_id'); table.dropForeign('fk_child_column_id'); table.index('fk_child_column_id'); table.dropForeign('fk_parent_column_id'); table.index('fk_parent_column_id'); table.dropForeign('fk_mm_model_id'); table.index('fk_mm_model_id'); table.dropForeign('fk_mm_child_column_id'); table.index('fk_mm_child_column_id'); table.dropForeign('fk_mm_parent_column_id'); table.index('fk_mm_parent_column_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.COL_RELATIONS}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.COL_SELECT_OPTIONS}'`, ); await knex.schema.alterTable(MetaTable.COL_SELECT_OPTIONS, (table) => { table.dropForeign('fk_column_id'); table.index('fk_column_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.COL_SELECT_OPTIONS}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.COL_LOOKUP}'`, ); await knex.schema.alterTable(MetaTable.COL_LOOKUP, (table) => { table.dropForeign('fk_column_id'); table.index('fk_column_id'); table.dropForeign('fk_relation_column_id'); table.index('fk_relation_column_id'); table.dropForeign('fk_lookup_column_id'); table.index('fk_lookup_column_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.COL_LOOKUP}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.COL_QRCODE}'`, ); await knex.schema.alterTable(MetaTable.COL_QRCODE, (table) => { table.dropForeign('fk_column_id'); table.index('fk_column_id'); table.dropForeign('fk_qr_value_column_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.COL_QRCODE}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.COL_BARCODE}'`, ); await knex.schema.alterTable(MetaTable.COL_BARCODE, (table) => { table.dropForeign('fk_column_id'); table.index('fk_column_id'); table.dropForeign('fk_barcode_value_column_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.COL_BARCODE}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.COL_FORMULA}'`, ); await knex.schema.alterTable(MetaTable.COL_FORMULA, (table) => { table.dropForeign('fk_column_id'); table.index('fk_column_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.COL_FORMULA}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.COL_ROLLUP}'`, ); await knex.schema.alterTable(MetaTable.COL_ROLLUP, (table) => { table.dropForeign('fk_column_id'); table.index('fk_column_id'); table.dropForeign('fk_relation_column_id'); table.index('fk_relation_column_id'); table.dropForeign('fk_rollup_column_id'); table.index('fk_rollup_column_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.COL_ROLLUP}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.VIEWS}'`, ); await knex.schema.alterTable(MetaTable.VIEWS, (table) => { table.dropForeign('fk_model_id'); table.index('fk_model_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.VIEWS}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.HOOKS}'`, ); await knex.schema.alterTable(MetaTable.HOOKS, (table) => { table.dropForeign('fk_model_id'); table.index('fk_model_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.HOOKS}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.FILTER_EXP}'`, ); await knex.schema.alterTable(MetaTable.FILTER_EXP, (table) => { table.dropForeign('fk_view_id'); table.index('fk_view_id'); table.dropForeign('fk_hook_id'); table.index('fk_hook_id'); table.dropForeign('fk_column_id'); table.index('fk_column_id'); table.dropForeign('fk_parent_id'); table.index('fk_parent_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.FILTER_EXP}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.SORT}'`, ); await knex.schema.alterTable(MetaTable.SORT, (table) => { table.dropForeign('fk_view_id'); table.index('fk_view_id'); table.dropForeign('fk_column_id'); table.index('fk_column_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.SORT}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.SHARED_VIEWS}'`, ); await knex.schema.alterTable(MetaTable.SHARED_VIEWS, (table) => { table.dropForeign('fk_view_id'); table.index('fk_view_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.SHARED_VIEWS}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.FORM_VIEW}'`, ); await knex.schema.alterTable(MetaTable.FORM_VIEW, (table) => { table.dropForeign('fk_view_id'); table.index('fk_view_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.FORM_VIEW}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.FORM_VIEW_COLUMNS}'`, ); await knex.schema.alterTable(MetaTable.FORM_VIEW_COLUMNS, (table) => { table.dropForeign('fk_view_id'); table.index('fk_view_id'); table.dropForeign('fk_column_id'); table.index('fk_column_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.FORM_VIEW_COLUMNS}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.GALLERY_VIEW}'`, ); await knex.schema.alterTable(MetaTable.GALLERY_VIEW, (table) => { table.dropForeign('fk_view_id'); table.index('fk_view_id'); table.dropForeign('fk_cover_image_col_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.GALLERY_VIEW}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.GALLERY_VIEW_COLUMNS}'`, ); await knex.schema.alterTable(MetaTable.GALLERY_VIEW_COLUMNS, (table) => { table.dropForeign('fk_view_id'); table.index('fk_view_id'); table.dropForeign('fk_column_id'); table.index('fk_column_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.GALLERY_VIEW_COLUMNS}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.GRID_VIEW}'`, ); await knex.schema.alterTable(MetaTable.GRID_VIEW, (table) => { table.dropForeign('fk_view_id'); table.index('fk_view_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.GRID_VIEW}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.GRID_VIEW_COLUMNS}'`, ); await knex.schema.alterTable(MetaTable.GRID_VIEW_COLUMNS, (table) => { table.dropForeign('fk_view_id'); table.index('fk_view_id'); table.dropForeign('fk_column_id'); table.index('fk_column_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.GRID_VIEW_COLUMNS}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.MAP_VIEW}'`, ); await knex.schema.alterTable(MetaTable.MAP_VIEW, (table) => { table.dropForeign('fk_view_id'); table.index('fk_view_id'); table.dropForeign('fk_geo_data_col_id'); table.index('fk_geo_data_col_id'); table.dropForeign('base_id'); table.dropForeign('project_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.MAP_VIEW}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.MAP_VIEW_COLUMNS}'`, ); await knex.schema.alterTable(MetaTable.MAP_VIEW_COLUMNS, (table) => { table.dropForeign('fk_view_id'); table.index('fk_view_id'); table.dropForeign('fk_column_id'); table.index('fk_column_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.MAP_VIEW_COLUMNS}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.KANBAN_VIEW}'`, ); await knex.schema.alterTable(MetaTable.KANBAN_VIEW, (table) => { table.dropForeign('fk_view_id'); table.index('fk_view_id'); table.dropForeign('fk_grp_col_id'); table.index('fk_grp_col_id'); table.dropForeign('fk_cover_image_col_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.KANBAN_VIEW}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.KANBAN_VIEW_COLUMNS}'`, ); await knex.schema.alterTable(MetaTable.KANBAN_VIEW_COLUMNS, (table) => { table.dropForeign('fk_view_id'); table.index('fk_view_id'); table.dropForeign('fk_column_id'); table.index('fk_column_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.KANBAN_VIEW_COLUMNS}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTableOldV2.PROJECT_USERS}'`, ); await knex.schema.alterTable(MetaTableOldV2.PROJECT_USERS, (table) => { table.dropForeign('project_id'); table.index('project_id'); table.dropForeign('fk_user_id'); table.index('fk_user_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTableOldV2.PROJECT_USERS}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.AUDIT}'`, ); await knex.schema.alterTable(MetaTable.AUDIT, (table) => { table.dropForeign('project_id'); table.index('project_id'); table.dropForeign('fk_model_id'); table.index('fk_model_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.AUDIT}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.MODEL_ROLE_VISIBILITY}'`, ); await knex.schema.alterTable(MetaTable.MODEL_ROLE_VISIBILITY, (table) => { table.dropForeign('fk_view_id'); table.index('fk_view_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.MODEL_ROLE_VISIBILITY}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.SYNC_SOURCE}'`, ); await knex.schema.alterTable(MetaTable.SYNC_SOURCE, (table) => { table.dropForeign('project_id'); table.index('project_id'); table.dropForeign('base_id'); table.index('base_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.SYNC_SOURCE}'`, ); console.time( `Removed foreign keys and created index for columns in '${MetaTable.API_TOKENS}'`, ); await knex.schema.alterTable(MetaTable.API_TOKENS, (table) => { table.dropForeign('fk_user_id'); table.index('fk_user_id'); }); console.timeEnd( `Removed foreign keys and created index for columns in '${MetaTable.API_TOKENS}'`, ); }; const down = async (knex: Knex) => { await knex.schema.alterTable(MetaTableOldV2.BASES, (table) => { table.foreign('project_id').references(`${MetaTableOldV2.PROJECT}.id`); }); await knex.schema.alterTable(MetaTable.MODELS, (table) => { table.foreign('base_id').references(`${MetaTableOldV2.BASES}.id`); table.foreign('project_id').references(`${MetaTableOldV2.PROJECT}.id`); }); await knex.schema.alterTable(MetaTable.COLUMNS, (table) => { table.foreign('fk_model_id').references(`${MetaTable.MODELS}.id`); }); await knex.schema.alterTable(MetaTable.COL_RELATIONS, (table) => { table.foreign('fk_column_id').references(`${MetaTable.COLUMNS}.id`); table.foreign('fk_related_model_id').references(`${MetaTable.MODELS}.id`); table.foreign('fk_child_column_id').references(`${MetaTable.COLUMNS}.id`); table.foreign('fk_parent_column_id').references(`${MetaTable.COLUMNS}.id`); table.foreign('fk_mm_model_id').references(`${MetaTable.MODELS}.id`); table .foreign('fk_mm_child_column_id') .references(`${MetaTable.COLUMNS}.id`); table .foreign('fk_mm_parent_column_id') .references(`${MetaTable.COLUMNS}.id`); }); await knex.schema.alterTable(MetaTable.COL_SELECT_OPTIONS, (table) => { table.foreign('fk_column_id').references(`${MetaTable.COLUMNS}.id`); }); await knex.schema.alterTable(MetaTable.COL_LOOKUP, (table) => { table.foreign('fk_column_id').references(`${MetaTable.COLUMNS}.id`); table .foreign('fk_relation_column_id') .references(`${MetaTable.COLUMNS}.id`); table.foreign('fk_lookup_column_id').references(`${MetaTable.COLUMNS}.id`); }); await knex.schema.alterTable(MetaTable.COL_ROLLUP, (table) => { table.foreign('fk_column_id').references(`${MetaTable.COLUMNS}.id`); table .foreign('fk_relation_column_id') .references(`${MetaTable.COLUMNS}.id`); table.foreign('fk_rollup_column_id').references(`${MetaTable.COLUMNS}.id`); }); await knex.schema.alterTable(MetaTable.COL_QRCODE, (table) => { table.foreign('fk_column_id').references(`${MetaTable.COLUMNS}.id`); table .foreign('fk_qr_value_column_id') .references(`${MetaTable.COLUMNS}.id`); }); await knex.schema.alterTable(MetaTable.COL_BARCODE, (table) => { table.foreign('fk_column_id').references(`${MetaTable.COLUMNS}.id`); table .foreign('fk_barcode_value_column_id') .references(`${MetaTable.COLUMNS}.id`); }); await knex.schema.alterTable(MetaTable.COL_FORMULA, (table) => { table.foreign('fk_column_id').references(`${MetaTable.COLUMNS}.id`); }); await knex.schema.alterTable(MetaTable.VIEWS, (table) => { table.foreign('fk_model_id').references(`${MetaTable.MODELS}.id`); }); await knex.schema.alterTable(MetaTable.HOOKS, (table) => { table.foreign('fk_model_id').references(`${MetaTable.MODELS}.id`); }); await knex.schema.alterTable(MetaTable.FILTER_EXP, (table) => { table.foreign('fk_view_id').references(`${MetaTable.VIEWS}.id`); table.foreign('fk_hook_id').references(`${MetaTable.HOOKS}.id`); table.foreign('fk_column_id').references(`${MetaTable.COLUMNS}.id`); table.foreign('fk_parent_id').references(`${MetaTable.FILTER_EXP}.id`); }); await knex.schema.alterTable(MetaTable.SORT, (table) => { table.foreign('fk_view_id').references(`${MetaTable.VIEWS}.id`); table.foreign('fk_column_id').references(`${MetaTable.COLUMNS}.id`); }); await knex.schema.alterTable(MetaTable.SHARED_VIEWS, (table) => { table.foreign('fk_view_id').references(`${MetaTable.VIEWS}.id`); }); await knex.schema.alterTable(MetaTable.FORM_VIEW, (table) => { table.foreign('fk_view_id').references(`${MetaTable.VIEWS}.id`); }); await knex.schema.alterTable(MetaTable.FORM_VIEW_COLUMNS, (table) => { table.foreign('fk_view_id').references(`${MetaTable.FORM_VIEW}.fk_view_id`); table.foreign('fk_column_id').references(`${MetaTable.COLUMNS}.id`); }); await knex.schema.alterTable(MetaTable.GALLERY_VIEW, (table) => { table.foreign('fk_view_id').references(`${MetaTable.VIEWS}.id`); table .foreign('fk_cover_image_col_id') .references(`${MetaTable.COLUMNS}.id`); }); await knex.schema.alterTable(MetaTable.GALLERY_VIEW_COLUMNS, (table) => { table .foreign('fk_view_id') .references(`${MetaTable.GALLERY_VIEW}.fk_view_id`); table.foreign('fk_column_id').references(`${MetaTable.COLUMNS}.id`); }); await knex.schema.alterTable(MetaTable.GRID_VIEW, (table) => { table.foreign('fk_view_id').references(`${MetaTable.VIEWS}.id`); }); await knex.schema.alterTable(MetaTable.GRID_VIEW_COLUMNS, (table) => { table.foreign('fk_view_id').references(`${MetaTable.GRID_VIEW}.fk_view_id`); table.foreign('fk_column_id').references(`${MetaTable.COLUMNS}.id`); }); await knex.schema.alterTable(MetaTable.MAP_VIEW, (table) => { table.string('fk_view_id', 20).primary(); table.foreign('fk_view_id').references(`${MetaTable.VIEWS}.id`); table.foreign('base_id').references(`${MetaTableOldV2.BASES}.id`); table.foreign('project_id').references(`${MetaTableOldV2.PROJECT}.id`); table.foreign('fk_geo_data_col_id').references(`${MetaTable.COLUMNS}.id`); }); await knex.schema.alterTable(MetaTable.MAP_VIEW_COLUMNS, (table) => { table.foreign('fk_view_id').references(`${MetaTable.MAP_VIEW}.fk_view_id`); table.foreign('fk_column_id').references(`${MetaTable.COLUMNS}.id`); }); await knex.schema.alterTable(MetaTable.KANBAN_VIEW, (table) => { table.foreign('fk_view_id').references(`${MetaTable.VIEWS}.id`); table.foreign('fk_grp_col_id').references(`${MetaTable.COLUMNS}.id`); table .foreign('fk_cover_image_col_id') .references(`${MetaTable.COLUMNS}.id`); }); await knex.schema.alterTable(MetaTable.KANBAN_VIEW_COLUMNS, (table) => { table .foreign('fk_view_id') .references(`${MetaTable.KANBAN_VIEW}.fk_view_id`); table.foreign('fk_column_id').references(`${MetaTable.COLUMNS}.id`); }); await knex.schema.alterTable(MetaTableOldV2.PROJECT_USERS, (table) => { table.foreign('project_id').references(`${MetaTableOldV2.PROJECT}.id`); table.foreign('fk_user_id').references(`${MetaTable.USERS}.id`); }); await knex.schema.alterTable(MetaTable.AUDIT, (table) => { table.foreign('project_id').references(`${MetaTableOldV2.PROJECT}.id`); table.foreign('fk_model_id').references(`${MetaTable.MODELS}.id`); }); await knex.schema.alterTable(MetaTable.MODEL_ROLE_VISIBILITY, (table) => { table.foreign('fk_view_id').references(`${MetaTable.VIEWS}.id`); }); await knex.schema.alterTable(MetaTable.SYNC_SOURCE, (table) => { table.foreign('project_id').references(`${MetaTableOldV2.PROJECT}.id`); }); await knex.schema.alterTable(MetaTable.API_TOKENS, (table) => { table.foreign('fk_user_id').references(`${MetaTable.USERS}.id`); table.foreign('base_id').references(`${MetaTableOldV2.BASES}.id`); }); }; export { up, down };
packages/nocodb/src/meta/migrations/v2/nc_031_remove_fk_and_add_idx.ts
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00017404624668415636, 0.00017072510672733188, 0.00016565577243454754, 0.0001713247038424015, 0.000001991423687286442 ]
{ "id": 10, "code_window": [ "\n", ".nc-drawer-expanded-form .nc-modal {\n", " @apply !p-0;\n", "}\n", "</style>\n" ], "labels": [ "keep", "keep", "keep", "keep", "add" ], "after_edit": [ "\n", "<style lang=\"scss\" scoped>\n", ":deep(.ant-select-selector) {\n", " @apply !xs:(h-full);\n", "}\n", "\n", ":deep(.ant-select-selection-item) {\n", " @apply !xs:(mt-1.75 ml-1);\n", "}\n", "</style>" ], "file_path": "packages/nc-gui/components/smartsheet/expanded-form/index.vue", "type": "add", "edit_start_line_idx": 827 }
<script lang="ts" setup> import { onKeyStroke } from '@vueuse/core' import type { CSSProperties } from '@vue/runtime-dom' import type { TooltipPlacement } from 'ant-design-vue/lib/tooltip' import { controlledRef, ref, useAttrs, useElementHover, watch } from '#imports' interface Props { // Key to be pressed on hover to trigger the tooltip modifierKey?: string tooltipStyle?: CSSProperties // force disable tooltip disabled?: boolean placement?: TooltipPlacement | undefined hideOnClick?: boolean overlayClassName?: string } const props = defineProps<Props>() const modifierKey = computed(() => props.modifierKey) const tooltipStyle = computed(() => props.tooltipStyle) const disabled = computed(() => props.disabled) const hideOnClick = computed(() => props.hideOnClick) const placement = computed(() => props.placement ?? 'top') const el = ref() const showTooltip = controlledRef(false, { onBeforeChange: (shouldShow) => { if (shouldShow && disabled.value) return false }, }) const isHovering = useElementHover(() => el.value) const attrs = useAttrs() const isKeyPressed = ref(false) const overlayClassName = computed(() => props.overlayClassName) onKeyStroke( (e) => e.key === modifierKey.value, (e) => { e.preventDefault() if (isHovering.value) { showTooltip.value = true } isKeyPressed.value = true }, { eventName: 'keydown' }, ) onKeyStroke( (e) => e.key === modifierKey.value, (e) => { e.preventDefault() showTooltip.value = false isKeyPressed.value = false }, { eventName: 'keyup' }, ) watch([isHovering, () => modifierKey.value, () => disabled.value], ([hovering, key, isDisabled]) => { if (!hovering || isDisabled) { showTooltip.value = false return } // Show tooltip on mouseover if no modifier key is provided if (hovering && !key) { showTooltip.value = true return } // While hovering if the modifier key was changed and the key is not pressed, hide tooltip if (hovering && key && !isKeyPressed.value) { showTooltip.value = false return } // When mouse leaves the element, then re-enters the element while key stays pressed, show the tooltip if (!showTooltip.value && hovering && key && isKeyPressed.value) { showTooltip.value = true } }) const divStyles = computed(() => ({ style: attrs.style as CSSProperties, class: attrs.class as string, })) const onClick = () => { if (hideOnClick.value && showTooltip.value) { showTooltip.value = false } } </script> <template> <a-tooltip v-model:visible="showTooltip" :overlay-class-name="`nc-tooltip ${showTooltip ? 'visible' : 'hidden'} ${overlayClassName}`" :overlay-style="tooltipStyle" arrow-point-at-center :trigger="[]" :placement="placement" > <template #title> <slot name="title" /> </template> <div ref="el" v-bind="divStyles" @mousedown="onClick"> <slot /> </div> </a-tooltip> </template> <style lang="scss"> .nc-tooltip.hidden { @apply invisible; } .nc-tooltip { .ant-tooltip-inner { @apply !px-2 !py-1 !rounded-lg !bg-gray-800; } .ant-tooltip-arrow-content { @apply !bg-gray-800; } } </style>
packages/nc-gui/components/nc/Tooltip.vue
0
https://github.com/nocodb/nocodb/commit/489a707aa84ae547a41539259f925169a2837df7
[ 0.00017654216208029538, 0.00017039339581970125, 0.00016621460963506252, 0.0001698253909125924, 0.00000275439788310905 ]
{ "id": 0, "code_window": [ " this._initContext();\n", "\n", " // empty all the old gl textures as they are useless now\n", " for (var key in utils.BaseTextureCache)\n", " {\n", " utils.BaseTextureCache[key]._glTextures = {};\n", " }\n", "};\n", "\n", "/**\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " utils.BaseTextureCache[key]._glTextures.length = 0;\n" ], "file_path": "src/core/renderers/webgl/WebGLRenderer.js", "type": "replace", "edit_start_line_idx": 370 }
var utils = require('../utils'), CONST = require('../const'); /** * A texture stores the information that represents an image. All textures have a base texture. * * @class * @mixes eventTarget * @namespace PIXI * @param source {Image|Canvas} the source object of the texture. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values */ function BaseTexture(source, scaleMode) { this.uuid = utils.uuid(); /** * The Resolution of the texture. * * @member {number} */ this.resolution = 1; /** * The width of the base texture set when the image has loaded * * @member {number} * @readOnly */ this.width = 100; /** * The height of the base texture set when the image has loaded * * @member {number} * @readOnly */ this.height = 100; /** * The scale mode to apply when scaling this texture * * @member {{number}} * @default scaleModes.LINEAR */ this.scaleMode = scaleMode || CONST.scaleModes.DEFAULT; /** * Set to true once the base texture has successfully loaded. * * This is never true if the underlying source fails to load or has no texture data. * * @member {boolean} * @readOnly */ this.hasLoaded = false; /** * Set to true if the source is currently loading. * * If an Image source is loading the 'loaded' or 'error' event will be * dispatched when the operation ends. An underyling source that is * immediately-available bypasses loading entirely. * * @member {boolean} * @readonly */ this.isLoading = false; /** * The image source that is used to create the texture. * * TODO: Make this a setter that calls loadSource(); * * @member {Image|Canvas} * @readonly */ this.source = null; // set in loadSource, if at all /** * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) * * @member {boolean} * @default true */ this.premultipliedAlpha = true; /** * @member {string} */ this.imageUrl = null; /** * @member {boolean} * @private */ this._powerOf2 = false; // used for webGL /** * * Set this to true if a mipmap of this texture needs to be generated. This value needs to be set before the texture is used * Also the texture must be a power of two size to work * * @member {boolean} */ this.mipmap = false; /** * A map of renderer IDs to webgl textures * * @member {object<number, WebGLTexture>} * @private */ this._glTextures = {}; // if no source passed don't try to load if (source) { this.loadSource(source); } /** * Fired when a not-immediately-available source finishes loading. * * @event loaded * @protected */ /** * Fired when a not-immediately-available source fails to load. * * @event error * @protected */ } BaseTexture.prototype.constructor = BaseTexture; module.exports = BaseTexture; utils.eventTarget.mixin(BaseTexture.prototype); /** * Updates the texture on all the webgl renderers. * * @fires update */ BaseTexture.prototype.update = function () { this.emit('update', this); }; /** * Load a source. * * If the source is not-immediately-available, such as an image that needs to be * downloaded, then the 'loaded' or 'error' event will be dispatched in the future * and `hasLoaded` will remain false after this call. * * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: * * if (texture.hasLoaded) { * // texture ready for use * } else if (texture.isLoading) { * // listen to 'loaded' and/or 'error' events on texture * } else { * // not loading, not going to load UNLESS the source is reloaded * // (it may still make sense to listen to the events) * } * * @protected * @param source {Image|Canvas} the source object of the texture. */ BaseTexture.prototype.loadSource = function (source) { var wasLoading = this.isLoading; this.hasLoaded = false; this.isLoading = false; if (wasLoading && this.source) { this.source.onload = null; this.source.onerror = null; } this.source = source; // Apply source if loaded. Otherwise setup appropriate loading monitors. if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) { this._sourceLoaded(); } else if (!source.getContext) { // Image fail / not ready this.isLoading = true; var scope = this; source.onload = function () { source.onload = null; source.onerror = null; if (!scope.isLoading) { return; } scope.isLoading = false; scope._sourceLoaded(); scope.emit('loaded', scope); }; source.onerror = function () { source.onload = null; source.onerror = null; if (!scope.isLoading) { return; } scope.isLoading = false; scope.emit('error', scope); }; // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element // "The value of `complete` can thus change while a script is executing." // So complete needs to be re-checked after the callbacks have been added.. // NOTE: complete will be true if the image has no src so best to check if the src is set. if (source.complete && source.src) { this.isLoading = false; // ..and if we're complete now, no need for callbacks source.onload = null; source.onerror = null; if (source.width && source.height) { this._sourceLoaded(); // If any previous subscribers possible if (wasLoading) { this.emit('loaded', this); } } else { // If any previous subscribers possible if (wasLoading) { this.emit('error', this); } } } } }; /** * Used internally to update the width, height, and some other tracking vars once * a source has successfully loaded. * * @private */ BaseTexture.prototype._sourceLoaded = function () { this.hasLoaded = true; this.width = this.source.naturalWidth || this.source.width; this.height = this.source.naturalHeight || this.source.height; this.update(); }; /** * Destroys this base texture * */ BaseTexture.prototype.destroy = function () { if (this.imageUrl) { delete utils.BaseTextureCache[this.imageUrl]; delete utils.TextureCache[this.imageUrl]; this.imageUrl = null; if (!navigator.isCocoonJS) { this.source.src = ''; } } else if (this.source && this.source._pixiId) { delete utils.BaseTextureCache[this.source._pixiId]; } this.source = null; this.dispose(); }; /** * Frees the texture from WebGL memory without destroying this texture object. * This means you can still use the texture later which will upload it to GPU * memory again. * */ BaseTexture.prototype.dispose = function () { this.emit('dispose', this); }; /** * Changes the source image of the texture. * The original source must be an Image element. * * @param newSrc {string} the path of the image */ BaseTexture.prototype.updateSourceImage = function (newSrc) { this.source.src = newSrc; this.loadSource(this.source); }; /** * Helper function that creates a base texture from the given image url. * If the image is not in the base texture cache it will be created and loaded. * * @static * @param imageUrl {string} The image url of the texture * @param [crossorigin=(auto)] {boolean} Should use anonymouse CORS? Defaults to true if the URL is not a data-URI. * @param [scaleMode=scaleModes.DEFAULT] {number} See {@link scaleModes} for possible values * @return BaseTexture */ BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) { var baseTexture = utils.BaseTextureCache[imageUrl]; if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { crossorigin = true; } if (!baseTexture) { // new Image() breaks tex loading in some versions of Chrome. // See https://code.google.com/p/chromium/issues/detail?id=238071 var image = new Image();//document.createElement('img'); if (crossorigin) { image.crossOrigin = ''; } baseTexture = new BaseTexture(image, scaleMode); baseTexture.imageUrl = imageUrl; image.src = imageUrl; utils.BaseTextureCache[imageUrl] = baseTexture; // if there is an @2x at the end of the url we are going to assume its a highres image if ( imageUrl.indexOf(CONST.RETINA_PREFIX + '.') !== -1) { baseTexture.resolution = 2; } } return baseTexture; }; /** * Helper function that creates a base texture from the given canvas element. * * @static * @param canvas {Canvas} The canvas element source of the texture * @param scaleMode {number} See {{#crossLink "PIXI/scaleModes:property"}}scaleModes{{/crossLink}} for possible values * @return BaseTexture */ BaseTexture.fromCanvas = function (canvas, scaleMode) { if (!canvas._pixiId) { canvas._pixiId = 'canvas_' + utils.uuid(); } var baseTexture = utils.BaseTextureCache[canvas._pixiId]; if (!baseTexture) { baseTexture = new BaseTexture(canvas, scaleMode); utils.BaseTextureCache[canvas._pixiId] = baseTexture; } return baseTexture; };
src/core/textures/BaseTexture.js
1
https://github.com/pixijs/pixijs/commit/3ea09431d16285d7839497727406c2366d14cf9c
[ 0.012128319591283798, 0.0006729555898346007, 0.00016371349920518696, 0.0001726884365780279, 0.001885782228782773 ]
{ "id": 0, "code_window": [ " this._initContext();\n", "\n", " // empty all the old gl textures as they are useless now\n", " for (var key in utils.BaseTextureCache)\n", " {\n", " utils.BaseTextureCache[key]._glTextures = {};\n", " }\n", "};\n", "\n", "/**\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " utils.BaseTextureCache[key]._glTextures.length = 0;\n" ], "file_path": "src/core/renderers/webgl/WebGLRenderer.js", "type": "replace", "edit_start_line_idx": 370 }
describe('renderers/webgl/WebGLShaders', function () { 'use strict'; var expect = chai.expect; it('Module members exist', function () { expect(PIXI).to.respondTo('CompileVertexShader'); expect(PIXI).to.respondTo('CompileFragmentShader'); expect(PIXI).to.respondTo('_CompileShader'); expect(PIXI).to.respondTo('compileProgram'); }); });
test/unit/pixi/renderers/webgl/WebGLShaders.js
0
https://github.com/pixijs/pixijs/commit/3ea09431d16285d7839497727406c2366d14cf9c
[ 0.00017764230142347515, 0.00017543681315146387, 0.00017323133943136781, 0.00017543681315146387, 0.000002205480996053666 ]
{ "id": 0, "code_window": [ " this._initContext();\n", "\n", " // empty all the old gl textures as they are useless now\n", " for (var key in utils.BaseTextureCache)\n", " {\n", " utils.BaseTextureCache[key]._glTextures = {};\n", " }\n", "};\n", "\n", "/**\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " utils.BaseTextureCache[key]._glTextures.length = 0;\n" ], "file_path": "src/core/renderers/webgl/WebGLRenderer.js", "type": "replace", "edit_start_line_idx": 370 }
describe('pixi/display/Sprite', function () { 'use strict'; var expect = chai.expect; var Sprite = PIXI.Sprite; var Texture = PIXI.Texture; it('Module exists', function () { expect(Sprite).to.be.a('function'); expect(PIXI).to.have.deep.property('blendModes.NORMAL', 0); expect(PIXI).to.have.deep.property('blendModes.ADD', 1); expect(PIXI).to.have.deep.property('blendModes.MULTIPLY', 2); expect(PIXI).to.have.deep.property('blendModes.SCREEN', 3); }); it('Members exist', function () { expect(Sprite).itself.to.respondTo('fromImage'); expect(Sprite).itself.to.respondTo('fromFrame'); }); it('Confirm new instance', function (done) { var texture = Texture.fromImage('/base/test/textures/SpriteSheet-Aliens.png'); var obj = new Sprite(texture); pixi_display_Sprite_confirmNew(obj, done); }); });
test/unit/pixi/display/Sprite.js
0
https://github.com/pixijs/pixijs/commit/3ea09431d16285d7839497727406c2366d14cf9c
[ 0.00017963825666811317, 0.0001761997555149719, 0.00017431796004530042, 0.00017464304983150214, 0.0000024350069907086436 ]
{ "id": 0, "code_window": [ " this._initContext();\n", "\n", " // empty all the old gl textures as they are useless now\n", " for (var key in utils.BaseTextureCache)\n", " {\n", " utils.BaseTextureCache[key]._glTextures = {};\n", " }\n", "};\n", "\n", "/**\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " utils.BaseTextureCache[key]._glTextures.length = 0;\n" ], "file_path": "src/core/renderers/webgl/WebGLRenderer.js", "type": "replace", "edit_start_line_idx": 370 }
function pixi_core_Matrix_confirmNewMatrix(matrix) { var expect = chai.expect; expect(matrix).to.be.an.instanceof(PIXI.Matrix); expect(matrix).to.not.be.empty; expect(matrix.a).to.equal(1); expect(matrix.b).to.equal(0); expect(matrix.c).to.equal(0); expect(matrix.d).to.equal(1); expect(matrix.tx).to.equal(0); expect(matrix.ty).to.equal(0); }
test/lib/pixi/core/Matrix.js
0
https://github.com/pixijs/pixijs/commit/3ea09431d16285d7839497727406c2366d14cf9c
[ 0.00017888924048747867, 0.00017605772882234305, 0.00017322621715720743, 0.00017605772882234305, 0.000002831511665135622 ]
{ "id": 1, "code_window": [ " * @member {object<number, WebGLTexture>}\n", " * @private\n", " */\n", " this._glTextures = {};\n", "\n", " // if no source passed don't try to load\n", " if (source)\n", " {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " this._glTextures = [];\n" ], "file_path": "src/core/textures/BaseTexture.js", "type": "replace", "edit_start_line_idx": 115 }
var SystemRenderer = require('../SystemRenderer'), ShaderManager = require('./managers/ShaderManager'), MaskManager = require('./managers/MaskManager'), StencilManager = require('./managers/StencilManager'), FilterManager = require('./managers/FilterManager'), BlendModeManager = require('./managers/BlendModeManager'), RenderTarget = require('./utils/RenderTarget'), ObjectRenderer = require('./utils/ObjectRenderer'), math = require('../../math'), utils = require('../../utils'), CONST = require('../../const'); /** * The WebGLRenderer draws the scene and all its content onto a webGL enabled canvas. This renderer * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. * So no need for Sprite Batches or Sprite Clouds. * Don't forget to add the view to your DOM or you will not see anything :) * * @class * @namespace PIXI * @param [width=0] {number} the width of the canvas view * @param [height=0] {number} the height of the canvas view * @param [options] {object} The optional renderer parameters * @param [options.view] {HTMLCanvasElement} the canvas to use as a view, optional * @param [options.transparent=false] {boolean} If the render view is transparent, default false * @param [options.autoResize=false] {boolean} If the render view is automatically resized, default false * @param [options.antialias=false] {boolean} sets antialias (only applicable in chrome at the moment) * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or * not before the new render pass. * @param [options.preserveDrawingBuffer=false] {boolean} enables drawing buffer preservation, enable this if * you need to call toDataUrl on the webgl context. */ function WebGLRenderer(width, height, options) { SystemRenderer.call(this, 'WebGL', width, height, options); this.type = CONST.RENDERER_TYPE.WEBGL; this._boundUpdateTexture = this.updateTexture.bind(this); this._boundDestroyTexture = this.destroyTexture.bind(this); this._boundContextLost = this.handleContextLost.bind(this); this._boundContextRestored = this.handleContextRestored.bind(this); this.view.addEventListener('webglcontextlost', this._boundContextLost, false); this.view.addEventListener('webglcontextrestored', this._boundContextRestored, false); /** * The options passed in to create a new webgl context. * * @member {object} * @private */ this._contextOptions = { alpha: this.transparent, antialias: options.antialias, premultipliedAlpha: this.transparent && this.transparent !== 'notMultiplied', stencil: true, preserveDrawingBuffer: options.preserveDrawingBuffer }; /** * Counter for the number of draws made each frame * * @member {number} */ this.drawCount = 0; /** * Deals with managing the shader programs and their attribs. * * @member {ShaderManager} */ this.shaderManager = new ShaderManager(this); /** * Manages the masks using the stencil buffer. * * @member {MaskManager} */ this.maskManager = new MaskManager(this); /** * Manages the stencil buffer. * * @member {StencilManager} */ this.stencilManager = new StencilManager(this); /** * Manages the filters. * * @member {FilterManager} */ this.filterManager = new FilterManager(this); /** * Manages the blendModes * @member {BlendModeManager} */ this.blendModeManager = new BlendModeManager(this); this.currentRenderTarget = this.renderTarget; /** * This temporary display object used as the parent of the currently being rendered item * @member DisplayObject * @private */ this._tempDisplayObjectParent = {worldTransform:new math.Matrix(), worldAlpha:1}; this.currentRenderer = new ObjectRenderer(this); this.initPlugins(); // initialize the context so it is ready for the managers. this._initContext(); // map some webGL blend modes.. this._mapBlendModes(); } // constructor WebGLRenderer.prototype = Object.create(SystemRenderer.prototype); WebGLRenderer.prototype.constructor = WebGLRenderer; module.exports = WebGLRenderer; utils.pluginTarget.mixin(WebGLRenderer); utils.eventTarget.mixin(WebGLRenderer.prototype); WebGLRenderer.glContextId = 0; utils.pluginTarget.mixin(WebGLRenderer); /** * * @private */ WebGLRenderer.prototype._initContext = function () { var gl = this.view.getContext('webgl', this._contextOptions) || this.view.getContext('experimental-webgl', this._contextOptions); this.gl = gl; if (!gl) { // fail, not able to get a context throw new Error('This browser does not support webGL. Try using the canvas renderer'); } this.glContextId = WebGLRenderer.glContextId++; gl.id = this.glContextId; gl.renderer = this; // set up the default pixi settings.. gl.disable(gl.DEPTH_TEST); gl.disable(gl.CULL_FACE); gl.enable(gl.BLEND); this.renderTarget = new RenderTarget(this.gl, this.width, this.height, null, true); this.emit('context', gl); // setup the width/height properties and gl viewport this.resize(this.width, this.height); }; /** * Renders the object to its webGL view * * @param object {DisplayObject} the object to be rendered */ WebGLRenderer.prototype.render = function (object) { // no point rendering if our context has been blown up! if (this.gl.isContextLost()) { return; } var cacheParent = object.parent; object.parent = this._tempDisplayObjectParent; // update the scene graph object.updateTransform(); object.parent = cacheParent; var gl = this.gl; // make sure we are bound to the main frame buffer gl.bindFramebuffer(gl.FRAMEBUFFER, null); if (this.clearBeforeRender) { if (this.transparent) { gl.clearColor(0, 0, 0, 0); } else { gl.clearColor(this._backgroundColorRgb[0], this._backgroundColorRgb[1], this._backgroundColorRgb[2], 1); } gl.clear(gl.COLOR_BUFFER_BIT); } this.renderDisplayObject(object, this.renderTarget);//this.projection); }; /** * Renders a Display Object. * * @param displayObject {DisplayObject} The DisplayObject to render * @param projection {Point} The projection * @param buffer {Array} a standard WebGL buffer */ WebGLRenderer.prototype.renderDisplayObject = function (displayObject, renderTarget)//projection, buffer) { this.blendModeManager.setBlendMode(CONST.blendModes.NORMAL); this.setRenderTarget(renderTarget); // reset the render session data.. this.drawCount = 0; // start the filter manager this.filterManager.begin(); // render the scene! displayObject.renderWebGL(this); // finish the sprite batch this.currentRenderer.flush(); }; WebGLRenderer.prototype.setObjectRenderer = function (objectRenderer) { if (this.currentRenderer === objectRenderer) { return; } this.currentRenderer.stop(); this.currentRenderer = objectRenderer; this.currentRenderer.start(); }; WebGLRenderer.prototype.setRenderTarget = function (renderTarget) { this.currentRenderTarget = renderTarget; this.currentRenderTarget.activate(); this.stencilManager.setMaskStack( renderTarget.stencilMaskStack ); }; /** * Resizes the webGL view to the specified width and height. * * @param width {number} the new width of the webGL view * @param height {number} the new height of the webGL view */ WebGLRenderer.prototype.resize = function (width, height) { SystemRenderer.prototype.resize.call(this, width, height); this.gl.viewport(0, 0, this.width, this.height); this.filterManager.resize(width, height); this.renderTarget.resize(width, height); }; /** * Updates and/or Creates a WebGL texture for the renderer's context. * * @param texture {BaseTexture|Texture} the texture to update */ WebGLRenderer.prototype.updateTexture = function (texture) { texture = texture.baseTexture || texture; if (!texture.hasLoaded) { return; } var gl = this.gl; if (!texture._glTextures[gl.id]) { texture._glTextures[gl.id] = gl.createTexture(); texture.on('update', this._boundUpdateTexture); texture.on('dispose', this._boundDestroyTexture); } gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultipliedAlpha); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.source); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texture.scaleMode === CONST.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); if (texture.mipmap && utils.isPowerOfTwo(texture.width, texture.height)) { gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === CONST.scaleModes.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); gl.generateMipmap(gl.TEXTURE_2D); } else { gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === CONST.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); } if (!texture._powerOf2) { gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); } else { gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); } return texture._glTextures[gl.id]; }; WebGLRenderer.prototype.destroyTexture = function (texture) { texture = texture.baseTexture || texture; if (!texture.hasLoaded) { return; } if (texture._glTextures[this.gl.id]) { this.gl.deleteTexture(texture._glTextures[this.gl.id]); } }; /** * Handles a lost webgl context * * @param event {Event} * @private */ WebGLRenderer.prototype.handleContextLost = function (event) { event.preventDefault(); }; /** * Handles a restored webgl context * * @param event {Event} * @private */ WebGLRenderer.prototype.handleContextRestored = function () { this._initContext(); // empty all the old gl textures as they are useless now for (var key in utils.BaseTextureCache) { utils.BaseTextureCache[key]._glTextures = {}; } }; /** * Removes everything from the renderer (event listeners, spritebatch, etc...) * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ WebGLRenderer.prototype.destroy = function (removeView) { this.destroyPlugins(); // remove listeners this.view.removeEventListener('webglcontextlost', this._boundContextLost); this.view.removeEventListener('webglcontextrestored', this._boundContextRestored); // call base destroy SystemRenderer.prototype.destroy.call(this, removeView); this.uuid = 0; // destroy the managers this.shaderManager.destroy(); this.maskManager.destroy(); this.stencilManager.destroy(); this.filterManager.destroy(); this.shaderManager = null; this.maskManager = null; this.filterManager = null; this.blendModeManager = null; this._boundContextLost = null; this._boundContextRestored = null; this._contextOptions = null; this.drawCount = 0; this.gl = null; }; /** * Maps Pixi blend modes to WebGL blend modes. * * @private */ WebGLRenderer.prototype._mapBlendModes = function () { var gl = this.gl; if (!this.blendModes) { this.blendModes = {}; this.blendModes[CONST.blendModes.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.ADD] = [gl.SRC_ALPHA, gl.DST_ALPHA]; this.blendModes[CONST.blendModes.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.SCREEN] = [gl.SRC_ALPHA, gl.ONE]; this.blendModes[CONST.blendModes.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; } };
src/core/renderers/webgl/WebGLRenderer.js
1
https://github.com/pixijs/pixijs/commit/3ea09431d16285d7839497727406c2366d14cf9c
[ 0.007419714238494635, 0.0005807729903608561, 0.00016399644664488733, 0.00017024112457875162, 0.0013653631322085857 ]
{ "id": 1, "code_window": [ " * @member {object<number, WebGLTexture>}\n", " * @private\n", " */\n", " this._glTextures = {};\n", "\n", " // if no source passed don't try to load\n", " if (source)\n", " {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " this._glTextures = [];\n" ], "file_path": "src/core/textures/BaseTexture.js", "type": "replace", "edit_start_line_idx": 115 }
describe('pixi/textures/RenderTexture', function () { 'use strict'; var expect = chai.expect; var RenderTexture = PIXI.RenderTexture; it('Module exists', function () { expect(RenderTexture).to.be.a('function'); }); it('Confirm new instance', function (done) { var texture = new RenderTexture(100, 100, new PIXI.CanvasRenderer()); pixi_textures_RenderTexture_confirmNew(texture, done); }); });
test/unit/pixi/textures/RenderTexture.js
0
https://github.com/pixijs/pixijs/commit/3ea09431d16285d7839497727406c2366d14cf9c
[ 0.00017323315842077136, 0.00017283344641327858, 0.00017243371985387057, 0.00017283344641327858, 3.9971928345039487e-7 ]
{ "id": 1, "code_window": [ " * @member {object<number, WebGLTexture>}\n", " * @private\n", " */\n", " this._glTextures = {};\n", "\n", " // if no source passed don't try to load\n", " if (source)\n", " {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " this._glTextures = [];\n" ], "file_path": "src/core/textures/BaseTexture.js", "type": "replace", "edit_start_line_idx": 115 }
var core = require('../../core'); /** * This lowers the color depth of your image by the given amount, producing an image with a smaller palette. * * @class * @extends AbstractFilter * @namespace PIXI.filters */ function ColorStepFilter() { core.AbstractFilter.call(this, // vertex shader null, // fragment shader require('fs').readFileSync(__dirname + '/colorStep.frag', 'utf8'), // custom uniforms { step: { type: '1f', value: 5 } } ); } ColorStepFilter.prototype = Object.create(core.AbstractFilter.prototype); ColorStepFilter.prototype.constructor = ColorStepFilter; module.exports = ColorStepFilter; Object.defineProperties(ColorStepFilter.prototype, { /** * The number of steps to reduce the palette by. * * @member {number} * @memberof ColorStepFilter# */ step: { get: function () { return this.uniforms.step.value; }, set: function (value) { this.uniforms.step.value = value; } } });
src/filters/color/ColorStepFilter.js
0
https://github.com/pixijs/pixijs/commit/3ea09431d16285d7839497727406c2366d14cf9c
[ 0.00017517656669951975, 0.00017355168529320508, 0.00017205580661538988, 0.00017408242274541408, 0.0000012423531643435126 ]
{ "id": 1, "code_window": [ " * @member {object<number, WebGLTexture>}\n", " * @private\n", " */\n", " this._glTextures = {};\n", "\n", " // if no source passed don't try to load\n", " if (source)\n", " {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " this._glTextures = [];\n" ], "file_path": "src/core/textures/BaseTexture.js", "type": "replace", "edit_start_line_idx": 115 }
describe('pixi/core/Rectangle', function () { 'use strict'; var expect = chai.expect; var Rectangle = PIXI.Rectangle; it('Module exists', function () { expect(Rectangle).to.be.a('function'); }); it('Confirm new instance', function () { var rect = new Rectangle(); pixi_core_Rectangle_confirm(rect, 0, 0, 0, 0); }); });
test/unit/pixi/core/Rectangle.js
0
https://github.com/pixijs/pixijs/commit/3ea09431d16285d7839497727406c2366d14cf9c
[ 0.00017393394955433905, 0.00017365510575473309, 0.00017337626195512712, 0.00017365510575473309, 2.788437996059656e-7 ]
{ "id": 2, "code_window": [ " * @member {BaseTexture}\n", " */\n", " var baseTexture = new BaseTexture();\n", " baseTexture.width = width * resolution;\n", " baseTexture.height = height * resolution;\n", " baseTexture._glTextures = [];\n", " baseTexture.resolution = resolution;\n", " baseTexture.scaleMode = scaleMode || CONST.scaleModes.DEFAULT;\n", " baseTexture.hasLoaded = true;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/core/textures/RenderTexture.js", "type": "replace", "edit_start_line_idx": 67 }
var SystemRenderer = require('../SystemRenderer'), ShaderManager = require('./managers/ShaderManager'), MaskManager = require('./managers/MaskManager'), StencilManager = require('./managers/StencilManager'), FilterManager = require('./managers/FilterManager'), BlendModeManager = require('./managers/BlendModeManager'), RenderTarget = require('./utils/RenderTarget'), ObjectRenderer = require('./utils/ObjectRenderer'), math = require('../../math'), utils = require('../../utils'), CONST = require('../../const'); /** * The WebGLRenderer draws the scene and all its content onto a webGL enabled canvas. This renderer * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. * So no need for Sprite Batches or Sprite Clouds. * Don't forget to add the view to your DOM or you will not see anything :) * * @class * @namespace PIXI * @param [width=0] {number} the width of the canvas view * @param [height=0] {number} the height of the canvas view * @param [options] {object} The optional renderer parameters * @param [options.view] {HTMLCanvasElement} the canvas to use as a view, optional * @param [options.transparent=false] {boolean} If the render view is transparent, default false * @param [options.autoResize=false] {boolean} If the render view is automatically resized, default false * @param [options.antialias=false] {boolean} sets antialias (only applicable in chrome at the moment) * @param [options.resolution=1] {number} the resolution of the renderer retina would be 2 * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or * not before the new render pass. * @param [options.preserveDrawingBuffer=false] {boolean} enables drawing buffer preservation, enable this if * you need to call toDataUrl on the webgl context. */ function WebGLRenderer(width, height, options) { SystemRenderer.call(this, 'WebGL', width, height, options); this.type = CONST.RENDERER_TYPE.WEBGL; this._boundUpdateTexture = this.updateTexture.bind(this); this._boundDestroyTexture = this.destroyTexture.bind(this); this._boundContextLost = this.handleContextLost.bind(this); this._boundContextRestored = this.handleContextRestored.bind(this); this.view.addEventListener('webglcontextlost', this._boundContextLost, false); this.view.addEventListener('webglcontextrestored', this._boundContextRestored, false); /** * The options passed in to create a new webgl context. * * @member {object} * @private */ this._contextOptions = { alpha: this.transparent, antialias: options.antialias, premultipliedAlpha: this.transparent && this.transparent !== 'notMultiplied', stencil: true, preserveDrawingBuffer: options.preserveDrawingBuffer }; /** * Counter for the number of draws made each frame * * @member {number} */ this.drawCount = 0; /** * Deals with managing the shader programs and their attribs. * * @member {ShaderManager} */ this.shaderManager = new ShaderManager(this); /** * Manages the masks using the stencil buffer. * * @member {MaskManager} */ this.maskManager = new MaskManager(this); /** * Manages the stencil buffer. * * @member {StencilManager} */ this.stencilManager = new StencilManager(this); /** * Manages the filters. * * @member {FilterManager} */ this.filterManager = new FilterManager(this); /** * Manages the blendModes * @member {BlendModeManager} */ this.blendModeManager = new BlendModeManager(this); this.currentRenderTarget = this.renderTarget; /** * This temporary display object used as the parent of the currently being rendered item * @member DisplayObject * @private */ this._tempDisplayObjectParent = {worldTransform:new math.Matrix(), worldAlpha:1}; this.currentRenderer = new ObjectRenderer(this); this.initPlugins(); // initialize the context so it is ready for the managers. this._initContext(); // map some webGL blend modes.. this._mapBlendModes(); } // constructor WebGLRenderer.prototype = Object.create(SystemRenderer.prototype); WebGLRenderer.prototype.constructor = WebGLRenderer; module.exports = WebGLRenderer; utils.pluginTarget.mixin(WebGLRenderer); utils.eventTarget.mixin(WebGLRenderer.prototype); WebGLRenderer.glContextId = 0; utils.pluginTarget.mixin(WebGLRenderer); /** * * @private */ WebGLRenderer.prototype._initContext = function () { var gl = this.view.getContext('webgl', this._contextOptions) || this.view.getContext('experimental-webgl', this._contextOptions); this.gl = gl; if (!gl) { // fail, not able to get a context throw new Error('This browser does not support webGL. Try using the canvas renderer'); } this.glContextId = WebGLRenderer.glContextId++; gl.id = this.glContextId; gl.renderer = this; // set up the default pixi settings.. gl.disable(gl.DEPTH_TEST); gl.disable(gl.CULL_FACE); gl.enable(gl.BLEND); this.renderTarget = new RenderTarget(this.gl, this.width, this.height, null, true); this.emit('context', gl); // setup the width/height properties and gl viewport this.resize(this.width, this.height); }; /** * Renders the object to its webGL view * * @param object {DisplayObject} the object to be rendered */ WebGLRenderer.prototype.render = function (object) { // no point rendering if our context has been blown up! if (this.gl.isContextLost()) { return; } var cacheParent = object.parent; object.parent = this._tempDisplayObjectParent; // update the scene graph object.updateTransform(); object.parent = cacheParent; var gl = this.gl; // make sure we are bound to the main frame buffer gl.bindFramebuffer(gl.FRAMEBUFFER, null); if (this.clearBeforeRender) { if (this.transparent) { gl.clearColor(0, 0, 0, 0); } else { gl.clearColor(this._backgroundColorRgb[0], this._backgroundColorRgb[1], this._backgroundColorRgb[2], 1); } gl.clear(gl.COLOR_BUFFER_BIT); } this.renderDisplayObject(object, this.renderTarget);//this.projection); }; /** * Renders a Display Object. * * @param displayObject {DisplayObject} The DisplayObject to render * @param projection {Point} The projection * @param buffer {Array} a standard WebGL buffer */ WebGLRenderer.prototype.renderDisplayObject = function (displayObject, renderTarget)//projection, buffer) { this.blendModeManager.setBlendMode(CONST.blendModes.NORMAL); this.setRenderTarget(renderTarget); // reset the render session data.. this.drawCount = 0; // start the filter manager this.filterManager.begin(); // render the scene! displayObject.renderWebGL(this); // finish the sprite batch this.currentRenderer.flush(); }; WebGLRenderer.prototype.setObjectRenderer = function (objectRenderer) { if (this.currentRenderer === objectRenderer) { return; } this.currentRenderer.stop(); this.currentRenderer = objectRenderer; this.currentRenderer.start(); }; WebGLRenderer.prototype.setRenderTarget = function (renderTarget) { this.currentRenderTarget = renderTarget; this.currentRenderTarget.activate(); this.stencilManager.setMaskStack( renderTarget.stencilMaskStack ); }; /** * Resizes the webGL view to the specified width and height. * * @param width {number} the new width of the webGL view * @param height {number} the new height of the webGL view */ WebGLRenderer.prototype.resize = function (width, height) { SystemRenderer.prototype.resize.call(this, width, height); this.gl.viewport(0, 0, this.width, this.height); this.filterManager.resize(width, height); this.renderTarget.resize(width, height); }; /** * Updates and/or Creates a WebGL texture for the renderer's context. * * @param texture {BaseTexture|Texture} the texture to update */ WebGLRenderer.prototype.updateTexture = function (texture) { texture = texture.baseTexture || texture; if (!texture.hasLoaded) { return; } var gl = this.gl; if (!texture._glTextures[gl.id]) { texture._glTextures[gl.id] = gl.createTexture(); texture.on('update', this._boundUpdateTexture); texture.on('dispose', this._boundDestroyTexture); } gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultipliedAlpha); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.source); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texture.scaleMode === CONST.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); if (texture.mipmap && utils.isPowerOfTwo(texture.width, texture.height)) { gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === CONST.scaleModes.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); gl.generateMipmap(gl.TEXTURE_2D); } else { gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === CONST.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST); } if (!texture._powerOf2) { gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); } else { gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); } return texture._glTextures[gl.id]; }; WebGLRenderer.prototype.destroyTexture = function (texture) { texture = texture.baseTexture || texture; if (!texture.hasLoaded) { return; } if (texture._glTextures[this.gl.id]) { this.gl.deleteTexture(texture._glTextures[this.gl.id]); } }; /** * Handles a lost webgl context * * @param event {Event} * @private */ WebGLRenderer.prototype.handleContextLost = function (event) { event.preventDefault(); }; /** * Handles a restored webgl context * * @param event {Event} * @private */ WebGLRenderer.prototype.handleContextRestored = function () { this._initContext(); // empty all the old gl textures as they are useless now for (var key in utils.BaseTextureCache) { utils.BaseTextureCache[key]._glTextures = {}; } }; /** * Removes everything from the renderer (event listeners, spritebatch, etc...) * * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. */ WebGLRenderer.prototype.destroy = function (removeView) { this.destroyPlugins(); // remove listeners this.view.removeEventListener('webglcontextlost', this._boundContextLost); this.view.removeEventListener('webglcontextrestored', this._boundContextRestored); // call base destroy SystemRenderer.prototype.destroy.call(this, removeView); this.uuid = 0; // destroy the managers this.shaderManager.destroy(); this.maskManager.destroy(); this.stencilManager.destroy(); this.filterManager.destroy(); this.shaderManager = null; this.maskManager = null; this.filterManager = null; this.blendModeManager = null; this._boundContextLost = null; this._boundContextRestored = null; this._contextOptions = null; this.drawCount = 0; this.gl = null; }; /** * Maps Pixi blend modes to WebGL blend modes. * * @private */ WebGLRenderer.prototype._mapBlendModes = function () { var gl = this.gl; if (!this.blendModes) { this.blendModes = {}; this.blendModes[CONST.blendModes.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.ADD] = [gl.SRC_ALPHA, gl.DST_ALPHA]; this.blendModes[CONST.blendModes.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.SCREEN] = [gl.SRC_ALPHA, gl.ONE]; this.blendModes[CONST.blendModes.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; this.blendModes[CONST.blendModes.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; } };
src/core/renderers/webgl/WebGLRenderer.js
1
https://github.com/pixijs/pixijs/commit/3ea09431d16285d7839497727406c2366d14cf9c
[ 0.05128811299800873, 0.002203775104135275, 0.00016108265845105052, 0.00017245509661734104, 0.009466378949582577 ]
{ "id": 2, "code_window": [ " * @member {BaseTexture}\n", " */\n", " var baseTexture = new BaseTexture();\n", " baseTexture.width = width * resolution;\n", " baseTexture.height = height * resolution;\n", " baseTexture._glTextures = [];\n", " baseTexture.resolution = resolution;\n", " baseTexture.scaleMode = scaleMode || CONST.scaleModes.DEFAULT;\n", " baseTexture.hasLoaded = true;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/core/textures/RenderTexture.js", "type": "replace", "edit_start_line_idx": 67 }
/** * Creates an homogenous object for tracking events so users can know what to expect. * * @class * @namespace PIXI * @param target {object} The target object that the event is called on * @param name {string} The string name of the event that was triggered * @param data {object} Arbitrary event data to pass along */ function EventData(target, name, data) { // for duck typing in the ".on()" function this.__isEventObject = true; /** * Tracks the state of bubbling propagation. Do not * set this directly, instead use `event.stopPropagation()` * * @member {boolean} * @private * @readonly */ this.stopped = false; /** * Tracks the state of sibling listener propagation. Do not * set this directly, instead use `event.stopImmediatePropagation()` * * @member {boolean} * @private * @readonly */ this.stoppedImmediate = false; /** * The original target the event triggered on. * * @member {object} * @readonly */ this.target = target; /** * The string name of the event that this represents. * * @member {string} * @readonly */ this.type = name; /** * The data that was passed in with this event. * * @member {object} * @readonly */ this.data = data; /** * The timestamp when the event occurred. * * @member {number} * @readonly */ this.timeStamp = Date.now(); } EventData.prototype.constructor = EventData; module.exports = EventData; /** * Stops the propagation of events up the scene graph (prevents bubbling). * */ EventData.prototype.stopPropagation = function stopPropagation() { this.stopped = true; }; /** * Stops the propagation of events to sibling listeners (no longer calls any listeners). * */ EventData.prototype.stopImmediatePropagation = function stopImmediatePropagation() { this.stoppedImmediate = true; };
src/core/utils/EventData.js
0
https://github.com/pixijs/pixijs/commit/3ea09431d16285d7839497727406c2366d14cf9c
[ 0.0001771911047399044, 0.00016891289851628244, 0.00016584526747465134, 0.00016879271424841136, 0.000003306225607957458 ]
{ "id": 2, "code_window": [ " * @member {BaseTexture}\n", " */\n", " var baseTexture = new BaseTexture();\n", " baseTexture.width = width * resolution;\n", " baseTexture.height = height * resolution;\n", " baseTexture._glTextures = [];\n", " baseTexture.resolution = resolution;\n", " baseTexture.scaleMode = scaleMode || CONST.scaleModes.DEFAULT;\n", " baseTexture.hasLoaded = true;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/core/textures/RenderTexture.js", "type": "replace", "edit_start_line_idx": 67 }
function pixi_core_Circle_confirmNewCircle(obj) { var expect = chai.expect; expect(obj).to.be.an.instanceof(PIXI.Circle); expect(obj).to.respondTo('clone'); expect(obj).to.respondTo('contains'); expect(obj).to.respondTo('getBounds'); expect(obj).to.have.property('x', 0); expect(obj).to.have.property('y', 0); expect(obj).to.have.property('radius', 0); } function pixi_core_Circle_isBoundedByRectangle(obj, rect) { var expect = chai.expect; expect(rect).to.have.property('x', obj.x - obj.radius); expect(rect).to.have.property('y', obj.y - obj.radius); expect(rect).to.have.property('width', obj.radius * 2); expect(rect).to.have.property('height', obj.radius * 2); }
test/lib/pixi/core/Circle.js
0
https://github.com/pixijs/pixijs/commit/3ea09431d16285d7839497727406c2366d14cf9c
[ 0.00017562245193403214, 0.00017456589557696134, 0.00017373022274114192, 0.00017434507026337087, 7.881252486185986e-7 ]
{ "id": 2, "code_window": [ " * @member {BaseTexture}\n", " */\n", " var baseTexture = new BaseTexture();\n", " baseTexture.width = width * resolution;\n", " baseTexture.height = height * resolution;\n", " baseTexture._glTextures = [];\n", " baseTexture.resolution = resolution;\n", " baseTexture.scaleMode = scaleMode || CONST.scaleModes.DEFAULT;\n", " baseTexture.hasLoaded = true;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/core/textures/RenderTexture.js", "type": "replace", "edit_start_line_idx": 67 }
/** * The Point object represents a location in a two-dimensional coordinate system, where x represents * the horizontal axis and y represents the vertical axis. * * @class * @namespace PIXI * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ function Point(x, y) { /** * @member {number} * @default 0 */ this.x = x || 0; /** * @member {number} * @default 0 */ this.y = y || 0; } Point.prototype.constructor = Point; module.exports = Point; /** * Creates a clone of this point * * @return {Point} a copy of the point */ Point.prototype.clone = function () { return new Point(this.x, this.y); }; /** * Sets the point to a new x and y position. * If y is omitted, both x and y will be set to x. * * @param [x=0] {number} position of the point on the x axis * @param [y=0] {number} position of the point on the y axis */ Point.prototype.set = function (x, y) { this.x = x || 0; this.y = y || ( (y !== 0) ? this.x : 0 ) ; };
src/core/math/Point.js
0
https://github.com/pixijs/pixijs/commit/3ea09431d16285d7839497727406c2366d14cf9c
[ 0.00017562446009833366, 0.00017059562378562987, 0.00016420548490714282, 0.0001714052341412753, 0.0000037376059935922967 ]
{ "id": 0, "code_window": [ ".monaco-findInput .monaco-inputbox {\n", "\tfont-size: 13px;\n", "\twidth: 100%;\n", "}\n", "\n", ".monaco-findInput .monaco-inputbox > .wrapper > .input {\n", "\twidth: 100% !important;\n", "}\n", "\n", ".monaco-findInput > .controls {\n", "\tposition: absolute;\n", "\ttop: 3px;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/browser/ui/findinput/findInput.css", "type": "replace", "edit_start_line_idx": 15 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./findInput'; import * as nls from 'vs/nls'; import * as dom from 'vs/base/browser/dom'; import { IMessage as InputBoxMessage, IInputValidator, IInputBoxStyles, HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox'; import { IContextViewProvider } from 'vs/base/browser/ui/contextview/contextview'; import { Widget } from 'vs/base/browser/ui/widget'; import { Event, Emitter } from 'vs/base/common/event'; import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { IMouseEvent } from 'vs/base/browser/mouseEvent'; import { KeyCode } from 'vs/base/common/keyCodes'; import { CaseSensitiveCheckbox, WholeWordsCheckbox, RegexCheckbox } from 'vs/base/browser/ui/findinput/findInputCheckboxes'; import { Color } from 'vs/base/common/color'; import { ICheckboxStyles } from 'vs/base/browser/ui/checkbox/checkbox'; export interface IFindInputOptions extends IFindInputStyles { readonly placeholder?: string; readonly width?: number; readonly validation?: IInputValidator; readonly label: string; readonly flexibleHeight?: boolean; readonly appendCaseSensitiveLabel?: string; readonly appendWholeWordsLabel?: string; readonly appendRegexLabel?: string; readonly history?: string[]; } export interface IFindInputStyles extends IInputBoxStyles { inputActiveOptionBorder?: Color; } const NLS_DEFAULT_LABEL = nls.localize('defaultLabel', "input"); export class FindInput extends Widget { static readonly OPTION_CHANGE: string = 'optionChange'; private contextViewProvider: IContextViewProvider; private width: number; private placeholder: string; private validation?: IInputValidator; private label: string; private fixFocusOnOptionClickEnabled = true; private inputActiveOptionBorder?: Color; private inputBackground?: Color; private inputForeground?: Color; private inputBorder?: Color; private inputValidationInfoBorder?: Color; private inputValidationInfoBackground?: Color; private inputValidationInfoForeground?: Color; private inputValidationWarningBorder?: Color; private inputValidationWarningBackground?: Color; private inputValidationWarningForeground?: Color; private inputValidationErrorBorder?: Color; private inputValidationErrorBackground?: Color; private inputValidationErrorForeground?: Color; private regex: RegexCheckbox; private wholeWords: WholeWordsCheckbox; private caseSensitive: CaseSensitiveCheckbox; public domNode: HTMLElement; public inputBox: HistoryInputBox; private readonly _onDidOptionChange = this._register(new Emitter<boolean>()); public readonly onDidOptionChange: Event<boolean /* via keyboard */> = this._onDidOptionChange.event; private readonly _onKeyDown = this._register(new Emitter<IKeyboardEvent>()); public readonly onKeyDown: Event<IKeyboardEvent> = this._onKeyDown.event; private readonly _onMouseDown = this._register(new Emitter<IMouseEvent>()); public readonly onMouseDown: Event<IMouseEvent> = this._onMouseDown.event; private readonly _onInput = this._register(new Emitter<void>()); public readonly onInput: Event<void> = this._onInput.event; private readonly _onKeyUp = this._register(new Emitter<IKeyboardEvent>()); public readonly onKeyUp: Event<IKeyboardEvent> = this._onKeyUp.event; private _onCaseSensitiveKeyDown = this._register(new Emitter<IKeyboardEvent>()); public readonly onCaseSensitiveKeyDown: Event<IKeyboardEvent> = this._onCaseSensitiveKeyDown.event; private _onRegexKeyDown = this._register(new Emitter<IKeyboardEvent>()); public readonly onRegexKeyDown: Event<IKeyboardEvent> = this._onRegexKeyDown.event; constructor(parent: HTMLElement | null, contextViewProvider: IContextViewProvider, private readonly _showOptionButtons: boolean, options: IFindInputOptions) { super(); this.contextViewProvider = contextViewProvider; this.width = options.width || 100; this.placeholder = options.placeholder || ''; this.validation = options.validation; this.label = options.label || NLS_DEFAULT_LABEL; this.inputActiveOptionBorder = options.inputActiveOptionBorder; this.inputBackground = options.inputBackground; this.inputForeground = options.inputForeground; this.inputBorder = options.inputBorder; this.inputValidationInfoBorder = options.inputValidationInfoBorder; this.inputValidationInfoBackground = options.inputValidationInfoBackground; this.inputValidationInfoForeground = options.inputValidationInfoForeground; this.inputValidationWarningBorder = options.inputValidationWarningBorder; this.inputValidationWarningBackground = options.inputValidationWarningBackground; this.inputValidationWarningForeground = options.inputValidationWarningForeground; this.inputValidationErrorBorder = options.inputValidationErrorBorder; this.inputValidationErrorBackground = options.inputValidationErrorBackground; this.inputValidationErrorForeground = options.inputValidationErrorForeground; this.buildDomNode(options.appendCaseSensitiveLabel || '', options.appendWholeWordsLabel || '', options.appendRegexLabel || '', options.history || [], !!options.flexibleHeight); if (parent) { parent.appendChild(this.domNode); } this.onkeydown(this.inputBox.inputElement, (e) => this._onKeyDown.fire(e)); this.onkeyup(this.inputBox.inputElement, (e) => this._onKeyUp.fire(e)); this.oninput(this.inputBox.inputElement, (e) => this._onInput.fire()); this.onmousedown(this.inputBox.inputElement, (e) => this._onMouseDown.fire(e)); } public enable(): void { dom.removeClass(this.domNode, 'disabled'); this.inputBox.enable(); this.regex.enable(); this.wholeWords.enable(); this.caseSensitive.enable(); } public disable(): void { dom.addClass(this.domNode, 'disabled'); this.inputBox.disable(); this.regex.disable(); this.wholeWords.disable(); this.caseSensitive.disable(); } public setFocusInputOnOptionClick(value: boolean): void { this.fixFocusOnOptionClickEnabled = value; } public setEnabled(enabled: boolean): void { if (enabled) { this.enable(); } else { this.disable(); } } public clear(): void { this.clearValidation(); this.setValue(''); this.focus(); } public setWidth(newWidth: number): void { this.width = newWidth; this.domNode.style.width = this.width + 'px'; this.contextViewProvider.layout(); this.setInputWidth(); } public getValue(): string { return this.inputBox.value; } public setValue(value: string): void { if (this.inputBox.value !== value) { this.inputBox.value = value; } } public onSearchSubmit(): void { this.inputBox.addToHistory(); } public style(styles: IFindInputStyles): void { this.inputActiveOptionBorder = styles.inputActiveOptionBorder; this.inputBackground = styles.inputBackground; this.inputForeground = styles.inputForeground; this.inputBorder = styles.inputBorder; this.inputValidationInfoBackground = styles.inputValidationInfoBackground; this.inputValidationInfoForeground = styles.inputValidationInfoForeground; this.inputValidationInfoBorder = styles.inputValidationInfoBorder; this.inputValidationWarningBackground = styles.inputValidationWarningBackground; this.inputValidationWarningForeground = styles.inputValidationWarningForeground; this.inputValidationWarningBorder = styles.inputValidationWarningBorder; this.inputValidationErrorBackground = styles.inputValidationErrorBackground; this.inputValidationErrorForeground = styles.inputValidationErrorForeground; this.inputValidationErrorBorder = styles.inputValidationErrorBorder; this.applyStyles(); } protected applyStyles(): void { if (this.domNode) { const checkBoxStyles: ICheckboxStyles = { inputActiveOptionBorder: this.inputActiveOptionBorder, }; this.regex.style(checkBoxStyles); this.wholeWords.style(checkBoxStyles); this.caseSensitive.style(checkBoxStyles); const inputBoxStyles: IInputBoxStyles = { inputBackground: this.inputBackground, inputForeground: this.inputForeground, inputBorder: this.inputBorder, inputValidationInfoBackground: this.inputValidationInfoBackground, inputValidationInfoForeground: this.inputValidationInfoForeground, inputValidationInfoBorder: this.inputValidationInfoBorder, inputValidationWarningBackground: this.inputValidationWarningBackground, inputValidationWarningForeground: this.inputValidationWarningForeground, inputValidationWarningBorder: this.inputValidationWarningBorder, inputValidationErrorBackground: this.inputValidationErrorBackground, inputValidationErrorForeground: this.inputValidationErrorForeground, inputValidationErrorBorder: this.inputValidationErrorBorder }; this.inputBox.style(inputBoxStyles); } } public select(): void { this.inputBox.select(); } public focus(): void { this.inputBox.focus(); } public getCaseSensitive(): boolean { return this.caseSensitive.checked; } public setCaseSensitive(value: boolean): void { this.caseSensitive.checked = value; this.setInputWidth(); } public getWholeWords(): boolean { return this.wholeWords.checked; } public setWholeWords(value: boolean): void { this.wholeWords.checked = value; this.setInputWidth(); } public getRegex(): boolean { return this.regex.checked; } public setRegex(value: boolean): void { this.regex.checked = value; this.setInputWidth(); this.validate(); } public focusOnCaseSensitive(): void { this.caseSensitive.focus(); } public focusOnRegex(): void { this.regex.focus(); } private _lastHighlightFindOptions: number = 0; public highlightFindOptions(): void { dom.removeClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions)); this._lastHighlightFindOptions = 1 - this._lastHighlightFindOptions; dom.addClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions)); } private setInputWidth(): void { let w = this.width - this.caseSensitive.width() - this.wholeWords.width() - this.regex.width(); this.inputBox.width = w; this.inputBox.layout(); } private buildDomNode(appendCaseSensitiveLabel: string, appendWholeWordsLabel: string, appendRegexLabel: string, history: string[], flexibleHeight: boolean): void { this.domNode = document.createElement('div'); this.domNode.style.width = this.width + 'px'; dom.addClass(this.domNode, 'monaco-findInput'); this.inputBox = this._register(new HistoryInputBox(this.domNode, this.contextViewProvider, { placeholder: this.placeholder || '', ariaLabel: this.label || '', validationOptions: { validation: this.validation }, inputBackground: this.inputBackground, inputForeground: this.inputForeground, inputBorder: this.inputBorder, inputValidationInfoBackground: this.inputValidationInfoBackground, inputValidationInfoForeground: this.inputValidationInfoForeground, inputValidationInfoBorder: this.inputValidationInfoBorder, inputValidationWarningBackground: this.inputValidationWarningBackground, inputValidationWarningForeground: this.inputValidationWarningForeground, inputValidationWarningBorder: this.inputValidationWarningBorder, inputValidationErrorBackground: this.inputValidationErrorBackground, inputValidationErrorForeground: this.inputValidationErrorForeground, inputValidationErrorBorder: this.inputValidationErrorBorder, history, flexibleHeight })); this.regex = this._register(new RegexCheckbox({ appendTitle: appendRegexLabel, isChecked: false, inputActiveOptionBorder: this.inputActiveOptionBorder })); this._register(this.regex.onChange(viaKeyboard => { this._onDidOptionChange.fire(viaKeyboard); if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) { this.inputBox.focus(); } this.setInputWidth(); this.validate(); })); this._register(this.regex.onKeyDown(e => { this._onRegexKeyDown.fire(e); })); this.wholeWords = this._register(new WholeWordsCheckbox({ appendTitle: appendWholeWordsLabel, isChecked: false, inputActiveOptionBorder: this.inputActiveOptionBorder })); this._register(this.wholeWords.onChange(viaKeyboard => { this._onDidOptionChange.fire(viaKeyboard); if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) { this.inputBox.focus(); } this.setInputWidth(); this.validate(); })); this.caseSensitive = this._register(new CaseSensitiveCheckbox({ appendTitle: appendCaseSensitiveLabel, isChecked: false, inputActiveOptionBorder: this.inputActiveOptionBorder })); this._register(this.caseSensitive.onChange(viaKeyboard => { this._onDidOptionChange.fire(viaKeyboard); if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) { this.inputBox.focus(); } this.setInputWidth(); this.validate(); })); this._register(this.caseSensitive.onKeyDown(e => { this._onCaseSensitiveKeyDown.fire(e); })); if (this._showOptionButtons) { this.inputBox.inputElement.style.paddingRight = (this.caseSensitive.width() + this.wholeWords.width() + this.regex.width()) + 'px'; } // Arrow-Key support to navigate between options let indexes = [this.caseSensitive.domNode, this.wholeWords.domNode, this.regex.domNode]; this.onkeydown(this.domNode, (event: IKeyboardEvent) => { if (event.equals(KeyCode.LeftArrow) || event.equals(KeyCode.RightArrow) || event.equals(KeyCode.Escape)) { let index = indexes.indexOf(<HTMLElement>document.activeElement); if (index >= 0) { let newIndex: number = -1; if (event.equals(KeyCode.RightArrow)) { newIndex = (index + 1) % indexes.length; } else if (event.equals(KeyCode.LeftArrow)) { if (index === 0) { newIndex = indexes.length - 1; } else { newIndex = index - 1; } } if (event.equals(KeyCode.Escape)) { indexes[index].blur(); } else if (newIndex >= 0) { indexes[newIndex].focus(); } dom.EventHelper.stop(event, true); } } }); this.setInputWidth(); let controls = document.createElement('div'); controls.className = 'controls'; controls.style.display = this._showOptionButtons ? 'block' : 'none'; controls.appendChild(this.caseSensitive.domNode); controls.appendChild(this.wholeWords.domNode); controls.appendChild(this.regex.domNode); this.domNode.appendChild(controls); } public validate(): void { if (this.inputBox) { this.inputBox.validate(); } } public showMessage(message: InputBoxMessage): void { if (this.inputBox) { this.inputBox.showMessage(message); } } public clearMessage(): void { if (this.inputBox) { this.inputBox.hideMessage(); } } private clearValidation(): void { if (this.inputBox) { this.inputBox.hideMessage(); } } public dispose(): void { super.dispose(); } }
src/vs/base/browser/ui/findinput/findInput.ts
1
https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe
[ 0.01481357216835022, 0.0005577795673161745, 0.0001627759775146842, 0.00017249217489734292, 0.0021831514313817024 ]
{ "id": 0, "code_window": [ ".monaco-findInput .monaco-inputbox {\n", "\tfont-size: 13px;\n", "\twidth: 100%;\n", "}\n", "\n", ".monaco-findInput .monaco-inputbox > .wrapper > .input {\n", "\twidth: 100% !important;\n", "}\n", "\n", ".monaco-findInput > .controls {\n", "\tposition: absolute;\n", "\ttop: 3px;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/browser/ui/findinput/findInput.css", "type": "replace", "edit_start_line_idx": 15 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Application, Quality } from '../../application'; export function setup() { describe('Extensions', () => { it(`install and activate vscode-smoketest-check extension`, async function () { const app = this.app as Application; if (app.quality === Quality.Dev) { this.skip(); return; } const extensionName = 'vscode-smoketest-check'; await app.workbench.extensions.openExtensionsViewlet(); await app.workbench.extensions.installExtension(extensionName); await app.reload(); await app.workbench.extensions.waitForExtensionsViewlet(); await app.workbench.quickopen.runCommand('Smoke Test Check'); await app.workbench.statusbar.waitForStatusbarText('smoke test', 'VS Code Smoke Test Check'); }); }); }
test/smoke/src/areas/extensions/extensions.test.ts
0
https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe
[ 0.000175492386915721, 0.00017479044618085027, 0.00017354397277813405, 0.00017533499340061098, 8.837322980070894e-7 ]
{ "id": 0, "code_window": [ ".monaco-findInput .monaco-inputbox {\n", "\tfont-size: 13px;\n", "\twidth: 100%;\n", "}\n", "\n", ".monaco-findInput .monaco-inputbox > .wrapper > .input {\n", "\twidth: 100% !important;\n", "}\n", "\n", ".monaco-findInput > .controls {\n", "\tposition: absolute;\n", "\ttop: 3px;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/browser/ui/findinput/findInput.css", "type": "replace", "edit_start_line_idx": 15 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { IMatch } from 'vs/base/common/filters'; import { matchesFuzzyOcticonAware, parseOcticons } from 'vs/base/common/octicon'; export interface IOcticonFilter { // Returns null if word doesn't match. (query: string, target: { text: string, octiconOffsets?: number[] }): IMatch[] | null; } function filterOk(filter: IOcticonFilter, word: string, target: { text: string, octiconOffsets?: number[] }, highlights?: { start: number; end: number; }[]) { let r = filter(word, target); assert(r); if (highlights) { assert.deepEqual(r, highlights); } } suite('Octicon', () => { test('matchesFuzzzyOcticonAware', () => { // Camel Case filterOk(matchesFuzzyOcticonAware, 'ccr', parseOcticons('$(octicon)CamelCaseRocks$(octicon)'), [ { start: 10, end: 11 }, { start: 15, end: 16 }, { start: 19, end: 20 } ]); filterOk(matchesFuzzyOcticonAware, 'ccr', parseOcticons('$(octicon) CamelCaseRocks $(octicon)'), [ { start: 11, end: 12 }, { start: 16, end: 17 }, { start: 20, end: 21 } ]); filterOk(matchesFuzzyOcticonAware, 'iut', parseOcticons('$(octicon) Indent $(octico) Using $(octic) Tpaces'), [ { start: 11, end: 12 }, { start: 28, end: 29 }, { start: 43, end: 44 }, ]); // Prefix filterOk(matchesFuzzyOcticonAware, 'using', parseOcticons('$(octicon) Indent Using Spaces'), [ { start: 18, end: 23 }, ]); // Broken Octicon filterOk(matchesFuzzyOcticonAware, 'octicon', parseOcticons('This $(octicon Indent Using Spaces'), [ { start: 7, end: 14 }, ]); filterOk(matchesFuzzyOcticonAware, 'indent', parseOcticons('This $octicon Indent Using Spaces'), [ { start: 14, end: 20 }, ]); // Testing #59343 filterOk(matchesFuzzyOcticonAware, 'unt', parseOcticons('$(primitive-dot) $(file-text) Untitled-1'), [ { start: 30, end: 33 }, ]); }); });
src/vs/base/test/common/octicon.test.ts
0
https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe
[ 0.0001781477767508477, 0.00017612543888390064, 0.00017340006888844073, 0.00017662046593613923, 0.000001529432097413519 ]
{ "id": 0, "code_window": [ ".monaco-findInput .monaco-inputbox {\n", "\tfont-size: 13px;\n", "\twidth: 100%;\n", "}\n", "\n", ".monaco-findInput .monaco-inputbox > .wrapper > .input {\n", "\twidth: 100% !important;\n", "}\n", "\n", ".monaco-findInput > .controls {\n", "\tposition: absolute;\n", "\ttop: 3px;\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/browser/ui/findinput/findInput.css", "type": "replace", "edit_start_line_idx": 15 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as path from 'path'; import { Event, EventEmitter, ExtensionContext, Task, TextDocument, ThemeIcon, TreeDataProvider, TreeItem, TreeItemCollapsibleState, Uri, WorkspaceFolder, commands, window, workspace, tasks, Selection, TaskGroup } from 'vscode'; import { visit, JSONVisitor } from 'jsonc-parser'; import { NpmTaskDefinition, getPackageJsonUriFromTask, getScripts, isWorkspaceFolder, getTaskName, createTask, extractDebugArgFromScript, startDebugging } from './tasks'; import * as nls from 'vscode-nls'; const localize = nls.loadMessageBundle(); class Folder extends TreeItem { packages: PackageJSON[] = []; workspaceFolder: WorkspaceFolder; constructor(folder: WorkspaceFolder) { super(folder.name, TreeItemCollapsibleState.Expanded); this.contextValue = 'folder'; this.resourceUri = folder.uri; this.workspaceFolder = folder; this.iconPath = ThemeIcon.Folder; } addPackage(packageJson: PackageJSON) { this.packages.push(packageJson); } } const packageName = 'package.json'; class PackageJSON extends TreeItem { path: string; folder: Folder; scripts: NpmScript[] = []; static getLabel(_folderName: string, relativePath: string): string { if (relativePath.length > 0) { return path.join(relativePath, packageName); } return packageName; } constructor(folder: Folder, relativePath: string) { super(PackageJSON.getLabel(folder.label!, relativePath), TreeItemCollapsibleState.Expanded); this.folder = folder; this.path = relativePath; this.contextValue = 'packageJSON'; if (relativePath) { this.resourceUri = Uri.file(path.join(folder!.resourceUri!.fsPath, relativePath, packageName)); } else { this.resourceUri = Uri.file(path.join(folder!.resourceUri!.fsPath, packageName)); } this.iconPath = ThemeIcon.File; } addScript(script: NpmScript) { this.scripts.push(script); } } type ExplorerCommands = 'open' | 'run'; class NpmScript extends TreeItem { task: Task; package: PackageJSON; constructor(context: ExtensionContext, packageJson: PackageJSON, task: Task) { super(task.name, TreeItemCollapsibleState.None); const command: ExplorerCommands = workspace.getConfiguration('npm').get<ExplorerCommands>('scriptExplorerAction') || 'open'; const commandList = { 'open': { title: 'Edit Script', command: 'npm.openScript', arguments: [this] }, 'run': { title: 'Run Script', command: 'npm.runScript', arguments: [this] } }; this.contextValue = 'script'; if (task.group && task.group === TaskGroup.Rebuild) { this.contextValue = 'debugScript'; } this.package = packageJson; this.task = task; this.command = commandList[command]; if (task.group && task.group === TaskGroup.Clean) { this.iconPath = { light: context.asAbsolutePath(path.join('resources', 'light', 'prepostscript.svg')), dark: context.asAbsolutePath(path.join('resources', 'dark', 'prepostscript.svg')) }; } else { this.iconPath = { light: context.asAbsolutePath(path.join('resources', 'light', 'script.svg')), dark: context.asAbsolutePath(path.join('resources', 'dark', 'script.svg')) }; } let uri = getPackageJsonUriFromTask(task); getScripts(uri!).then(scripts => { if (scripts && scripts[task.definition['script']]) { this.tooltip = scripts[task.definition['script']]; } }); } getFolder(): WorkspaceFolder { return this.package.folder.workspaceFolder; } } class NoScripts extends TreeItem { constructor() { super(localize('noScripts', 'No scripts found'), TreeItemCollapsibleState.None); this.contextValue = 'noscripts'; } } export class NpmScriptsTreeDataProvider implements TreeDataProvider<TreeItem> { private taskTree: Folder[] | PackageJSON[] | NoScripts[] | null = null; private extensionContext: ExtensionContext; private _onDidChangeTreeData: EventEmitter<TreeItem | null> = new EventEmitter<TreeItem | null>(); readonly onDidChangeTreeData: Event<TreeItem | null> = this._onDidChangeTreeData.event; constructor(context: ExtensionContext) { const subscriptions = context.subscriptions; this.extensionContext = context; subscriptions.push(commands.registerCommand('npm.runScript', this.runScript, this)); subscriptions.push(commands.registerCommand('npm.debugScript', this.debugScript, this)); subscriptions.push(commands.registerCommand('npm.openScript', this.openScript, this)); subscriptions.push(commands.registerCommand('npm.refresh', this.refresh, this)); subscriptions.push(commands.registerCommand('npm.runInstall', this.runInstall, this)); } private scriptIsValid(scripts: any, task: Task): boolean { for (const script in scripts) { let label = getTaskName(script, task.definition.path); if (task.name === label) { return true; } } return false; } private async runScript(script: NpmScript) { let task = script.task; let uri = getPackageJsonUriFromTask(task); let scripts = await getScripts(uri!); if (!this.scriptIsValid(scripts, task)) { this.scriptNotValid(task); return; } tasks.executeTask(script.task); } private extractDebugArg(scripts: any, task: Task): [string, number] | undefined { return extractDebugArgFromScript(scripts[task.name]); } private async debugScript(script: NpmScript) { let task = script.task; let uri = getPackageJsonUriFromTask(task); let scripts = await getScripts(uri!); if (!this.scriptIsValid(scripts, task)) { this.scriptNotValid(task); return; } let debugArg = this.extractDebugArg(scripts, task); if (!debugArg) { let message = localize('noDebugOptions', 'Could not launch "{0}" for debugging because the scripts lacks a node debug option, e.g. "--inspect-brk".', task.name); let learnMore = localize('learnMore', 'Learn More'); let ok = localize('ok', 'OK'); let result = await window.showErrorMessage(message, { modal: true }, ok, learnMore); if (result === learnMore) { commands.executeCommand('vscode.open', Uri.parse('https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_launch-configuration-support-for-npm-and-other-tools')); } return; } startDebugging(task.name, debugArg[0], debugArg[1], script.getFolder()); } private scriptNotValid(task: Task) { let message = localize('scriptInvalid', 'Could not find the script "{0}". Try to refresh the view.', task.name); window.showErrorMessage(message); } private findScript(document: TextDocument, script?: NpmScript): number { let scriptOffset = 0; let inScripts = false; let visitor: JSONVisitor = { onError() { return scriptOffset; }, onObjectEnd() { if (inScripts) { inScripts = false; } }, onObjectProperty(property: string, offset: number, _length: number) { if (property === 'scripts') { inScripts = true; if (!script) { // select the script section scriptOffset = offset; } } else if (inScripts && script) { let label = getTaskName(property, script.task.definition.path); if (script.task.name === label) { scriptOffset = offset; } } } }; visit(document.getText(), visitor); return scriptOffset; } private async runInstall(selection: PackageJSON) { let uri: Uri | undefined = undefined; if (selection instanceof PackageJSON) { uri = selection.resourceUri; } if (!uri) { return; } let task = createTask('install', 'install', selection.folder.workspaceFolder, uri, []); tasks.executeTask(task); } private async openScript(selection: PackageJSON | NpmScript) { let uri: Uri | undefined = undefined; if (selection instanceof PackageJSON) { uri = selection.resourceUri!; } else if (selection instanceof NpmScript) { uri = selection.package.resourceUri; } if (!uri) { return; } let document: TextDocument = await workspace.openTextDocument(uri); let offset = this.findScript(document, selection instanceof NpmScript ? selection : undefined); let position = document.positionAt(offset); await window.showTextDocument(document, { selection: new Selection(position, position) }); } public refresh() { this.taskTree = null; this._onDidChangeTreeData.fire(); } getTreeItem(element: TreeItem): TreeItem { return element; } getParent(element: TreeItem): TreeItem | null { if (element instanceof Folder) { return null; } if (element instanceof PackageJSON) { return element.folder; } if (element instanceof NpmScript) { return element.package; } if (element instanceof NoScripts) { return null; } return null; } async getChildren(element?: TreeItem): Promise<TreeItem[]> { if (!this.taskTree) { let taskItems = await tasks.fetchTasks({ type: 'npm' }); if (taskItems) { this.taskTree = this.buildTaskTree(taskItems); if (this.taskTree.length === 0) { this.taskTree = [new NoScripts()]; } } } if (element instanceof Folder) { return element.packages; } if (element instanceof PackageJSON) { return element.scripts; } if (element instanceof NpmScript) { return []; } if (element instanceof NoScripts) { return []; } if (!element) { if (this.taskTree) { return this.taskTree; } } return []; } private isInstallTask(task: Task): boolean { let fullName = getTaskName('install', task.definition.path); return fullName === task.name; } private buildTaskTree(tasks: Task[]): Folder[] | PackageJSON[] | NoScripts[] { let folders: Map<String, Folder> = new Map(); let packages: Map<String, PackageJSON> = new Map(); let folder = null; let packageJson = null; tasks.forEach(each => { if (isWorkspaceFolder(each.scope) && !this.isInstallTask(each)) { folder = folders.get(each.scope.name); if (!folder) { folder = new Folder(each.scope); folders.set(each.scope.name, folder); } let definition: NpmTaskDefinition = <NpmTaskDefinition>each.definition; let relativePath = definition.path ? definition.path : ''; let fullPath = path.join(each.scope.name, relativePath); packageJson = packages.get(fullPath); if (!packageJson) { packageJson = new PackageJSON(folder, relativePath); folder.addPackage(packageJson); packages.set(fullPath, packageJson); } let script = new NpmScript(this.extensionContext, packageJson, each); packageJson.addScript(script); } }); if (folders.size === 1) { return [...packages.values()]; } return [...folders.values()]; } }
extensions/npm/src/npmView.ts
0
https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe
[ 0.0001789898960851133, 0.0001742662861943245, 0.00016559843788854778, 0.0001750356168486178, 0.000003279818429291481 ]
{ "id": 1, "code_window": [ "\tstatic readonly OPTION_CHANGE: string = 'optionChange';\n", "\n", "\tprivate contextViewProvider: IContextViewProvider;\n", "\tprivate width: number;\n", "\tprivate placeholder: string;\n", "\tprivate validation?: IInputValidator;\n", "\tprivate label: string;\n", "\tprivate fixFocusOnOptionClickEnabled = true;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/browser/ui/findinput/findInput.ts", "type": "replace", "edit_start_line_idx": 44 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ .search-view .search-widgets-container { margin: 0px 9px 0 2px; padding-top: 6px; } .search-view .search-widget .toggle-replace-button { position: absolute; top: 0; left: 0; width: 16px; height: 100%; box-sizing: border-box; background-position: center center; background-repeat: no-repeat; cursor: pointer; } .search-view .search-widget .search-container, .search-view .search-widget .replace-container { margin-left: 17px; } .search-view .search-widget .monaco-inputbox > .wrapper { height: 100%; } .search-view .search-widget .monaco-inputbox > .wrapper > .mirror, .search-view .search-widget .monaco-inputbox > .wrapper > textarea.input { padding: 3px; padding-left: 4px; } .search-view .search-widget .monaco-inputbox > .wrapper > .mirror { max-height: 134px; } .search-view .search-widget .monaco-inputbox > .wrapper > textarea.input { overflow: initial; height: 24px; /* set initial height before measure */ } .search-view .monaco-inputbox > .wrapper > textarea.input::-webkit-scrollbar { display: none; } .search-view .search-widget .monaco-findInput { display: inline-block; vertical-align: middle; } .search-view .search-widget .replace-container { margin-top: 6px; position: relative; display: inline-flex; } .search-view .search-widget .replace-container.disabled { display: none; } .search-view .search-widget .replace-container .monaco-action-bar { margin-left: 3px; } .search-view .search-widget .replace-container .monaco-action-bar { height: 25px; } .search-view .search-widget .replace-container .monaco-action-bar .action-item .icon { background-repeat: no-repeat; width: 20px; height: 25px; } .search-view .query-details { min-height: 1em; position: relative; margin: 0 0 0 17px; } .search-view .query-details .more { position: absolute; margin-right: 0.3em; right: 0; cursor: pointer; width: 16px; height: 13px; z-index: 2; /* Force it above the search results message, which has a negative top margin */ } .hc-black .monaco-workbench .search-view .query-details .more, .vs-dark .monaco-workbench .search-view .query-details .more { background: url('ellipsis-inverse.svg') top center no-repeat; } .vs .monaco-workbench .search-view .query-details .more { background: url('ellipsis.svg') top center no-repeat; } .search-view .query-details .file-types { display: none; } .search-view .query-details .file-types > .monaco-inputbox { width: 100%; height: 25px; } .search-view .query-details.more .file-types { display: inherit; } .search-view .query-details.more .file-types:last-child { padding-bottom: 10px; } .search-view .query-details.more h4 { text-overflow: ellipsis; overflow: hidden; white-space: nowrap; padding: 4px 0 0; margin: 0; font-size: 11px; font-weight: normal; } .search-view .messages { margin-top: -5px; cursor: default; } .search-view .message { padding-left: 22px; padding-right: 22px; padding-top: 0px; } .search-view .message p:first-child { margin-top: 0px; margin-bottom: 0px; padding-bottom: 4px; user-select: text; } .search-view .foldermatch, .search-view .filematch { display: flex; position: relative; line-height: 22px; padding: 0; } .search-view:not(.wide) .foldermatch .monaco-icon-label, .search-view:not(.wide) .filematch .monaco-icon-label { flex: 1; } .search-view:not(.wide) .monaco-list .monaco-list-row:hover:not(.highlighted) .foldermatch .monaco-icon-label, .search-view:not(.wide) .monaco-list .monaco-list-row.focused .foldermatch .monaco-icon-label, .search-view:not(.wide) .monaco-list .monaco-list-row:hover:not(.highlighted) .filematch .monaco-icon-label, .search-view:not(.wide) .monaco-list .monaco-list-row.focused .filematch .monaco-icon-label { flex: 1; } .search-view.wide .foldermatch .badge, .search-view.wide .filematch .badge { margin-left: 10px; } .search-view .linematch { position: relative; line-height: 22px; display: flex; overflow: hidden; } .search-view .linematch > .match { overflow: hidden; text-overflow: ellipsis; white-space: pre; } .search-view .linematch .matchLineNum { margin-left: 7px; margin-right: 4px; opacity: .7; font-size: 0.9em; display: none; } .search-view .linematch .matchLineNum.show { display: block; } .search-view.wide .monaco-list .monaco-list-row .foldermatch .actionBarContainer, .search-view.wide .monaco-list .monaco-list-row .filematch .actionBarContainer, .search-view .monaco-list .monaco-list-row .linematch .actionBarContainer { flex: 1 0 auto; } .search-view:not(.wide) .monaco-list .monaco-list-row .foldermatch .actionBarContainer, .search-view:not(.wide) .monaco-list .monaco-list-row .filematch .actionBarContainer { flex: 0 0 auto; } .search-view.actions-right .monaco-list .monaco-list-row .foldermatch .actionBarContainer, .search-view.actions-right .monaco-list .monaco-list-row .filematch .actionBarContainer, .search-view.actions-right .monaco-list .monaco-list-row .linematch .actionBarContainer, .search-view:not(.wide) .monaco-list .monaco-list-row .linematch .actionBarContainer { text-align: right; } .search-view .monaco-list .monaco-list-row .monaco-action-bar { line-height: 1em; display: none; padding: 0 0.8em 0 0.4em; } .search-view .monaco-list .monaco-list-row .monaco-action-bar .action-item { margin: 0; } .search-view .monaco-list .monaco-list-row:hover:not(.highlighted) .monaco-action-bar, .search-view .monaco-list .monaco-list-row.focused .monaco-action-bar { display: inline-block; } .search-view .monaco-list .monaco-list-row .monaco-action-bar .action-label { margin-right: 0.2em; margin-top: 4px; background-repeat: no-repeat; width: 16px; height: 16px; } /* Adjusts spacing in high contrast mode so that actions are vertically centered */ .hc-black .monaco-list .monaco-list-row .monaco-action-bar .action-label { margin-top: 2px; } .search-view .action-remove { background: url("action-remove.svg") center center no-repeat; } .search-view .action-replace { background-image: url('replace.svg'); } .search-view .action-replace-all { background: url('replace-all.svg') center center no-repeat; } .hc-black .search-view .action-replace, .vs-dark .search-view .action-replace { background-image: url('replace-inverse.svg'); } .hc-black .search-view .action-replace-all, .vs-dark .search-view .action-replace-all { background: url('replace-all-inverse.svg') center center no-repeat; } .search-view .monaco-count-badge { margin-right: 12px; } .search-view:not(.wide) > .results > .monaco-list .monaco-list-row:hover .filematch .monaco-count-badge, .search-view:not(.wide) > .results > .monaco-list .monaco-list-row:hover .foldermatch .monaco-count-badge, .search-view:not(.wide) > .results > .monaco-list .monaco-list-row:hover .linematch .monaco-count-badge, .search-view:not(.wide) > .results > .monaco-list .monaco-list-row.focused .filematch .monaco-count-badge, .search-view:not(.wide) > .results > .monaco-list .monaco-list-row.focused .foldermatch .monaco-count-badge, .search-view:not(.wide) > .results > .monaco-list .monaco-list-row.focused .linematch .monaco-count-badge { display: none; } .monaco-workbench .search-action.refresh { background: url('Refresh.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-action.refresh, .hc-black .monaco-workbench .search-action.refresh { background: url('Refresh_inverse.svg') center center no-repeat; } .monaco-workbench .search-action.collapse { background: url('CollapseAll.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-action.collapse, .hc-black .monaco-workbench .search-action.collapse { background: url('CollapseAll_inverse.svg') center center no-repeat; } .monaco-workbench .search-action.clear-search-results { background: url('clear-search-results.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-action.clear-search-results, .hc-black .monaco-workbench .search-action.clear-search-results { background: url('clear-search-results-dark.svg') center center no-repeat; } .monaco-workbench .search-action.cancel-search { background: url('stop.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-action.cancel-search, .hc-black .monaco-workbench .search-action.cancel-search { background: url('stop-inverse.svg') center center no-repeat; } .vs .monaco-workbench .search-view .query-details .file-types .controls>.monaco-custom-checkbox.useExcludesAndIgnoreFiles { background: url('excludeSettings.svg') center center no-repeat; } .vs-dark .monaco-workbench .search-view .query-details .file-types .controls>.monaco-custom-checkbox.useExcludesAndIgnoreFiles, .hc-black .monaco-workbench .search-view .query-details .file-types .controls>.monaco-custom-checkbox.useExcludesAndIgnoreFiles { background: url('excludeSettings-dark.svg') center center no-repeat; } .search-view .replace.findInFileMatch { text-decoration: line-through; } .search-view .findInFileMatch, .search-view .replaceMatch { white-space: pre; } .hc-black .monaco-workbench .search-view .replaceMatch, .hc-black .monaco-workbench .search-view .findInFileMatch { background: none !important; box-sizing: border-box; } .monaco-workbench .search-view a.prominent { text-decoration: underline; } /* Theming */ .vs .search-view .search-widget .toggle-replace-button:hover { background-color: rgba(0, 0, 0, 0.1) !important; } .vs-dark .search-view .search-widget .toggle-replace-button:hover { background-color: rgba(255, 255, 255, 0.1) !important; } .vs .search-view .search-widget .toggle-replace-button.collapse { background-image: url('expando-collapsed.svg'); } .vs .search-view .search-widget .toggle-replace-button.expand { background-image: url('expando-expanded.svg'); } .vs-dark .search-view .action-remove, .hc-black .search-view .action-remove { background: url("action-remove-dark.svg") center center no-repeat; } .vs-dark .search-view .message { opacity: .5; } .vs-dark .search-view .foldermatch, .vs-dark .search-view .filematch { padding: 0; } .vs-dark .search-view .search-widget .toggle-replace-button.expand, .hc-black .search-view .search-widget .toggle-replace-button.expand { background-image: url('expando-expanded-dark.svg'); } .vs-dark .search-view .search-widget .toggle-replace-button.collapse, .hc-black .search-view .search-widget .toggle-replace-button.collapse { background-image: url('expando-collapsed-dark.svg'); } /* High Contrast Theming */ .hc-black .monaco-workbench .search-view .foldermatch, .hc-black .monaco-workbench .search-view .filematch, .hc-black .monaco-workbench .search-view .linematch { line-height: 20px; } .vs .panel .search-view .monaco-inputbox { border: 1px solid #ddd; }
src/vs/workbench/contrib/search/browser/media/searchview.css
1
https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe
[ 0.00017481332179158926, 0.0001710456854198128, 0.00016653331113047898, 0.00017095496878027916, 0.0000019479375623632222 ]
{ "id": 1, "code_window": [ "\tstatic readonly OPTION_CHANGE: string = 'optionChange';\n", "\n", "\tprivate contextViewProvider: IContextViewProvider;\n", "\tprivate width: number;\n", "\tprivate placeholder: string;\n", "\tprivate validation?: IInputValidator;\n", "\tprivate label: string;\n", "\tprivate fixFocusOnOptionClickEnabled = true;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/browser/ui/findinput/findInput.ts", "type": "replace", "edit_start_line_idx": 44 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Range } from 'vs/editor/common/core/range'; import { Selection } from 'vs/editor/common/core/selection'; import { IViewModel, IViewWhitespaceViewportData, ViewLineRenderingData, ViewModelDecoration } from 'vs/editor/common/viewModel/viewModel'; export interface IPartialViewLinesViewportData { /** * Value to be substracted from `scrollTop` (in order to vertical offset numbers < 1MM) */ readonly bigNumbersDelta: number; /** * The first (partially) visible line number. */ readonly startLineNumber: number; /** * The last (partially) visible line number. */ readonly endLineNumber: number; /** * relativeVerticalOffset[i] is the `top` position for line at `i` + `startLineNumber`. */ readonly relativeVerticalOffset: number[]; /** * The centered line in the viewport. */ readonly centeredLineNumber: number; /** * The first completely visible line number. */ readonly completelyVisibleStartLineNumber: number; /** * The last completely visible line number. */ readonly completelyVisibleEndLineNumber: number; } /** * Contains all data needed to render at a specific viewport. */ export class ViewportData { public readonly selections: Selection[]; /** * The line number at which to start rendering (inclusive). */ public readonly startLineNumber: number; /** * The line number at which to end rendering (inclusive). */ public readonly endLineNumber: number; /** * relativeVerticalOffset[i] is the `top` position for line at `i` + `startLineNumber`. */ public readonly relativeVerticalOffset: number[]; /** * The viewport as a range (startLineNumber,1) -> (endLineNumber,maxColumn(endLineNumber)). */ public readonly visibleRange: Range; /** * Value to be substracted from `scrollTop` (in order to vertical offset numbers < 1MM) */ public readonly bigNumbersDelta: number; /** * Positioning information about gaps whitespace. */ public readonly whitespaceViewportData: IViewWhitespaceViewportData[]; private readonly _model: IViewModel; constructor( selections: Selection[], partialData: IPartialViewLinesViewportData, whitespaceViewportData: IViewWhitespaceViewportData[], model: IViewModel ) { this.selections = selections; this.startLineNumber = partialData.startLineNumber | 0; this.endLineNumber = partialData.endLineNumber | 0; this.relativeVerticalOffset = partialData.relativeVerticalOffset; this.bigNumbersDelta = partialData.bigNumbersDelta | 0; this.whitespaceViewportData = whitespaceViewportData; this._model = model; this.visibleRange = new Range( partialData.startLineNumber, this._model.getLineMinColumn(partialData.startLineNumber), partialData.endLineNumber, this._model.getLineMaxColumn(partialData.endLineNumber) ); } public getViewLineRenderingData(lineNumber: number): ViewLineRenderingData { return this._model.getViewLineRenderingData(this.visibleRange, lineNumber); } public getDecorationsInViewport(): ViewModelDecoration[] { return this._model.getDecorationsInViewport(this.visibleRange); } }
src/vs/editor/common/viewLayout/viewLinesViewportData.ts
0
https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe
[ 0.0008896398940123618, 0.0002875881327781826, 0.00016702934226486832, 0.0001734050310915336, 0.0002105908642988652 ]
{ "id": 1, "code_window": [ "\tstatic readonly OPTION_CHANGE: string = 'optionChange';\n", "\n", "\tprivate contextViewProvider: IContextViewProvider;\n", "\tprivate width: number;\n", "\tprivate placeholder: string;\n", "\tprivate validation?: IInputValidator;\n", "\tprivate label: string;\n", "\tprivate fixFocusOnOptionClickEnabled = true;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/browser/ui/findinput/findInput.ts", "type": "replace", "edit_start_line_idx": 44 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Event } from 'vs/base/common/event'; import { dispose, IDisposable } from 'vs/base/common/lifecycle'; import { URI, UriComponents } from 'vs/base/common/uri'; import { IWindowService, IWindowsService } from 'vs/platform/windows/common/windows'; import { extHostNamedCustomer } from 'vs/workbench/api/electron-browser/extHostCustomers'; import { ExtHostContext, ExtHostWindowShape, IExtHostContext, MainContext, MainThreadWindowShape } from '../node/extHost.protocol'; @extHostNamedCustomer(MainContext.MainThreadWindow) export class MainThreadWindow implements MainThreadWindowShape { private readonly proxy: ExtHostWindowShape; private disposables: IDisposable[] = []; constructor( extHostContext: IExtHostContext, @IWindowService private readonly windowService: IWindowService, @IWindowsService private readonly windowsService: IWindowsService ) { this.proxy = extHostContext.getProxy(ExtHostContext.ExtHostWindow); Event.latch(windowService.onDidChangeFocus) (this.proxy.$onDidChangeWindowFocus, this.proxy, this.disposables); } dispose(): void { this.disposables = dispose(this.disposables); } $getWindowVisibility(): Promise<boolean> { return this.windowService.isFocused(); } $openUri(uri: UriComponents): Promise<boolean> { return this.windowsService.openExternal(URI.revive(uri).toString(true)); } }
src/vs/workbench/api/electron-browser/mainThreadWindow.ts
0
https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe
[ 0.00017680616292636842, 0.000172209256561473, 0.00016902736388146877, 0.000172329499037005, 0.00000287110833596671 ]
{ "id": 1, "code_window": [ "\tstatic readonly OPTION_CHANGE: string = 'optionChange';\n", "\n", "\tprivate contextViewProvider: IContextViewProvider;\n", "\tprivate width: number;\n", "\tprivate placeholder: string;\n", "\tprivate validation?: IInputValidator;\n", "\tprivate label: string;\n", "\tprivate fixFocusOnOptionClickEnabled = true;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/browser/ui/findinput/findInput.ts", "type": "replace", "edit_start_line_idx": 44 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import 'mocha'; import * as vscode from 'vscode'; import LinkProvider from '../features/documentLinkProvider'; import { InMemoryDocument } from './inMemoryDocument'; const testFileName = vscode.Uri.file('test.md'); const noopToken = new class implements vscode.CancellationToken { private _onCancellationRequestedEmitter = new vscode.EventEmitter<void>(); public onCancellationRequested = this._onCancellationRequestedEmitter.event; get isCancellationRequested() { return false; } }; function getLinksForFile(fileContents: string) { const doc = new InMemoryDocument(testFileName, fileContents); const provider = new LinkProvider(); return provider.provideDocumentLinks(doc, noopToken); } function assertRangeEqual(expected: vscode.Range, actual: vscode.Range) { assert.strictEqual(expected.start.line, actual.start.line); assert.strictEqual(expected.start.character, actual.start.character); assert.strictEqual(expected.end.line, actual.end.line); assert.strictEqual(expected.end.character, actual.end.character); } suite('markdown.DocumentLinkProvider', () => { test('Should not return anything for empty document', () => { const links = getLinksForFile(''); assert.strictEqual(links.length, 0); }); test('Should not return anything for simple document without links', () => { const links = getLinksForFile('# a\nfdasfdfsafsa'); assert.strictEqual(links.length, 0); }); test('Should detect basic http links', () => { const links = getLinksForFile('a [b](https://example.com) c'); assert.strictEqual(links.length, 1); const [link] = links; assertRangeEqual(link.range, new vscode.Range(0, 6, 0, 25)); }); test('Should detect basic workspace links', () => { { const links = getLinksForFile('a [b](./file) c'); assert.strictEqual(links.length, 1); const [link] = links; assertRangeEqual(link.range, new vscode.Range(0, 6, 0, 12)); } { const links = getLinksForFile('a [b](file.png) c'); assert.strictEqual(links.length, 1); const [link] = links; assertRangeEqual(link.range, new vscode.Range(0, 6, 0, 14)); } }); test('Should detect links with title', () => { const links = getLinksForFile('a [b](https://example.com "abc") c'); assert.strictEqual(links.length, 1); const [link] = links; assertRangeEqual(link.range, new vscode.Range(0, 6, 0, 25)); }); test('Should handle links with balanced parens', () => { { const links = getLinksForFile('a [b](https://example.com/a()c) c'); assert.strictEqual(links.length, 1); const [link] = links; assertRangeEqual(link.range, new vscode.Range(0, 6, 0, 30)); } { const links = getLinksForFile('a [b](https://example.com/a(b)c) c'); assert.strictEqual(links.length, 1); const [link] = links; assertRangeEqual(link.range, new vscode.Range(0, 6, 0, 31)); } { // #49011 const links = getLinksForFile('[A link](http://ThisUrlhasParens/A_link(in_parens))'); assert.strictEqual(links.length, 1); const [link] = links; assertRangeEqual(link.range, new vscode.Range(0, 9, 0, 50)); } }); test('Should handle two links without space', () => { const links = getLinksForFile('a ([test](test)[test2](test2)) c'); assert.strictEqual(links.length, 2); const [link1, link2] = links; assertRangeEqual(link1.range, new vscode.Range(0, 10, 0, 14)); assertRangeEqual(link2.range, new vscode.Range(0, 23, 0, 28)); }); // #49238 test('should handle hyperlinked images', () => { { const links = getLinksForFile('[![alt text](image.jpg)](https://example.com)'); assert.strictEqual(links.length, 2); const [link1, link2] = links; assertRangeEqual(link1.range, new vscode.Range(0,13,0,22)); assertRangeEqual(link2.range, new vscode.Range(0,25,0,44)); } { const links = getLinksForFile('[![a]( whitespace.jpg )]( https://whitespace.com )'); assert.strictEqual(links.length, 2); const [link1, link2] = links; assertRangeEqual(link1.range, new vscode.Range(0,7,0,21)); assertRangeEqual(link2.range, new vscode.Range(0,26,0,48)); } { const links = getLinksForFile('[![a](img1.jpg)](file1.txt) text [![a](img2.jpg)](file2.txt)'); assert.strictEqual(links.length, 4); const [link1, link2, link3, link4] = links; assertRangeEqual(link1.range, new vscode.Range(0,6,0,14)); assertRangeEqual(link2.range, new vscode.Range(0,17,0,26)); assertRangeEqual(link3.range, new vscode.Range(0,39,0,47)); assertRangeEqual(link4.range, new vscode.Range(0,50,0,59)); } }); });
extensions/markdown-language-features/src/test/documentLinkProvider.test.ts
0
https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe
[ 0.00017542998830322176, 0.00017300188483204693, 0.0001690373755991459, 0.00017293411656282842, 0.0000015763278042868478 ]
{ "id": 2, "code_window": [ "\tconstructor(parent: HTMLElement | null, contextViewProvider: IContextViewProvider, private readonly _showOptionButtons: boolean, options: IFindInputOptions) {\n", "\t\tsuper();\n", "\t\tthis.contextViewProvider = contextViewProvider;\n", "\t\tthis.width = options.width || 100;\n", "\t\tthis.placeholder = options.placeholder || '';\n", "\t\tthis.validation = options.validation;\n", "\t\tthis.label = options.label || NLS_DEFAULT_LABEL;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/browser/ui/findinput/findInput.ts", "type": "replace", "edit_start_line_idx": 95 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./findInput'; import * as nls from 'vs/nls'; import * as dom from 'vs/base/browser/dom'; import { IMessage as InputBoxMessage, IInputValidator, IInputBoxStyles, HistoryInputBox } from 'vs/base/browser/ui/inputbox/inputBox'; import { IContextViewProvider } from 'vs/base/browser/ui/contextview/contextview'; import { Widget } from 'vs/base/browser/ui/widget'; import { Event, Emitter } from 'vs/base/common/event'; import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { IMouseEvent } from 'vs/base/browser/mouseEvent'; import { KeyCode } from 'vs/base/common/keyCodes'; import { CaseSensitiveCheckbox, WholeWordsCheckbox, RegexCheckbox } from 'vs/base/browser/ui/findinput/findInputCheckboxes'; import { Color } from 'vs/base/common/color'; import { ICheckboxStyles } from 'vs/base/browser/ui/checkbox/checkbox'; export interface IFindInputOptions extends IFindInputStyles { readonly placeholder?: string; readonly width?: number; readonly validation?: IInputValidator; readonly label: string; readonly flexibleHeight?: boolean; readonly appendCaseSensitiveLabel?: string; readonly appendWholeWordsLabel?: string; readonly appendRegexLabel?: string; readonly history?: string[]; } export interface IFindInputStyles extends IInputBoxStyles { inputActiveOptionBorder?: Color; } const NLS_DEFAULT_LABEL = nls.localize('defaultLabel', "input"); export class FindInput extends Widget { static readonly OPTION_CHANGE: string = 'optionChange'; private contextViewProvider: IContextViewProvider; private width: number; private placeholder: string; private validation?: IInputValidator; private label: string; private fixFocusOnOptionClickEnabled = true; private inputActiveOptionBorder?: Color; private inputBackground?: Color; private inputForeground?: Color; private inputBorder?: Color; private inputValidationInfoBorder?: Color; private inputValidationInfoBackground?: Color; private inputValidationInfoForeground?: Color; private inputValidationWarningBorder?: Color; private inputValidationWarningBackground?: Color; private inputValidationWarningForeground?: Color; private inputValidationErrorBorder?: Color; private inputValidationErrorBackground?: Color; private inputValidationErrorForeground?: Color; private regex: RegexCheckbox; private wholeWords: WholeWordsCheckbox; private caseSensitive: CaseSensitiveCheckbox; public domNode: HTMLElement; public inputBox: HistoryInputBox; private readonly _onDidOptionChange = this._register(new Emitter<boolean>()); public readonly onDidOptionChange: Event<boolean /* via keyboard */> = this._onDidOptionChange.event; private readonly _onKeyDown = this._register(new Emitter<IKeyboardEvent>()); public readonly onKeyDown: Event<IKeyboardEvent> = this._onKeyDown.event; private readonly _onMouseDown = this._register(new Emitter<IMouseEvent>()); public readonly onMouseDown: Event<IMouseEvent> = this._onMouseDown.event; private readonly _onInput = this._register(new Emitter<void>()); public readonly onInput: Event<void> = this._onInput.event; private readonly _onKeyUp = this._register(new Emitter<IKeyboardEvent>()); public readonly onKeyUp: Event<IKeyboardEvent> = this._onKeyUp.event; private _onCaseSensitiveKeyDown = this._register(new Emitter<IKeyboardEvent>()); public readonly onCaseSensitiveKeyDown: Event<IKeyboardEvent> = this._onCaseSensitiveKeyDown.event; private _onRegexKeyDown = this._register(new Emitter<IKeyboardEvent>()); public readonly onRegexKeyDown: Event<IKeyboardEvent> = this._onRegexKeyDown.event; constructor(parent: HTMLElement | null, contextViewProvider: IContextViewProvider, private readonly _showOptionButtons: boolean, options: IFindInputOptions) { super(); this.contextViewProvider = contextViewProvider; this.width = options.width || 100; this.placeholder = options.placeholder || ''; this.validation = options.validation; this.label = options.label || NLS_DEFAULT_LABEL; this.inputActiveOptionBorder = options.inputActiveOptionBorder; this.inputBackground = options.inputBackground; this.inputForeground = options.inputForeground; this.inputBorder = options.inputBorder; this.inputValidationInfoBorder = options.inputValidationInfoBorder; this.inputValidationInfoBackground = options.inputValidationInfoBackground; this.inputValidationInfoForeground = options.inputValidationInfoForeground; this.inputValidationWarningBorder = options.inputValidationWarningBorder; this.inputValidationWarningBackground = options.inputValidationWarningBackground; this.inputValidationWarningForeground = options.inputValidationWarningForeground; this.inputValidationErrorBorder = options.inputValidationErrorBorder; this.inputValidationErrorBackground = options.inputValidationErrorBackground; this.inputValidationErrorForeground = options.inputValidationErrorForeground; this.buildDomNode(options.appendCaseSensitiveLabel || '', options.appendWholeWordsLabel || '', options.appendRegexLabel || '', options.history || [], !!options.flexibleHeight); if (parent) { parent.appendChild(this.domNode); } this.onkeydown(this.inputBox.inputElement, (e) => this._onKeyDown.fire(e)); this.onkeyup(this.inputBox.inputElement, (e) => this._onKeyUp.fire(e)); this.oninput(this.inputBox.inputElement, (e) => this._onInput.fire()); this.onmousedown(this.inputBox.inputElement, (e) => this._onMouseDown.fire(e)); } public enable(): void { dom.removeClass(this.domNode, 'disabled'); this.inputBox.enable(); this.regex.enable(); this.wholeWords.enable(); this.caseSensitive.enable(); } public disable(): void { dom.addClass(this.domNode, 'disabled'); this.inputBox.disable(); this.regex.disable(); this.wholeWords.disable(); this.caseSensitive.disable(); } public setFocusInputOnOptionClick(value: boolean): void { this.fixFocusOnOptionClickEnabled = value; } public setEnabled(enabled: boolean): void { if (enabled) { this.enable(); } else { this.disable(); } } public clear(): void { this.clearValidation(); this.setValue(''); this.focus(); } public setWidth(newWidth: number): void { this.width = newWidth; this.domNode.style.width = this.width + 'px'; this.contextViewProvider.layout(); this.setInputWidth(); } public getValue(): string { return this.inputBox.value; } public setValue(value: string): void { if (this.inputBox.value !== value) { this.inputBox.value = value; } } public onSearchSubmit(): void { this.inputBox.addToHistory(); } public style(styles: IFindInputStyles): void { this.inputActiveOptionBorder = styles.inputActiveOptionBorder; this.inputBackground = styles.inputBackground; this.inputForeground = styles.inputForeground; this.inputBorder = styles.inputBorder; this.inputValidationInfoBackground = styles.inputValidationInfoBackground; this.inputValidationInfoForeground = styles.inputValidationInfoForeground; this.inputValidationInfoBorder = styles.inputValidationInfoBorder; this.inputValidationWarningBackground = styles.inputValidationWarningBackground; this.inputValidationWarningForeground = styles.inputValidationWarningForeground; this.inputValidationWarningBorder = styles.inputValidationWarningBorder; this.inputValidationErrorBackground = styles.inputValidationErrorBackground; this.inputValidationErrorForeground = styles.inputValidationErrorForeground; this.inputValidationErrorBorder = styles.inputValidationErrorBorder; this.applyStyles(); } protected applyStyles(): void { if (this.domNode) { const checkBoxStyles: ICheckboxStyles = { inputActiveOptionBorder: this.inputActiveOptionBorder, }; this.regex.style(checkBoxStyles); this.wholeWords.style(checkBoxStyles); this.caseSensitive.style(checkBoxStyles); const inputBoxStyles: IInputBoxStyles = { inputBackground: this.inputBackground, inputForeground: this.inputForeground, inputBorder: this.inputBorder, inputValidationInfoBackground: this.inputValidationInfoBackground, inputValidationInfoForeground: this.inputValidationInfoForeground, inputValidationInfoBorder: this.inputValidationInfoBorder, inputValidationWarningBackground: this.inputValidationWarningBackground, inputValidationWarningForeground: this.inputValidationWarningForeground, inputValidationWarningBorder: this.inputValidationWarningBorder, inputValidationErrorBackground: this.inputValidationErrorBackground, inputValidationErrorForeground: this.inputValidationErrorForeground, inputValidationErrorBorder: this.inputValidationErrorBorder }; this.inputBox.style(inputBoxStyles); } } public select(): void { this.inputBox.select(); } public focus(): void { this.inputBox.focus(); } public getCaseSensitive(): boolean { return this.caseSensitive.checked; } public setCaseSensitive(value: boolean): void { this.caseSensitive.checked = value; this.setInputWidth(); } public getWholeWords(): boolean { return this.wholeWords.checked; } public setWholeWords(value: boolean): void { this.wholeWords.checked = value; this.setInputWidth(); } public getRegex(): boolean { return this.regex.checked; } public setRegex(value: boolean): void { this.regex.checked = value; this.setInputWidth(); this.validate(); } public focusOnCaseSensitive(): void { this.caseSensitive.focus(); } public focusOnRegex(): void { this.regex.focus(); } private _lastHighlightFindOptions: number = 0; public highlightFindOptions(): void { dom.removeClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions)); this._lastHighlightFindOptions = 1 - this._lastHighlightFindOptions; dom.addClass(this.domNode, 'highlight-' + (this._lastHighlightFindOptions)); } private setInputWidth(): void { let w = this.width - this.caseSensitive.width() - this.wholeWords.width() - this.regex.width(); this.inputBox.width = w; this.inputBox.layout(); } private buildDomNode(appendCaseSensitiveLabel: string, appendWholeWordsLabel: string, appendRegexLabel: string, history: string[], flexibleHeight: boolean): void { this.domNode = document.createElement('div'); this.domNode.style.width = this.width + 'px'; dom.addClass(this.domNode, 'monaco-findInput'); this.inputBox = this._register(new HistoryInputBox(this.domNode, this.contextViewProvider, { placeholder: this.placeholder || '', ariaLabel: this.label || '', validationOptions: { validation: this.validation }, inputBackground: this.inputBackground, inputForeground: this.inputForeground, inputBorder: this.inputBorder, inputValidationInfoBackground: this.inputValidationInfoBackground, inputValidationInfoForeground: this.inputValidationInfoForeground, inputValidationInfoBorder: this.inputValidationInfoBorder, inputValidationWarningBackground: this.inputValidationWarningBackground, inputValidationWarningForeground: this.inputValidationWarningForeground, inputValidationWarningBorder: this.inputValidationWarningBorder, inputValidationErrorBackground: this.inputValidationErrorBackground, inputValidationErrorForeground: this.inputValidationErrorForeground, inputValidationErrorBorder: this.inputValidationErrorBorder, history, flexibleHeight })); this.regex = this._register(new RegexCheckbox({ appendTitle: appendRegexLabel, isChecked: false, inputActiveOptionBorder: this.inputActiveOptionBorder })); this._register(this.regex.onChange(viaKeyboard => { this._onDidOptionChange.fire(viaKeyboard); if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) { this.inputBox.focus(); } this.setInputWidth(); this.validate(); })); this._register(this.regex.onKeyDown(e => { this._onRegexKeyDown.fire(e); })); this.wholeWords = this._register(new WholeWordsCheckbox({ appendTitle: appendWholeWordsLabel, isChecked: false, inputActiveOptionBorder: this.inputActiveOptionBorder })); this._register(this.wholeWords.onChange(viaKeyboard => { this._onDidOptionChange.fire(viaKeyboard); if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) { this.inputBox.focus(); } this.setInputWidth(); this.validate(); })); this.caseSensitive = this._register(new CaseSensitiveCheckbox({ appendTitle: appendCaseSensitiveLabel, isChecked: false, inputActiveOptionBorder: this.inputActiveOptionBorder })); this._register(this.caseSensitive.onChange(viaKeyboard => { this._onDidOptionChange.fire(viaKeyboard); if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) { this.inputBox.focus(); } this.setInputWidth(); this.validate(); })); this._register(this.caseSensitive.onKeyDown(e => { this._onCaseSensitiveKeyDown.fire(e); })); if (this._showOptionButtons) { this.inputBox.inputElement.style.paddingRight = (this.caseSensitive.width() + this.wholeWords.width() + this.regex.width()) + 'px'; } // Arrow-Key support to navigate between options let indexes = [this.caseSensitive.domNode, this.wholeWords.domNode, this.regex.domNode]; this.onkeydown(this.domNode, (event: IKeyboardEvent) => { if (event.equals(KeyCode.LeftArrow) || event.equals(KeyCode.RightArrow) || event.equals(KeyCode.Escape)) { let index = indexes.indexOf(<HTMLElement>document.activeElement); if (index >= 0) { let newIndex: number = -1; if (event.equals(KeyCode.RightArrow)) { newIndex = (index + 1) % indexes.length; } else if (event.equals(KeyCode.LeftArrow)) { if (index === 0) { newIndex = indexes.length - 1; } else { newIndex = index - 1; } } if (event.equals(KeyCode.Escape)) { indexes[index].blur(); } else if (newIndex >= 0) { indexes[newIndex].focus(); } dom.EventHelper.stop(event, true); } } }); this.setInputWidth(); let controls = document.createElement('div'); controls.className = 'controls'; controls.style.display = this._showOptionButtons ? 'block' : 'none'; controls.appendChild(this.caseSensitive.domNode); controls.appendChild(this.wholeWords.domNode); controls.appendChild(this.regex.domNode); this.domNode.appendChild(controls); } public validate(): void { if (this.inputBox) { this.inputBox.validate(); } } public showMessage(message: InputBoxMessage): void { if (this.inputBox) { this.inputBox.showMessage(message); } } public clearMessage(): void { if (this.inputBox) { this.inputBox.hideMessage(); } } private clearValidation(): void { if (this.inputBox) { this.inputBox.hideMessage(); } } public dispose(): void { super.dispose(); } }
src/vs/base/browser/ui/findinput/findInput.ts
1
https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe
[ 0.9980179071426392, 0.024393854662775993, 0.00016455329023301601, 0.00017087985179387033, 0.14858083426952362 ]
{ "id": 2, "code_window": [ "\tconstructor(parent: HTMLElement | null, contextViewProvider: IContextViewProvider, private readonly _showOptionButtons: boolean, options: IFindInputOptions) {\n", "\t\tsuper();\n", "\t\tthis.contextViewProvider = contextViewProvider;\n", "\t\tthis.width = options.width || 100;\n", "\t\tthis.placeholder = options.placeholder || '';\n", "\t\tthis.validation = options.validation;\n", "\t\tthis.label = options.label || NLS_DEFAULT_LABEL;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/vs/base/browser/ui/findinput/findInput.ts", "type": "replace", "edit_start_line_idx": 95 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- * Please make sure to make edits in the .ts file at https://github.com/Microsoft/vscode-loader/ *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------*/ 'use strict'; var NLSLoaderPlugin; (function (NLSLoaderPlugin) { var Environment = /** @class */ (function () { function Environment() { this._detected = false; this._isPseudo = false; } Object.defineProperty(Environment.prototype, "isPseudo", { get: function () { this._detect(); return this._isPseudo; }, enumerable: true, configurable: true }); Environment.prototype._detect = function () { if (this._detected) { return; } this._detected = true; this._isPseudo = (typeof document !== 'undefined' && document.location && document.location.hash.indexOf('pseudo=true') >= 0); }; return Environment; }()); function _format(message, args, env) { var result; if (args.length === 0) { result = message; } else { result = message.replace(/\{(\d+)\}/g, function (match, rest) { var index = rest[0]; var arg = args[index]; var result = match; if (typeof arg === 'string') { result = arg; } else if (typeof arg === 'number' || typeof arg === 'boolean' || arg === undefined || arg === null) { result = String(arg); } return result; }); } if (env.isPseudo) { // FF3B and FF3D is the Unicode zenkaku representation for [ and ] result = '\uFF3B' + result.replace(/[aouei]/g, '$&$&') + '\uFF3D'; } return result; } function findLanguageForModule(config, name) { var result = config[name]; if (result) return result; result = config['*']; if (result) return result; return null; } function localize(env, data, message) { var args = []; for (var _i = 3; _i < arguments.length; _i++) { args[_i - 3] = arguments[_i]; } return _format(message, args, env); } function createScopedLocalize(scope, env) { return function (idx, defaultValue) { var restArgs = Array.prototype.slice.call(arguments, 2); return _format(scope[idx], restArgs, env); }; } var NLSPlugin = /** @class */ (function () { function NLSPlugin(env) { var _this = this; this._env = env; this.localize = function (data, message) { var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } return localize.apply(undefined, [_this._env, data, message].concat(args)); }; } NLSPlugin.prototype.setPseudoTranslation = function (value) { this._env._isPseudo = value; }; NLSPlugin.prototype.create = function (key, data) { return { localize: createScopedLocalize(data[key], this._env) }; }; NLSPlugin.prototype.load = function (name, req, load, config) { var _this = this; config = config || {}; if (!name || name.length === 0) { load({ localize: this.localize }); } else { var pluginConfig = config['vs/nls'] || {}; var language = pluginConfig.availableLanguages ? findLanguageForModule(pluginConfig.availableLanguages, name) : null; var suffix = '.nls'; if (language !== null && language !== NLSPlugin.DEFAULT_TAG) { suffix = suffix + '.' + language; } var messagesLoaded_1 = function (messages) { if (Array.isArray(messages)) { messages.localize = createScopedLocalize(messages, _this._env); } else { messages.localize = createScopedLocalize(messages[name], _this._env); } load(messages); }; if (typeof pluginConfig.loadBundle === 'function') { pluginConfig.loadBundle(name, language, function (err, messages) { // We have an error. Load the English default strings to not fail if (err) { req([name + '.nls'], messagesLoaded_1); } else { messagesLoaded_1(messages); } }); } else { req([name + suffix], messagesLoaded_1); } } }; NLSPlugin.DEFAULT_TAG = 'i-default'; return NLSPlugin; }()); NLSLoaderPlugin.NLSPlugin = NLSPlugin; define('vs/nls', new NLSPlugin(new Environment())); })(NLSLoaderPlugin || (NLSLoaderPlugin = {}));
src/vs/nls.js
0
https://github.com/microsoft/vscode/commit/bbff11633c7e56e7fd5d16cc20daa9a3284afbfe
[ 0.0001749849325278774, 0.00016902846982702613, 0.00016499069170095026, 0.00016894866712391376, 0.0000026744598926597973 ]