message: moved findAddressBook back to the class

diff:
],
"scripts": {
"build": "npm run clean && npm run build-version && npm run build-lib && npm run build-types && npm run build-webpack",
- "build-lib": "babel src -d lib --source-maps --extensions '.ts,.js'",
+ "build-lib": "babel src -d lib --source-maps --extensions \".ts,.js\"",
"build-types": "tsc --emitDeclarationOnly",
"build-version": "sh ./timestamp.sh > src/versionInfo.ts && eslint \"src/versionInfo.ts\" --fix",
"build-webpack": "webpack",
- "watch": "npm run build-version && babel src --out-dir lib --watch --source-maps --extensions '.ts,.js'",
+ "watch": "npm run build-version && babel src --out-dir lib --watch --source-maps --extensions \".ts,.js\"",
"clean": "rm -rf lib",
"coverage": "jest --coverage --collectCoverageFrom=src/**/*.[jt]s",
"lint": "eslint \"src/**/*.js\" \"src/**/*.ts\" \"test/**/*.ts\"",

diff:
@@ -28,6 +28,7 @@ export class PeoplePicker {
this.groupPickedCb = groupPickedCb
this.selectedgroup = this.options.selectedgroup // current selected group if any
this.onSelectGroup = this.onSelectGroup.bind(this)
+ this.findAddressBook = this.findAddressBook.bind(this)
}
render () {
@@ -50,7 +51,7 @@ export class PeoplePicker {
container.appendChild(selectedGroup)
container.appendChild(changeGroupButton)
} else {
- findAddressBook(this.typeIndex)
+ this.findAddressBook(this.typeIndex)
.then(({ book }) => {
const chooseExistingGroupButton = document.createElement('button')
chooseExistingGroupButton.textContent = escape(
@@ -105,6 +106,40 @@ export class PeoplePicker {
return this
}
+ findAddressBook (typeIndex) {
+ return new Promise((resolve, reject) => {
+ kb.fetcher.nowOrWhenFetched(typeIndex, (ok, err) => {
+ if (!ok) {
+ return reject(err)
+ }
+ const bookRegistration = kb.any(
+ null,
+ ns.solid('forClass'),
+ ns.vcard('AddressBook')
+ )
+ if (!bookRegistration) {
+ return reject(
+ new Error(
+ 'no address book registered in the solid type index ' + typeIndex
+ )
+ )
+ }
+ const book = kb.any(bookRegistration, ns.solid('instance'))
+ if (!book) {
+ return reject(new Error('incomplete address book registration'))
+ }
+ kb.fetcher
+ .load(book)
+ .then(function (_xhr) {
+ return resolve({ book })
+ })
+ .catch(function (err) {
+ return reject(new Error('Could not load address book ' + err))
+ })
+ })
+ })
+ }
+
onSelectGroup (group) {
this.selectedgroup = group
this.groupPickedCb(group)
@@ -440,41 +475,6 @@ function indexes(book) {
groupContainer: kb.sym(book.dir().uri + 'Group/')
}
}
-// Below are functions that are exported to make testing easier
-// @ignore exporting this only for the unit test
-export function findAddressBook(typeIndex) {
- return new Promise((resolve, reject) => {
- kb.fetcher.nowOrWhenFetched(typeIndex, (ok, err) => {
- if (!ok) {
- return reject(err)
- }
- const bookRegistration = kb.any(
- null,
- ns.solid('forClass'),
- ns.vcard('AddressBook')
- )
- if (!bookRegistration) {
- return reject(
- new Error(
- 'no address book registered in the solid type index ' + typeIndex
- )
- )
- }
- const book = kb.any(bookRegistration, ns.solid('instance'))
- if (!book) {
- return reject(new Error('incomplete address book registration'))
- }
- kb.fetcher
- .load(book)
- .then(function(_xhr) {
- return resolve({ book })
- })
- .catch(function(err) {
- return reject(new Error('Could not load address book ' + err))
- })
- })
- })
-}
export function createNewGroup (book, defaultNewGroupName) {
const { groupIndex, groupContainer } = indexes(book)

diff:
@@ -7,7 +7,6 @@ import {
Group,
GroupBuilder,
Person,
- findAddressBook,
createNewGroup
} from '../../../src/widgets/peoplePicker'
import ns from '../../../src/ns'
@@ -21,10 +20,10 @@ const element = dom.createElement('div')
describe('FindAddressBook', () => {
it('exists', () => {
- expect(findAddressBook).toBeInstanceOf(Function)
+ expect(new PeoplePicker().findAddressBook).toBeInstanceOf(Function)
})
it('runs', () => {
- expect(findAddressBook('typeIndex')).toMatchObject({})
+ expect(new PeoplePicker().findAddressBook('typeIndex')).toMatchObject({})
})
it('should call kb.any and spy load when callback is successful ', () => {
@@ -35,7 +34,7 @@ describe('FindAddressBook', () => {
.mockReturnValueOnce('book')
.mockReturnValueOnce('book')
const spyLoad = jest.spyOn(fetcher, 'load').mockResolvedValue('book')
- findAddressBook('typeIndex')
+ new PeoplePicker().findAddressBook('typeIndex')
const callback: any = spyOnNowOrWhenFetched.mock.calls[0][1]
callback(true, undefined)
@@ -51,7 +50,7 @@ describe('FindAddressBook', () => {
.mockReturnValue('book')
.mockReturnValueOnce('book')
const spyLoad = jest.spyOn(fetcher, 'load').mockResolvedValue('book')
- findAddressBook('typeIndex')
+ new PeoplePicker().findAddressBook('typeIndex')
const callback: any = spyOnNowOrWhenFetched.mock.calls[0][1]
callback(false, undefined)
// expect(spyOnNowOrWhenFetched).toThrowError()
@@ -63,7 +62,7 @@ describe('FindAddressBook', () => {
.mockReturnValueOnce(null)
.mockReturnValueOnce('book')
const spyLoad = jest.spyOn(fetcher, 'load').mockResolvedValue('book')
- findAddressBook('typeIndex')
+ new PeoplePicker().findAddressBook('typeIndex')
const callback: any = spyOnNowOrWhenFetched.mock.calls[0][1]
callback(true, undefined)
// expect(spyOnNowOrWhenFetched).toThrowError()
@@ -76,7 +75,7 @@ describe('FindAddressBook', () => {
.mockReturnValueOnce('bookregs')
.mockReturnValueOnce(null)
const spyLoad = jest.spyOn(fetcher, 'load').mockResolvedValue('book')
- findAddressBook('typeIndex')
+ new PeoplePicker().findAddressBook('typeIndex')
const callback: any = spyOnNowOrWhenFetched.mock.calls[0][1]
callback(true, undefined)
// expect(spyOnNowOrWhenFetched).toThrowError()
@@ -91,7 +90,7 @@ describe('FindAddressBook', () => {
.mockReturnValue('book')
.mockReturnValue('book')
const spyLoad = jest.spyOn(fetcher, 'load').mockRejectedValue(new Error())
- findAddressBook('typeIndex')
+ new PeoplePicker().findAddressBook('typeIndex')
const callback: any = spyOnNowOrWhenFetched.mock.calls[0][1]
callback(true, undefined)
// expect(spyOnNowOrWhenFetched).toThrowError()

original_message: moved findAddressBook back to the class


message: removed single quotes and changed test script to use && instead of ;

change_type: MODIFY

diff:
],
"scripts": {
"build": "npm run clean && npm run build-version && npm run build-lib && npm run build-types && npm run build-webpack",
- "build-lib": "babel src -d lib --source-maps --extensions '.ts,.js'",
+ "build-lib": "babel src -d lib --source-maps --extensions \".ts,.js\"",
"build-types": "tsc --emitDeclarationOnly",
"build-version": "sh ./timestamp.sh > src/versionInfo.ts && eslint \"src/versionInfo.ts\" --fix",
"build-webpack": "webpack",
"lint-fix": "eslint \"src/**/*.js\" \"src/**/*.ts\" --fix",
"jest": "jest",
"test:debug": "node --inspect-brk ./node_modules/jest/bin/jest.js --runInBand --watch",
- "test": "npm run build; npm run lint; npm run jest",
+ "test": "npm run build && npm run lint && npm run jest",
"doc": "typedoc --out ./Documentation/api/ ./src/",
"prepublishOnly": "npm test && npm run build",
"postpublish": "git push origin master --follow-tags"

license: MIT License

repo: solidos/solid-ui


message: changed from Inline snapshots to snapshots in a file

change_type: ADD

diff:
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`GroupBuilder.add runs: Promise {} 1`] = `Promise {}`;
+
+exports[`GroupBuilder.handleRemove runs: [Function] 1`] = `[Function]`;
+
+exports[`GroupBuilder.render runs:
+GroupBuilder {
+ "book": Object {
+ "dir": [Function],
+ "doc": [Function],
+ "elements": Array [],
+ "sameTerm": [Function],
+ "uri": "uri",
+ "value": "",
+ },
+ "doneBuildingCb": [Function],
+ "element":

+

+
+ Group Name:
+ <input
+ type="text"
+ />
+
+ <button>
+ Done
+ </button>
+

+
,
+ "group": Object {
+ "dir": [Function],
+ "doc": [Function],
+ "elements": Array [],
+ "sameTerm": [Function],
+ "uri": "uri",
+ "value": "",
+ },
+ "groupChangedCb": [Function],
+ "onGroupChanged": [Function],
+}
+ 1`] = `
+GroupBuilder {
+ "book": Object {
+ "dir": [Function],
+ "doc": [Function],
+ "elements": Array [],
+ "sameTerm": [Function],
+ "uri": "uri",
+ "value": "",
+ },
+ "doneBuildingCb": [Function],
+ "element":

+

+
+ Group Name:
+ <input
+ type="text"
+ />
+
+ <button>
+ Done
+ </button>
+

+
,
+ "group": Object {
+ "dir": [Function],
+ "doc": [Function],
+ "elements": Array [],
+ "sameTerm": [Function],
+ "uri": "uri",
+ "value": "",
+ },
+ "groupChangedCb": [Function],
+ "onGroupChanged": [Function],
+}
+`;
+
+exports[`GroupBuilder.setGroupName runs: Promise {} 1`] = `Promise {}`;
+
+exports[`PeoplePicker.render .. type index ...:
+ PeoplePicker {
+ "element":

+

+
,
+ "groupPickedCb": [Function],
+ "onSelectGroup": [Function],
+ "options": Object {
+ "selectedGroup": Object {},
+ },
+ "selectedgroup": undefined,
+ "typeIndex": "publicTypeIndex",
+ }
+ 1`] = `
+PeoplePicker {
+ "element":

+

+
,
+ "findAddressBook": [Function],
+ "groupPickedCb": [Function],
+ "onSelectGroup": [Function],
+ "options": Object {
+ "selectedGroup": Object {},
+ },
+ "selectedgroup": undefined,
+ "typeIndex": "publicTypeIndex",
+}
+`;
+
+exports[`PeoplePicker.render mocking kb any for book:
+PeoplePicker {
+ "element":

+

+
,
+ "groupPickedCb": [Function],
+ "onSelectGroup": [Function],
+ "options": Object {
+ "selectedGroup": true,
+ },
+ "selectedgroup": undefined,
+ "typeIndex": Object {},
+}
+ 1`] = `
+PeoplePicker {
+ "element":

+

+
,
+ "findAddressBook": [Function],
+ "groupPickedCb": [Function],
+ "onSelectGroup": [Function],
+ "options": Object {
+ "selectedGroup": true,
+ },
+ "selectedgroup": undefined,
+ "typeIndex": Object {},
+}
+`;
+
+exports[`PeoplePicker.render runs 2:
+ PeoplePicker {
+ "element":

+

+
,
+ "groupPickedCb": [Function],
+ "onSelectGroup": [Function],
+ "options": Object {
+ "selectedGroup": true,
+ },
+ "selectedgroup": undefined,
+ "typeIndex": Object {},
+ }
+ 1`] = `
+PeoplePicker {
+ "element":

+

+
,
+ "findAddressBook": [Function],
+ "groupPickedCb": [Function],
+ "onSelectGroup": [Function],
+ "options": Object {
+ "selectedGroup": true,
+ },
+ "selectedgroup": undefined,
+ "typeIndex": Object {},
+}
+`;
+
+exports[`PeoplePicker.render runs:
+ PeoplePicker {
+ "element":

+

+
,
+ "groupPickedCb": [Function],
+ "onSelectGroup": [Function],
+ "options": Object {
+ "selectedGroup": false,
+ },
+ "selectedgroup": undefined,
+ "typeIndex": Object {},
+ }
+ 1`] = `
+PeoplePicker {
+ "element":

+

+
,
+ "findAddressBook": [Function],
+ "groupPickedCb": [Function],
+ "onSelectGroup": [Function],
+ "options": Object {
+ "selectedGroup": false,
+ },
+ "selectedgroup": undefined,
+ "typeIndex": Object {},
+}
+`;
+
+exports[`Person.render runs:
+Person {
+ "element":

+

+
+
+ undefined
+
+ <button
+ style="margin: 5px;"
+ >
+ Remove
+ </button>
+

+
,
+ "handleRemove": true,
+ "webIdNode":
,
+}
+ 1`] = `
+Person {
+ "element":

+

+
+
+ undefined
+
+ <button
+ style="margin: 5px;"
+ >
+ Remove
+ </button>
+

+
,
+ "handleRemove": true,
+ "webIdNode":
,
+}
+`;

diff:
@@ -114,8 +114,8 @@ describe('PeoplePicker.render', () => {
it('exists', () => {
expect(new PeoplePicker().render).toBeInstanceOf(Function)
})
- // skipping snapshots for now until decision is made about prettier
- it.skip('runs', () => {
+
+ it('runs', () => {
const typeIndex = {}
const groupPickedCb = () => { }
const options = { selectedGroup: false }
@@ -126,7 +126,7 @@ describe('PeoplePicker.render', () => {
groupPickedCb,
options
)
- expect(peoplePicker.render()).toMatchInlineSnapshot(`
+ expect(peoplePicker.render()).toMatchSnapshot(`
PeoplePicker {
"element":

 {
}
`)
})
- // skipping snapshots for now until decision is made about prettier
- it.skip('.. type index ...', () => {
+
+ it('.. type index ...', () => {
const typeIndex = 'publicTypeIndex'
const groupPickedCb = () => { }
const options = { selectedGroup: {} }
@@ -170,7 +170,7 @@ describe('PeoplePicker.render', () => {
// expect(spySecondAny).toBeCalled()
// expect(spyLoad).toBeCalled()
- expect(peoplePicker.render()).toMatchInlineSnapshot(`
+ expect(peoplePicker.render()).toMatchSnapshot(`
PeoplePicker {
"element":

 {
expect(spy).toHaveBeenCalledTimes(2)
})
// skipping snapshots for now until decision is made about prettier
- it.skip('runs 2', () => {
+ it('runs 2', () => {
const typeIndex = {}
const groupPickedCb = () => { }
const options = { selectedGroup: true }
@@ -216,7 +216,7 @@ describe('PeoplePicker.render', () => {
groupPickedCb,
options
)
- expect(peoplePicker.render()).toMatchInlineSnapshot(`
+ expect(peoplePicker.render()).toMatchSnapshot(`
PeoplePicker {
"element":

 {
}
`)
})
- it.skip('mocking kb any for book', () => {
+ it('mocking kb any for book', () => {
const mockKbAny: jest.SpyInstance = require('../../../src/store').any
mockKbAny.mockReturnValueOnce(null)
const typeIndex = {}
@@ -246,7 +246,7 @@ describe('PeoplePicker.render', () => {
groupPickedCb,
options
)
- expect(peoplePicker.render()).toMatchInlineSnapshot(`
+ expect(peoplePicker.render()).toMatchSnapshot(`
PeoplePicker {
"element":

 {
it('exists', () => {
expect(new GroupBuilder().render).toBeInstanceOf(Function)
})
- // skipping snapshots for now until decision is made about prettier
- it.skip('runs', () => {
+
+ it('runs', () => {
jest.clearAllMocks()
const groupArg = RdfLib.sym('')
const book = RdfLib.sym('')
@@ -426,7 +426,7 @@ describe('GroupBuilder.render', () => {
// @@ TODO just trying to touch the code at this point. I want
// to make the test better than toBe(undefined)
expect(groupBuilder.onGroupChanged()).toBe(undefined)
- expect(groupBuilder.render()).toMatchInlineSnapshot(`
+ expect(groupBuilder.render()).toMatchSnapshot(`
GroupBuilder {
"book": Object {
"dir": [Function],
@@ -501,7 +501,7 @@ describe('GroupBuilder.add', () => {
handler,
handler
)
- expect(groupBuilder.add()).toMatchInlineSnapshot(`Promise {}`)
+ expect(groupBuilder.add()).toMatchSnapshot(`Promise {}`)
})
// need to to nowOrWhenFetched
it('not okay it returns an error -- callback false', () => {
@@ -554,8 +554,8 @@ describe('GroupBuilder.handleRemove', () => {
it('exists', () => {
expect(new GroupBuilder().handleRemove).toBeInstanceOf(Function)
})
- // skipping snapshots for now until decision is made about prettier
- it.skip('runs', () => {
+
+ it('runs', () => {
const groupArg = RdfLib.sym('')
const book = RdfLib.sym('')
const handler = () => { }
@@ -567,7 +567,7 @@ describe('GroupBuilder.handleRemove', () => {
handler,
handler
)
- expect(groupBuilder.handleRemove()).toMatchInlineSnapshot('[Function]')
+ expect(groupBuilder.handleRemove()).toMatchSnapshot('[Function]')
})
})
@@ -578,7 +578,7 @@ describe('GroupBuilder.setGroupName', () => {
// @@ TODO once I added the code for findAddressBook, a namedGraph
// error is popping up on line 392 Need to look into this
// think groupArg may need to be adjusted
- it.skip('runs', () => {
+ it('runs', () => {
const groupArg = RdfLib.sym('testing')
const book = RdfLib.sym('')
const handler = () => { }
@@ -590,7 +590,7 @@ describe('GroupBuilder.setGroupName', () => {
handler,
handler
)
- expect(groupBuilder.setGroupName()).toMatchInlineSnapshot('Promise {}')
+ expect(groupBuilder.setGroupName()).toMatchSnapshot('Promise {}')
})
})
@@ -603,14 +603,14 @@ describe('Person.render', () => {
it('exists', () => {
expect(new Person().render).toBeInstanceOf(Function)
})
- // skipping snapshots for now until decision is made about prettier
- it.skip('runs', () => {
+
+ it('runs', () => {
// @@ TODO Ask Michiel or Vince about what a proper WebIdNode should be
const webIdNode = document.createElement('div')
const element = document.createElement('div')
const handleRemove = true
const person = new Person(webIdNode, element, handleRemove)
- expect(person.render()).toMatchInlineSnapshot(`
+ expect(person.render()).toMatchSnapshot(`
Person {
"element":

<div


message: took out this.findAddressBook assignment

diff:
@@ -28,7 +28,7 @@ export class PeoplePicker {
this.groupPickedCb = groupPickedCb
this.selectedgroup = this.options.selectedgroup // current selected group if any
this.onSelectGroup = this.onSelectGroup.bind(this)
- this.findAddressBook = this.findAddressBook.bind(this)
+
}
render() {


message: moved createNewGroup back to PeoplePicker and changed tests for it

diff:
@@ -28,7 +28,6 @@ export class PeoplePicker {
this.groupPickedCb = groupPickedCb
this.selectedgroup = this.options.selectedgroup // current selected group if any
this.onSelectGroup = this.onSelectGroup.bind(this)
-
}
render () {
@@ -66,7 +65,7 @@ export class PeoplePicker {
createNewGroupButton.textContent = escape('Create a new group')
createNewGroupButton.style.margin = 'auto'
createNewGroupButton.addEventListener('click', _event => {
- createNewGroup(book, this.options.defaultNewGroupName)
+ this.createNewGroup(book, this.options.defaultNewGroupName)
.then(({ group }) => {
new GroupBuilder(
this.element,
@@ -140,6 +139,46 @@ export class PeoplePicker {
})
}
+ createNewGroup (book, defaultNewGroupName) {
+ const { groupIndex, groupContainer } = indexes(book)
+ const group = rdf.sym(
+ `${groupContainer.uri}${uuid.v4().slice(0, 8)}.ttl#this`
+ )
+ const name = defaultNewGroupName || 'Untitled Group'
+
+ // NOTE that order matters here. Unfortunately this type of update is
+ // non-atomic in that solid requires us to send two PATCHes, either of which
+ // might fail.
+ const patchPromises = [group.doc(), groupIndex].map(doc => {
+ const typeStatement = rdf.st(group, ns.rdf('type'), ns.vcard('Group'), doc)
+ const nameStatement = rdf.st(group, ns.vcard('fn'), name, group.doc(), doc)
+ const includesGroupStatement = rdf.st(
+ book,
+ ns.vcard('includesGroup'),
+ group,
+ doc
+ )
+ const toIns = doc.equals(groupIndex)
+ ? [typeStatement, nameStatement, includesGroupStatement]
+ : [typeStatement, nameStatement]
+ return patch(doc.uri, { toIns }).then(() => {
+ toIns.forEach(st => {
+ kb.add(st)
+ })
+ })
+ })
+ return Promise.all(patchPromises)
+ .then(() => ({ group }))
+ .catch(err => {
+ console.log('Could not create new group. PATCH failed ' + err)
+ throw new Error(
+ `Couldn't create new group. PATCH failed for (${
+ err.xhr ? err.xhr.responseURL : ''
+ } )`
+ )
+ })
+ }
+
onSelectGroup (group) {
this.selectedgroup = group
this.groupPickedCb(group)
@@ -475,43 +514,3 @@ function indexes(book) {
groupContainer: kb.sym(book.dir().uri + 'Group/')
}
}
-
-export function createNewGroup(book, defaultNewGroupName) {
- const { groupIndex, groupContainer } = indexes(book)
- const group = rdf.sym(
- `${groupContainer.uri}${uuid.v4().slice(0, 8)}.ttl#this`
- )
- const name = defaultNewGroupName || 'Untitled Group'
-
- // NOTE that order matters here. Unfortunately this type of update is
- // non-atomic in that solid requires us to send two PATCHes, either of which
- // might fail.
- const patchPromises = [group.doc(), groupIndex].map(doc => {
- const typeStatement = rdf.st(group, ns.rdf('type'), ns.vcard('Group'), doc)
- const nameStatement = rdf.st(group, ns.vcard('fn'), name, group.doc(), doc)
- const includesGroupStatement = rdf.st(
- book,
- ns.vcard('includesGroup'),
- group,
- doc
- )
- const toIns = doc.equals(groupIndex)
- ? [typeStatement, nameStatement, includesGroupStatement]
- : [typeStatement, nameStatement]
- return patch(doc.uri, { toIns }).then(() => {
- toIns.forEach(st => {
- kb.add(st)
- })
- })
- })
- return Promise.all(patchPromises)
- .then(() => ({ group }))
- .catch(err => {
- console.log('Could not create new group. PATCH failed ' + err)
- throw new Error(
- `Couldn't create new group. PATCH failed for (${
- err.xhr ? err.xhr.responseURL : ''
- } )`
- )
- })
-}

diff:
// Jest Snapshot v1, https://goo.gl/fbAQLP
-exports[`GroupBuilder.add runs: Promise {} 1`] = `Promise {}`;
+exports[`GroupBuilder.add runs 1`] = `Promise {}`;
-exports[`GroupBuilder.handleRemove runs: [Function] 1`] = `[Function]`;
+exports[`GroupBuilder.handleRemove runs 1`] = `[Function]`;
-exports[`GroupBuilder.render runs:
-GroupBuilder {
- "book": Object {
- "dir": [Function],
- "doc": [Function],
- "elements": Array [],
- "sameTerm": [Function],
- "uri": "uri",
- "value": "",
- },
- "doneBuildingCb": [Function],
- "element":

-

-
- Group Name:
- <input
- type="text"
- />
-
- <button>
- Done
- </button>
-

-
,
- "group": Object {
- "dir": [Function],
- "doc": [Function],
- "elements": Array [],
- "sameTerm": [Function],
- "uri": "uri",
- "value": "",
- },
- "groupChangedCb": [Function],
- "onGroupChanged": [Function],
-}
- 1`] = `
+exports[`GroupBuilder.render runs 1`] = `
GroupBuilder {
"book": Object {
"dir": [Function],
@@ -80,31 +43,15 @@ GroupBuilder {
}
`;
-exports[`GroupBuilder.setGroupName runs: Promise {} 1`] = `Promise {}`;
+exports[`GroupBuilder.setGroupName runs 1`] = `Promise {}`;
-exports[`PeoplePicker.render .. type index ...:
- PeoplePicker {
- "element":

-

-
,
- "groupPickedCb": [Function],
- "onSelectGroup": [Function],
- "options": Object {
- "selectedGroup": Object {},
- },
- "selectedgroup": undefined,
- "typeIndex": "publicTypeIndex",
- }
- 1`] = `
+exports[`PeoplePicker.render .. type index ... 1`] = `
PeoplePicker {
"element":

,
- "findAddressBook": [Function],
"groupPickedCb": [Function],
"onSelectGroup": [Function],
"options": Object {
@@ -115,29 +62,13 @@ PeoplePicker {
}
`;
-exports[`PeoplePicker.render mocking kb any for book:
-PeoplePicker {
- "element":

-

-
,
- "groupPickedCb": [Function],
- "onSelectGroup": [Function],
- "options": Object {
- "selectedGroup": true,
- },
- "selectedgroup": undefined,
- "typeIndex": Object {},
-}
- 1`] = `
+exports[`PeoplePicker.render mocking kb any for book 1`] = `
PeoplePicker {
"element":

,
- "findAddressBook": [Function],
"groupPickedCb": [Function],
"onSelectGroup": [Function],
"options": Object {
@@ -148,7 +79,7 @@ PeoplePicker {
}
`;
-exports[`PeoplePicker.render runs 2:
+exports[`PeoplePicker.render runs 1`] = `
PeoplePicker {
"element":

<div
@@ -158,30 +89,14 @@ exports[`PeoplePicker.render runs 2:
"groupPickedCb": [Function],
"onSelectGroup": [Function],
"options": Object {
- "selectedGroup": true,
- },
- "selectedgroup": undefined,
- "typeIndex": Object {},
- }
- 1`] = `
-PeoplePicker {
- "element":

-

-
,
- "findAddressBook": [Function],
- "groupPickedCb": [Function],
- "onSelectGroup": [Function],
- "options": Object {
- "selectedGroup": true,
+ "selectedGroup": false,
},
"selectedgroup": undefined,
"typeIndex": Object {},
}
`;
-exports[`PeoplePicker.render runs:
+exports[`PeoplePicker.render runs 2 1`] = `
PeoplePicker {
"element":

<div
@@ -191,57 +106,14 @@ exports[`PeoplePicker.render runs:
"groupPickedCb": [Function],
"onSelectGroup": [Function],
"options": Object {
- "selectedGroup": false,
- },
- "selectedgroup": undefined,
- "typeIndex": Object {},
- }
- 1`] = `
-PeoplePicker {
- "element":

-

-
,
- "findAddressBook": [Function],
- "groupPickedCb": [Function],
- "onSelectGroup": [Function],
- "options": Object {
- "selectedGroup": false,
+ "selectedGroup": true,
},
"selectedgroup": undefined,
"typeIndex": Object {},
}
`;
-exports[`Person.render runs:
-Person {
- "element":

-

-
-
- undefined
-
- <button
- style="margin: 5px;"
- >
- Remove
- </button>
-

-
,
- "handleRemove": true,
- "webIdNode":
,
-}
- 1`] = `
+exports[`Person.render runs 1`] = `
Person {
"element":

<div

diff:
@@ -6,8 +6,7 @@ import {
GroupPicker,
Group,
GroupBuilder,
- Person,
- createNewGroup
+ Person
} from '../../../src/widgets/peoplePicker'
import ns from '../../../src/ns'
jest.mock('rdflib')
@@ -96,13 +95,13 @@ describe('FindAddressBook', () => {
// expect(spyOnNowOrWhenFetched).toThrowError()
})
})
-describe('createNewGroup', () => {
+describe('PeoplePicker.createNewGroup', () => {
it('exists', () => {
- expect(createNewGroup).toBeInstanceOf(Function)
+ expect(new PeoplePicker().createNewGroup).toBeInstanceOf(Function)
})
// @@ TODO something about doc within the function has a problem
it.skip('runs', () => {
- expect(createNewGroup(RdfLib.sym('book'))).toMatchInlineSnapshot()
+ expect(new PeoplePicker().createNewGroup(RdfLib.sym('book'))).toMatchSnapshot()
})
})
describe('PeoplePicker', () => {
@@ -126,22 +125,7 @@ describe('PeoplePicker.render', () => {
groupPickedCb,
options
)
- expect(peoplePicker.render()).toMatchSnapshot(`
- PeoplePicker {
- "element":

-

-
,
- "groupPickedCb": [Function],
- "onSelectGroup": [Function],
- "options": Object {
- "selectedGroup": false,
- },
- "selectedgroup": undefined,
- "typeIndex": Object {},
- }
- `)
+ expect(peoplePicker.render()).toMatchSnapshot()
})
it('.. type index ...', () => {
@@ -170,22 +154,7 @@ describe('PeoplePicker.render', () => {
// expect(spySecondAny).toBeCalled()
// expect(spyLoad).toBeCalled()
- expect(peoplePicker.render()).toMatchSnapshot(`
- PeoplePicker {
- "element":

-

-
,
- "groupPickedCb": [Function],
- "onSelectGroup": [Function],
- "options": Object {
- "selectedGroup": Object {},
- },
- "selectedgroup": undefined,
- "typeIndex": "publicTypeIndex",
- }
- `)
+ expect(peoplePicker.render()).toMatchSnapshot()
})
it('create Element is called .. ', () => {
@@ -216,22 +185,7 @@ describe('PeoplePicker.render', () => {
groupPickedCb,
options
)
- expect(peoplePicker.render()).toMatchSnapshot(`
- PeoplePicker {
- "element":

-

-
,
- "groupPickedCb": [Function],
- "onSelectGroup": [Function],
- "options": Object {
- "selectedGroup": true,
- },
- "selectedgroup": undefined,
- "typeIndex": Object {},
- }
- `)
+ expect(peoplePicker.render()).toMatchSnapshot()
})
it('mocking kb any for book', () => {
const mockKbAny: jest.SpyInstance = require('../../../src/store').any
@@ -246,22 +200,7 @@ describe('PeoplePicker.render', () => {
groupPickedCb,
options
)
- expect(peoplePicker.render()).toMatchSnapshot(`
-PeoplePicker {
- "element":

-

-
,
- "groupPickedCb": [Function],
- "onSelectGroup": [Function],
- "options": Object {
- "selectedGroup": true,
- },
- "selectedgroup": undefined,
- "typeIndex": Object {},
-}
-`)
+ expect(peoplePicker.render()).toMatchSnapshot()
})
})
@@ -426,44 +365,7 @@ describe('GroupBuilder.render', () => {
// @@ TODO just trying to touch the code at this point. I want
// to make the test better than toBe(undefined)
expect(groupBuilder.onGroupChanged()).toBe(undefined)
- expect(groupBuilder.render()).toMatchSnapshot(`
-GroupBuilder {
- "book": Object {
- "dir": [Function],
- "doc": [Function],
- "elements": Array [],
- "sameTerm": [Function],
- "uri": "uri",
- "value": "",
- },
- "doneBuildingCb": [Function],
- "element":

-

-
- Group Name:
- <input
- type="text"
- />
-
- <button>
- Done
- </button>
-

-
,
- "group": Object {
- "dir": [Function],
- "doc": [Function],
- "elements": Array [],
- "sameTerm": [Function],
- "uri": "uri",
- "value": "",
- },
- "groupChangedCb": [Function],
- "onGroupChanged": [Function],
-}
-`)
+ expect(groupBuilder.render()).toMatchSnapshot()
})
})
@@ -501,7 +403,7 @@ describe('GroupBuilder.add', () => {
handler,
handler
)
- expect(groupBuilder.add()).toMatchSnapshot(`Promise {}`)
+ expect(groupBuilder.add()).toMatchSnapshot()
})
// need to to nowOrWhenFetched
it('not okay it returns an error -- callback false', () => {
@@ -567,7 +469,7 @@ describe('GroupBuilder.handleRemove', () => {
handler,
handler
)
- expect(groupBuilder.handleRemove()).toMatchSnapshot('[Function]')
+ expect(groupBuilder.handleRemove()).toMatchSnapshot()
})
})
@@ -590,7 +492,7 @@ describe('GroupBuilder.setGroupName', () => {
handler,
handler
)
- expect(groupBuilder.setGroupName()).toMatchSnapshot('Promise {}')
+ expect(groupBuilder.setGroupName()).toMatchSnapshot()
})
})
@@ -610,33 +512,6 @@ describe('Person.render', () => {
const element = document.createElement('div')
const handleRemove = true
const person = new Person(webIdNode, element, handleRemove)
- expect(person.render()).toMatchSnapshot(`
-Person {
- "element":

-

-
-
- undefined
-
- <button
- style="margin: 5px;"
- >
- Remove
- </button>
-

-
,
- "handleRemove": true,
- "webIdNode":
,
-}
-`)
+ expect(person.render()).toMatchSnapshot()
})
})


message: removed prettierrc file

change_type: DELETE

old_path: .prettierrc

diff:
-{
- "arrowParens": "avoid",
- "bracketSpacing": true,
- "htmlWhitespaceSensitivity": "css",
- "insertPragma": false,
- "jsxBracketSameLine": false,
- "jsxSingleQuote": false,
- "printWidth": 80,
- "proseWrap": "preserve",
- "quoteProps": "as-needed",
- "requirePragma": false,
- "semi": false,
- "singleQuote": true,
- "tabWidth": 2,
- "useTabs": false,
- "vueIndentScriptAndStyle": false,
- "space-before-fuction-paren": "always"
-}

original_message: removed prettierrc file


message: changed test should

diff:
@@ -271,7 +271,7 @@ describe('GroupPicker.loadGroups', () => {
const groupPicker = new GroupPicker(container, book, handler)
expect(groupPicker.loadGroups()).toBeTruthy()
})
- it('should....', () => {
+ it('should call nowOrWhenFetched and Each', () => {
const container = RdfLib.sym('')
const book = RdfLib.sym('book')
const handler = () => { }

original_message: changed test should


message: Fixed the preferences test

diff:
exports[`notepad runs 1`] = `

+

+ <input
+ style="font-size: 100%; font-family: monospace; width: 100%; border: none; white-space: pre-wrap;text-indent: 0em;"
+ type="text"
/>
+

+

`;
exports[`notepad status area ... 1`] = `

+

+ <input
+ style="font-size: 100%; font-family: monospace; width: 100%; border: none; white-space: pre-wrap;text-indent: 0em;"
+ type="text"
/>
+

+

`;

diff:
@@ -58,7 +58,7 @@ describe('Preferences.recordSharedPreferences', () => {
it('runs', () => {
const subject = null
const context = null
- expect(Preferences.recordSharedPreferences(subject, context).then())
+ expect(Preferences.recordSharedPreferences(subject, context)).toBeTruthy()
})
})

original_message: Fixed the preferences test


message: Added additionaly styles for the button

diff:
<!DOCTYPE HTML>

+

<meta charset='UTF-8'>
<title>solid-ui UI.widgets.buttons examples page</title>
}
</script>

+

addStyleSheet

-

+

+

allClassURIs

-

+

+

}
});
</script>
-

+

+

attachmentList

UI.widgets.attachmentList(document, UI.rdf.namedNode('https://example-user.inrupt.net/public/some-message.ttl#this'), $('#div-attachmentList'))
})
</script>
-

+

+

button with icon

)
})
</script>
-

+

+

button with text

$('#div-button-with-text').appendChild(
UI.widgets.button(document, undefined, 'test', () => {
window.alert('clicked!')
- })
+ }, { buttonType: 0, filled: false })
)
})
</script>
-

+

+

cancelButton

)
})
</script>
-

+

+

clearElement

}, 1000)
})
</script>
-

+

+

complain

UI.widgets.complain({ div: $('#div-complain'), dom: document }, 'not good!')
})
</script>
-

+

+

continueButton

)
})
</script>
-

+

+

defaultAnnotationStore

$('#div-defaultAnnotationStore').appendChild(document.createTextNode(result.uri))
})
</script>
-

+

+

deleteButtonWithCheck

$('#div-deleteButtonWithCheck').appendChild(result)
})
</script>
-

+

+

extractLogURI

$('#div-extractLogURI').appendChild(document.createTextNode(extracted))
})
</script>
-

+

+

formatDateTime

$('#div-formatDateTime').appendChild(document.createTextNode(result))
})
</script>
-

+

+

faviconOrDefault

$('#div-faviconOrDefault').appendChild(result)
})
</script>
-

+

+

-
fileUploadButtonDiv

+
fileUploadButtonDiv
+

-

+

+

findImage

displayFindImageResult(michiel)
})
</script>
-

+

+

findImageFromURI

displayFindImageFromURIResult('mailto:user@example.com')
})
</script>
-

+

+

iconForClass

$('#div-iconForClass').innerHTML = `<ul>${lines.join('')}</ul>`
})
</script>
-

+

+

imagesOf

})
})
</script>
-

+

+

twoLineTransaction

$('#div-twoLineTransaction').appendChild(result)
})
</script>
-

+

+

twoLineTrip

$('#div-twoLineTrip').appendChild(result)
})
</script>
-

+

+

twoLineWidgetForClass

$('#div-twoLineWidgetForClass').appendChild(widget)
})
</script>
-

+

+

isAudio

$('#div-isAudio').appendChild(document.createTextNode(result))
})
</script>
-

+

+

isImage

$('#div-isImage').appendChild(document.createTextNode(result))
})
</script>
-

+

+

isVideo

$('#div-isVideo').appendChild(document.createTextNode(result))
})
</script>
-

+

+

linkButton

$('#div-linkButton').appendChild(result)
})
</script>
-

+

+

linkIcon

)
})
</script>
-

+

+

openHrefInOutlineMode

$('#div-openHrefInOutlineMode').appendChild(anchor)
})
</script>
-

+

+

personTR

$('#div-personTR').appendChild(result)
})
</script>
-

+

+

propertyTriage

$('#div-propertyTriage').appendChild(document.createTextNode(JSON.stringify(result)))
})
</script>
-

+

+

refreshTree

$('#div-refreshTree').appendChild(refreshable)
})
</script>
-

+

+

removeButton

$('#div-removeButton').appendChild(button)
})
</script>
-

+

+

shortDate

$('#div-shortDate').innerHTML = `<ul><li>${results.join('</li><li>')}</li></ul>`
})
</script>
-

+

+

shortTime

$('#div-shortTime').appendChild(document.createTextNode(result))
})
</script>
-

+

+

selectorPanel

$('#div-selectorPanel').appendChild(result)
})
</script>
-

+

+

selectorPanelRefresh

$('#div-selectorPanelRefresh').appendChild(result)
})
</script>
-

+

+

setImage

$('#div-setImage').appendChild(img)
})
</script>
-

+

+

setName

UI.widgets.setName($('#div-setName'), myTrip)
})
</script>
-

+

+

tempSite

$('#div-tempSite').appendChild(document.createTextNode(result))
})
</script>
-

+

+

timestamp

$('#div-timestamp').appendChild(document.createTextNode(result))
})
</script>
-

+

+

+

\ No newline at end of file

diff:
@@ -27,6 +27,16 @@ export type StatusAreaContext = {
div?: HTMLElement
dom?: HTMLDocument
}
+enum ButtonType {
+ primary,
+ secondary,
+ cancel,
+ continue
+}
+type ButtonWidgetOptions = {
+ buttonType?: ButtonType
+ filled?: boolean
+}
function getStatusArea (context?: StatusAreaContext) {
var box = (context && context.statusArea) || (context && context.div) || null
if (box) return box
@@ -478,6 +488,34 @@ export function deleteButtonWithCheck (
return deleteButtonElt
}
+function getButtonStyle (options: ButtonWidgetOptions) {
+ const color = '#7c4dff'
+
+ const backgroundColor = options.filled ? color : '#ffffff'
+ const fontColor = options.filled ? '#ffffff' : color
+ const borderColor = options.filled ? 'none' : color
+ const hoverBackgroundColor = 'lighten(color, 5%)'
+
+ // See https://design.inrupt.com/atomic-core/?cat=Atoms#Buttons
+ return {
+ 'background-color': `${backgroundColor}`,
+ color: `${fontColor}`,
+ 'font-family': 'Raleway, Roboto, sans-serif',
+ 'border-radius': '0.25em',
+ 'border-color': `${borderColor}`,
+ border: '1px solid',
+ cursor: 'pointer',
+ 'font-size': '.8em',
+ 'text-decoration': 'none',
+ padding: '0.5em 4em',
+ transition: '0.25s all ease-in-out',
+ outline: 'none',
+ '&:hover': {
+ 'background-color': `${hoverBackgroundColor}`,
+ transition: '0.25s all ease-in-out'
+ }
+ }
+}
/* Make a button
*
* @param dom - the DOM document object
@@ -487,7 +525,7 @@ export function deleteButtonWithCheck (
*
* @returns <dDomElement> - the button
*/
-export function button (dom: HTMLDocument, iconURI: string | undefined, text: string, handler: (event: any) => void) {
+export function button (dom: HTMLDocument, iconURI: string | undefined, text: string, handler: (event: any) => void, options: ButtonWidgetOptions) {
var button = dom.createElement('button')
button.setAttribute('type', 'button')
// button.innerHTML = text // later, user preferences may make text preferred for some
@@ -499,25 +537,11 @@ export function button (dom: HTMLDocument, iconURI: string | undefined, text: st
button.setAttribute('style', style.buttonStyle)
} else {
button.innerText = text.toLocaleUpperCase()
+ const style = getButtonStyle(options)
const { classes } = getClasses(dom.head, {
- textButton: { // See https://design.inrupt.com/atomic-core/?cat=Atoms#Buttons
- 'background-color': '#7c4dff',
- color: '#fff',
- 'font-family': 'Raleway, Roboto, sans-serif',
- 'border-radius': '0.25em',
- border: 'none',
- cursor: 'pointer',
- 'font-size': '.8em',
- 'text-decoration': 'none',
- padding: '0.5em 4em',
- transition: '0.25s all ease-in-out',
- outline: 'none',
- '&:hover': {
- 'background-color': '#8f67ff',
- transition: '0.25s all ease-in-out'
- }
- }
+ textButton: style
})
+
button.classList.add(classes.textButton)
}
if (handler) {
@@ -534,7 +558,7 @@ export function button (dom: HTMLDocument, iconURI: string | undefined, text: st
* @returns <dDomElement> - the button
*/
export function cancelButton (dom: HTMLDocument, handler: (event: any) => void) {
- return button(dom, cancelIconURI, 'Cancel', handler)
+ return button(dom, cancelIconURI, 'Cancel', handler, {})
}
/* Make a continue button
@@ -545,7 +569,7 @@ export function cancelButton (dom: HTMLDocument, handler: (event: any) => void)
* @returns <dDomElement> - the button
*/
export function continueButton (dom: HTMLDocument, handler: (event: any) => void) {
- return button(dom, checkIconURI, 'Continue', handler)
+ return button(dom, checkIconURI, 'Continue', handler, {})
}
/* Grab a name for a new thing
@@ -1263,7 +1287,7 @@ export function fileUploadButtonDiv (
'Upload files',
_event => {
input.click()
- }
+ }, {}
)
)
dragAndDrop.makeDropTarget(buttonElt, null, droppedFileHandler) // Can also just drop on button

diff:
@@ -118,7 +118,7 @@ describe('button', () => {
head: {},
createElement: dom.createElement.bind(dom)
}
- expect(button(domCopy as unknown as HTMLDocument, iconURI, text, handler)).toBeTruthy()
+ expect(button(domCopy as unknown as HTMLDocument, iconURI, text, handler, {})).toBeTruthy()
})
})

original_message: Added additionaly styles for the button


message: Refactored button style code

diff:
$('#div-button-with-text').appendChild(
UI.widgets.button(document, undefined, 'test', () => {
window.alert('clicked!')
- }, { buttonType: 0, filled: false })
+ }, { buttonType: UI.widgets.ButtonType.Secondary, filled: true })
)
})
</script>

diff:
@@ -27,14 +27,14 @@ export type StatusAreaContext = {
div?: HTMLElement
dom?: HTMLDocument
}
-enum ButtonType {
- primary,
- secondary,
- cancel,
- continue
-}
-type ButtonWidgetOptions = {
- buttonType?: ButtonType
+export enum ButtonType {
+ Primary = '#7c4dff',
+ Secondary = '#01C9EA',
+ Cancel = '',
+ Continue = ''
+}
+export type ButtonWidgetOptions = {
+ buttonType?: ButtonType,
filled?: boolean
}
function getStatusArea (context?: StatusAreaContext) {
@@ -488,13 +488,20 @@ export function deleteButtonWithCheck (
return deleteButtonElt
}
-function getButtonStyle (options: ButtonWidgetOptions) {
- const color = '#7c4dff'
-
- const backgroundColor = options.filled ? color : '#ffffff'
- const fontColor = options.filled ? '#ffffff' : color
- const borderColor = options.filled ? 'none' : color
- const hoverBackgroundColor = 'lighten(color, 5%)'
+function getButtonStyle (options: ButtonWidgetOptions = { buttonType: ButtonType.Primary, filled: true }) {
+ // We need to accomadate for legacy code, which is why we have to allow buttonType and filled to be optional
+ let backgroundColor: (ButtonType | string | undefined) = options.buttonType
+ let fontColor: (ButtonType | string | undefined) = '#ffffff'
+ let borderColor: (ButtonType | string | undefined) = options.buttonType
+ let hoverBackgroundColor: (ButtonType | string | undefined) = `lighten(${options.buttonType}, 5%)`
+ let hoverFontColor: (ButtonType | string | undefined) = fontColor
+ if (!options.filled) {
+ backgroundColor = '#ffffff'
+ fontColor = options.buttonType
+ borderColor = options.buttonType
+ hoverBackgroundColor = options.buttonType
+ hoverFontColor = backgroundColor
+ }
// See https://design.inrupt.com/atomic-core/?cat=Atoms#Buttons
return {
@@ -512,6 +519,7 @@ function getButtonStyle (options: ButtonWidgetOptions) {
outline: 'none',
'&:hover': {
'background-color': `${hoverBackgroundColor}`,
+ color: `${hoverFontColor}`,
transition: '0.25s all ease-in-out'
}
}
@@ -525,7 +533,7 @@ function getButtonStyle (options: ButtonWidgetOptions) {
*
* @returns <dDomElement> - the button
*/
-export function button (dom: HTMLDocument, iconURI: string | undefined, text: string, handler: (event: any) => void, options: ButtonWidgetOptions) {
+export function button (dom: HTMLDocument, iconURI: string | undefined, text: string, handler: (event: any) => void, options: ButtonWidgetOptions = { buttonType: ButtonType.Primary, filled: true }) {
var button = dom.createElement('button')
button.setAttribute('type', 'button')
// button.innerHTML = text // later, user preferences may make text preferred for some

diff:
@@ -35,7 +35,8 @@ import {
setName,
shortDate,
shortTime,
- timestamp
+ timestamp,
+ ButtonType
} from '../../../src/widgets/buttons'
import { graph, namedNode, NamedNode, sym } from 'rdflib'
import { foaf, rdf, sioc, vcard } from '../../../src/ns'

original_message: Refactored button style code


message: added other button options

diff:
-
button with text

+
button with text

+
+

+
+

+
+
button with text

+
+

+
+

+
+
button with text

+
button with text

+
+

+
+

cancelButton

original_message: added other button options


message: made changes to fix comments in pr

diff:
-
button with text

-
-

-
-

+

+
+

-
button with text

-
-

-
-

+

+
+

-
button with text

-
-

-
-

-
button with text

-
+

+
+
button with
+ text

+
-

-
-

+

+
+

cancelButton

diff:
@@ -22,6 +22,10 @@ const dragAndDrop = require('./dragAndDrop')
const cancelIconURI = iconBase + 'noun_1180156.svg' // black X
const checkIconURI = iconBase + 'noun_1180158.svg' // green checkmark; Continue
+const PRIMARY_COLOR = '#7c4dff'
+const SECONDARY_COLOR = '#01C9EA'
+
+
export type StatusAreaContext = {
statusArea?: HTMLElement
div?: HTMLElement
@@ -34,8 +38,8 @@ export enum ButtonType {
Continue = ''
}
export type ButtonWidgetOptions = {
- buttonType?: ButtonType,
- filled?: boolean
+ buttonColor?: ButtonType,
+ needsBorder?: boolean
}
function getStatusArea (context?: StatusAreaContext) {
var box = (context && context.statusArea) || (context && context.div) || null
@@ -488,18 +492,22 @@ export function deleteButtonWithCheck (
return deleteButtonElt
}
-function getButtonStyle (options: ButtonWidgetOptions = { buttonType: ButtonType.Primary, filled: true }) {
+function getButtonStyle (options: ButtonWidgetOptions = { buttonColor: ButtonType.Primary, needsBorder: false }) {
// We need to accomadate for legacy code, which is why we have to allow buttonType and filled to be optional
- let backgroundColor: (ButtonType | string | undefined) = options.buttonType
- let fontColor: (ButtonType | string | undefined) = '#ffffff'
- let borderColor: (ButtonType | string | undefined) = options.buttonType
- let hoverBackgroundColor: (ButtonType | string | undefined) = `lighten(${options.buttonType}, 5%)`
- let hoverFontColor: (ButtonType | string | undefined) = fontColor
- if (!options.filled) {
+ let color = PRIMARY_COLOR
+ if (options.buttonColor === ButtonType.Secondary) {
+ color = SECONDARY_COLOR
+ }
+ let backgroundColor: string = color
+ let fontColor: string = '#ffffff'
+ let borderColor: string = color
+ let hoverBackgroundColor: string = `lighten(${color}, 5%)`
+ let hoverFontColor: string = fontColor
+ if (options.needsBorder) {
backgroundColor = '#ffffff'
- fontColor = options.buttonType
- borderColor = options.buttonType
- hoverBackgroundColor = options.buttonType
+ fontColor = color
+ borderColor = color
+ hoverBackgroundColor = color
hoverFontColor = backgroundColor
}
@@ -533,7 +541,7 @@ function getButtonStyle (options: ButtonWidgetOptions = { buttonType: ButtonType
*
* @returns <dDomElement> - the button
*/
-export function button (dom: HTMLDocument, iconURI: string | undefined, text: string, handler: (event: any) => void, options: ButtonWidgetOptions = { buttonType: ButtonType.Primary, filled: true }) {
+export function button (dom: HTMLDocument, iconURI: string | undefined, text: string, handler: (event: any) => void, options: ButtonWidgetOptions = { buttonColor: ButtonType.Primary, needsBorder: false }) {
var button = dom.createElement('button')
button.setAttribute('type', 'button')
// button.innerHTML = text // later, user preferences may make text preferred for some
@@ -566,7 +574,7 @@ export function button (dom: HTMLDocument, iconURI: string | undefined, text: st
* @returns <dDomElement> - the button
*/
export function cancelButton (dom: HTMLDocument, handler: (event: any) => void) {
- return button(dom, cancelIconURI, 'Cancel', handler, {})
+ return button(dom, cancelIconURI, 'Cancel', handler)
}
/* Make a continue button
@@ -577,7 +585,7 @@ export function cancelButton (dom: HTMLDocument, handler: (event: any) => void)
* @returns <dDomElement> - the button
*/
export function continueButton (dom: HTMLDocument, handler: (event: any) => void) {
- return button(dom, checkIconURI, 'Continue', handler, {})
+ return button(dom, checkIconURI, 'Continue', handler)
}
/* Grab a name for a new thing

diff:
@@ -119,7 +119,7 @@ describe('button', () => {
head: {},
createElement: dom.createElement.bind(dom)
}
- expect(button(domCopy as unknown as HTMLDocument, iconURI, text, handler, {})).toBeTruthy()
+ expect(button(domCopy as unknown as HTMLDocument, iconURI, text, handler)).toBeTruthy()
})
})

original_message: made changes to fix comments in pr


message: added the hover color

diff:
$('#div-button-with-text-primary-no-border').appendChild(
UI.widgets.button(document, undefined, 'test', () => {
window.alert('clicked!')
- }, { buttonType: UI.widgets.ButtonType.Primary, needsBorder: false })
+ }, { buttonColor: 'Primary', needsBorder: false })
)
})
</script>
$('#div-button-with-text-primary-needs-border').appendChild(
UI.widgets.button(document, undefined, 'test', () => {
window.alert('clicked!')
- }, { buttonType: UI.widgets.ButtonType.Primary, needsBorder: true })
+ }, { buttonColor: 'Primary', needsBorder: true })
)
})
</script>
$('#div-button-with-text-secondary-no-border').appendChild(
UI.widgets.button(document, undefined, 'test', () => {
window.alert('clicked!')
- }, { buttonType: UI.widgets.ButtonType.Secondary, needsBorder: false })
+ }, { buttonColor: 'Secondary', needsBorder: false })
)
})
</script>
$('#div-button-with-text-secondary-needs-border').appendChild(
UI.widgets.button(document, undefined, 'test', () => {
window.alert('clicked!')
- }, { buttonType: UI.widgets.ButtonType.Secondary, needsBorder: true })
+ }, { buttonColor: 'Secondary', needsBorder: true })
)
})
</script>

diff:
@@ -25,18 +25,13 @@ const checkIconURI = iconBase + 'noun_1180158.svg' // green checkmark; Continue
const PRIMARY_COLOR = '#7c4dff'
const SECONDARY_COLOR = '#01C9EA'
-
export type StatusAreaContext = {
statusArea?: HTMLElement
div?: HTMLElement
dom?: HTMLDocument
}
-export enum ButtonType {
- Primary = '#7c4dff',
- Secondary = '#01C9EA',
- Cancel = '',
- Continue = ''
-}
+export type ButtonType = 'Primary' | 'Secondary' | 'Cancel' | 'Continue'
+
export type ButtonWidgetOptions = {
buttonColor?: ButtonType,
needsBorder?: boolean
@@ -492,16 +487,18 @@ export function deleteButtonWithCheck (
return deleteButtonElt
}
-function getButtonStyle (options: ButtonWidgetOptions = { buttonColor: ButtonType.Primary, needsBorder: false }) {
+function getButtonStyle (options: ButtonWidgetOptions = { buttonColor: 'Primary', needsBorder: false }) {
// We need to accomadate for legacy code, which is why we have to allow buttonType and filled to be optional
let color = PRIMARY_COLOR
- if (options.buttonColor === ButtonType.Secondary) {
+ if (options.buttonColor === 'Secondary') {
color = SECONDARY_COLOR
}
let backgroundColor: string = color
let fontColor: string = '#ffffff'
let borderColor: string = color
- let hoverBackgroundColor: string = `lighten(${color}, 5%)`
+ // hoverBackground i used the color picker tool to change the rgb and then find out the hex
+ // lighten is used in design.inrupt.com, but this only works in sass and less
+ let hoverBackgroundColor: string = (options.buttonColor === 'Primary') ? '#9f7dff' : '#37cde6'
let hoverFontColor: string = fontColor
if (options.needsBorder) {
backgroundColor = '#ffffff'
@@ -541,7 +538,7 @@ function getButtonStyle (options: ButtonWidgetOptions = { buttonColor: ButtonTyp
*
* @returns <dDomElement> - the button
*/
-export function button (dom: HTMLDocument, iconURI: string | undefined, text: string, handler: (event: any) => void, options: ButtonWidgetOptions = { buttonColor: ButtonType.Primary, needsBorder: false }) {
+export function button (dom: HTMLDocument, iconURI: string | undefined, text: string, handler: (event: any) => void, options: ButtonWidgetOptions = { buttonColor: 'Primary', needsBorder: false }) {
var button = dom.createElement('button')
button.setAttribute('type', 'button')
// button.innerHTML = text // later, user preferences may make text preferred for some

original_message: added the hover color


message: added all the needed code

diff:
+/*
+ Copied from mashlib/src/global/metadata.ts
+ */
+import { NamedNode, sym } from 'rdflib'
+
+type ThrottleOptions = {
+ leading?: boolean;
+ throttling?: boolean;
+ trailing?: boolean;
+}
+
+export function getPod (): NamedNode {
+ // @@ TODO: This is given that mashlib runs on NSS - might need to change when we want it to run on other Pod servers
+ return sym(document.location.origin).site()
+}
+
+export function throttle (func: Function, wait: number, options: ThrottleOptions = {}): (...args: any[]) => any {
+ let context: any,
+ args: any,
+ result: any
+ let timeout: any = null
+ let previous = 0
+ const later = function () {
+ previous = !options.leading ? 0 : Date.now()
+ timeout = null
+ result = func.apply(context, args)
+ if (!timeout) context = args = null
+ }
+ return function () {
+ const now = Date.now()
+ if (!previous && !options.leading) previous = now
+ const remaining = wait - (now - previous)
+ // @ts-ignore
+ context = this
+ args = arguments
+ if (remaining <= 0 || remaining > wait) {
+ if (timeout) {
+ clearTimeout(timeout)
+ timeout = null
+ }
+ previous = now
+ result = func.apply(context, args)
+ if (!timeout) context = args = null
+ } else if (!timeout && options.trailing !== false) {
+ timeout = setTimeout(later, remaining)
+ }
+ return result
+ }
+}

diff:
+/*
+ This file was copied from mashlib/src/global/header.ts file. It is modified to
+ work in solid-ui by adjusting where imported functions are found.
+ */
+import { IndexedFormula, NamedNode, sym } from 'rdflib'
+import { loginStatusBox, solidAuthClient } from '../authn/authn'
+import { widgets } from '../widgets'
+import { icon } from './icon'
+import { emptyProfile } from './empty-profile'
+import { throttle, getPod } from './headerHelpers'
+import { getOutliner } from 'solid-panes'
+
+// SolidAuthorization, SolidClam, and SolidSession was copied from mashlib/typings/solid-auth-client
+// access_token, client_id, id_token, at_hash had to be converted to camelcase for typescript compatibility
+interface SolidAuthorization {
+ accessToken: string;
+ clientId: string;
+ idToken: string;
+}
+
+interface SolidClaim {
+ atHash: string;
+ aud: string;
+ azp: string;
+ cnf: {
+ jwk: string;
+ };
+ exp: number;
+ iat: number;
+ iss: string;
+ jti: string;
+ nonce: string;
+ sub: string;
+}
+export interface SolidSession {
+ authorization: SolidAuthorization;
+ credentialType: string;
+ idClaims: SolidClaim;
+ idp: string;
+ issuer: string;
+ sessionKey: string;
+ webId: string;
+}
+
+export async function initHeader (store: IndexedFormula) {
+ const header = document.getElementById('PageHeader')
+ if (!header) {
+ return
+ }
+
+ const pod = getPod()
+ solidAuthClient.trackSession(rebuildHeader(header, store, pod))
+}
+
+function rebuildHeader (header: HTMLElement, store: IndexedFormula, pod: NamedNode) {
+ return async (session: SolidSession | null) => {
+ const user = session ? sym(session.webId) : null
+ header.innerHTML = ''
+ header.appendChild(await createBanner(store, pod, user))
+ }
+}
+
+async function createBanner (store: IndexedFormula, pod: NamedNode, user: NamedNode | null): Promise<HTMLElement> {
+ const podLink = document.createElement('a')
+ podLink.href = pod.uri
+ podLink.classList.add('header-banner__link')
+ podLink.innerHTML = icon
+
+ const menu = user
+ ? await createUserMenu(store, user)
+ : createLoginSignUpButtons()
+
+ const banner = document.createElement('div')
+ banner.classList.add('header-banner')
+ banner.appendChild(podLink)
+ banner.appendChild(menu)
+
+ return banner
+}
+
+function createLoginSignUpButtons () {
+ const profileLoginButtonPre = document.createElement('div')
+ profileLoginButtonPre.classList.add('header-banner__login')
+ profileLoginButtonPre.appendChild(loginStatusBox(document, null, {}))
+ return profileLoginButtonPre
+}
+
+async function openDashboardPane (outliner: any, pane: string): Promise<void> {
+ outliner.showDashboard({
+ pane
+ })
+}
+
+function createUserMenuButton (label: string, onClick: EventListenerOrEventListenerObject): HTMLElement {
+ const button = document.createElement('button')
+ button.classList.add('header-user-menu__button')
+ button.addEventListener('click', onClick)
+ button.innerText = label
+ return button
+}
+
+function createUserMenuLink (label: string, href: string): HTMLElement {
+ const link = document.createElement('a')
+ link.classList.add('header-user-menu__link')
+ link.href = href
+ link.innerText = label
+ return link
+}
+
+async function createUserMenu (store: IndexedFormula, user: NamedNode): Promise<HTMLElement> {
+ const fetcher = (<any>store).fetcher
+ if (fetcher) {
+ // Making sure that Profile is loaded before building menu
+ await fetcher.load(user)
+ }
+ const outliner = getOutliner(document)
+
+ const loggedInMenuList = document.createElement('ul')
+ loggedInMenuList.classList.add('header-user-menu__list')
+ loggedInMenuList.appendChild(createUserMenuItem(createUserMenuLink('Show your profile', user.uri)))
+ const menuItems = await getMenuItems(outliner)
+ menuItems.forEach(item => {
+ loggedInMenuList.appendChild(createUserMenuItem(createUserMenuButton(item.label, () => openDashboardPane(outliner, item.tabName || item.paneName))))
+ })
+ loggedInMenuList.appendChild(createUserMenuItem(createUserMenuButton('Log out', () => solidAuthClient.logout())))
+
+ const loggedInMenu = document.createElement('nav')
+ loggedInMenu.classList.add('header-user-menu__navigation-menu')
+ loggedInMenu.setAttribute('aria-hidden', 'true')
+ loggedInMenu.appendChild(loggedInMenuList)
+
+ const loggedInMenuTrigger = document.createElement('button')
+ loggedInMenuTrigger.classList.add('header-user-menu__trigger')
+ loggedInMenuTrigger.type = 'button'
+ const profileImg = getProfileImg(store, user)
+ if (typeof profileImg === 'string') {
+ loggedInMenuTrigger.innerHTML = profileImg
+ } else {
+ loggedInMenuTrigger.appendChild(profileImg)
+ }
+
+ const loggedInMenuContainer = document.createElement('div')
+ loggedInMenuContainer.classList.add('header-banner__user-menu', 'header-user-menu')
+ loggedInMenuContainer.appendChild(loggedInMenuTrigger)
+ loggedInMenuContainer.appendChild(loggedInMenu)
+
+ const throttledMenuToggle = throttle((event: Event) => toggleMenu(event, loggedInMenuTrigger, loggedInMenu), 50)
+ loggedInMenuTrigger.addEventListener('click', throttledMenuToggle)
+ let timer = setTimeout(() => null, 0)
+ loggedInMenuContainer.addEventListener('mouseover', event => {
+ clearTimeout(timer)
+ throttledMenuToggle(event)
+ })
+ loggedInMenuContainer.addEventListener('mouseout', event => {
+ timer = setTimeout(() => throttledMenuToggle(event), 200)
+ })
+
+ return loggedInMenuContainer
+}
+
+function createUserMenuItem (child: HTMLElement): HTMLElement {
+ const menuProfileItem = document.createElement('li')
+ menuProfileItem.classList.add('header-user-menu__list-item')
+ menuProfileItem.appendChild(child)
+ return menuProfileItem
+}
+
+async function getMenuItems (outliner: any): Promise<Array<{
+ paneName: string;
+ tabName?: string;
+ label: string;
+ icon: string;
+}>> {
+ return outliner.getDashboardItems()
+}
+
+function getProfileImg (store: IndexedFormula, user: NamedNode): string | HTMLElement {
+ const profileUrl = widgets.findImage(user)
+ if (!profileUrl) {
+ return emptyProfile
+ }
+ const profileImage = document.createElement('div')
+ profileImage.classList.add('header-user-menu__photo')
+ profileImage.style.backgroundImage = `url("${profileUrl}")`
+ return profileImage
+}
+
+function toggleMenu (event: Event, trigger: HTMLButtonElement, menu: HTMLElement): void {
+ const isExpanded = trigger.getAttribute('aria-expanded') === 'true'
+ const expand = event.type === 'mouseover'
+ const close = event.type === 'mouseout'
+ if ((isExpanded && expand) || (!isExpanded && close)) {
+ return
+ }
+ trigger.setAttribute('aria-expanded', (!isExpanded).toString())
+ menu.setAttribute('aria-hidden', isExpanded.toString())
+}

original_message: added all the needed code


message: forgot to change my name back from testing

diff:
@@ -54,8 +54,7 @@ export async function initHeader (store: IndexedFormula) {
function rebuildHeader (header: HTMLElement, store: IndexedFormula, pod: NamedNode) {
return async (session: SolidSession | null) => {
- // const user = session ? sym(session.webId) : null
- const user = sym('https://sharonstrats.inrupt.net/profile/card#me')
+ const user = session ? sym(session.webId) : null
log(user)
header.innerHTML = ''
header.appendChild(await createBanner(store, pod, user))


message: took out outliner code

diff:
@@ -86,12 +86,6 @@ function createLoginSignUpButtons () {
return profileLoginButtonPre
}
-async function openDashboardPane (outliner: any, pane: string): Promise<void> {
- outliner.showDashboard({
- pane
- })
-}
-
function createUserMenuButton (label: string, onClick: EventListenerOrEventListenerObject): HTMLElement {
const button = document.createElement('button')
button.classList.add('header-user-menu__button')
@@ -114,15 +108,10 @@ async function createUserMenu (store: IndexedFormula, user: NamedNode): Promise<
// Making sure that Profile is loaded before building menu
await fetcher.load(user)
}
- // const outliner = getOutliner(document)
-
const loggedInMenuList = document.createElement('ul')
loggedInMenuList.classList.add('header-user-menu__list')
loggedInMenuList.appendChild(createUserMenuItem(createUserMenuLink('Show your profile', user.uri)))
- /* const menuItems = await getMenuItems(outliner)
- menuItems.forEach(item => {
- loggedInMenuList.appendChild(createUserMenuItem(createUserMenuButton(item.label, () => openDashboardPane(outliner, item.tabName || item.paneName))))
- }) */
+
loggedInMenuList.appendChild(createUserMenuItem(createUserMenuButton('Log out', () => solidAuthClient.logout())))
const loggedInMenu = document.createElement('nav')
@@ -133,12 +122,12 @@ async function createUserMenu (store: IndexedFormula, user: NamedNode): Promise<
const loggedInMenuTrigger = document.createElement('button')
loggedInMenuTrigger.classList.add('header-user-menu__trigger')
loggedInMenuTrigger.type = 'button'
- /* const profileImg = getProfileImg(store, user)
+ const profileImg = getProfileImg(store, user)
if (typeof profileImg === 'string') {
loggedInMenuTrigger.innerHTML = profileImg
} else {
loggedInMenuTrigger.appendChild(profileImg)
- } */
+ }
const loggedInMenuContainer = document.createElement('div')
loggedInMenuContainer.classList.add('header-banner__user-menu', 'header-user-menu')

original_message: took out outliner code


message: fixed error in empty profile

diff:
+
Header

+

+
+

+

\ No newline at end of file

diff:
@@ -42,33 +42,42 @@ export interface SolidSession {
webId: string;
}
-export async function initHeader (store: IndexedFormula) {
+type Menu = {
+ label: string,
+ url: string
+}
+type HeaderOptions = {
+ logo?: string,
+ menuList?: Menu[]
+}
+export async function initHeader (store: IndexedFormula, options: HeaderOptions) {
const header = document.getElementById('PageHeader')
if (!header) {
return
}
const pod = getPod()
- solidAuthClient.trackSession(rebuildHeader(header, store, pod))
+ solidAuthClient.trackSession(rebuildHeader(header, store, pod, options))
}
-function rebuildHeader (header: HTMLElement, store: IndexedFormula, pod: NamedNode) {
+function rebuildHeader (header: HTMLElement, store: IndexedFormula, pod: NamedNode, options: HeaderOptions) {
return async (session: SolidSession | null) => {
const user = session ? sym(session.webId) : null
- log(user)
+ // SAM - don't forget to put in the line above instead of the line below :)
+ // const user = sym('https://sharonstrats.inrupt.net/profile/card#me')
header.innerHTML = ''
- header.appendChild(await createBanner(store, pod, user))
+ header.appendChild(await createBanner(store, pod, user, options))
}
}
-async function createBanner (store: IndexedFormula, pod: NamedNode, user: NamedNode | null): Promise<HTMLElement> {
+async function createBanner (store: IndexedFormula, pod: NamedNode, user: NamedNode | null, options: HeaderOptions): Promise<HTMLElement> {
const podLink = document.createElement('a')
podLink.href = pod.uri
podLink.classList.add('header-banner__link')
podLink.innerHTML = icon
const menu = user
- ? await createUserMenu(store, user)
+ ? await createUserMenu(store, user, options)
: createLoginSignUpButtons()
const banner = document.createElement('div')
@@ -102,7 +111,7 @@ function createUserMenuLink (label: string, href: string): HTMLElement {
return link
}
-async function createUserMenu (store: IndexedFormula, user: NamedNode): Promise<HTMLElement> {
+async function createUserMenu (store: IndexedFormula, user: NamedNode, options: HeaderOptions): Promise<HTMLElement> {
const fetcher = (<any>store).fetcher
if (fetcher) {
// Making sure that Profile is loaded before building menu
@@ -155,20 +164,17 @@ function createUserMenuItem (child: HTMLElement): HTMLElement {
return menuProfileItem
}
-async function getMenuItems (outliner: any): Promise<Array<{
- paneName: string;
- tabName?: string;
- label: string;
- icon: string;
-}>> {
- return outliner.getDashboardItems()
-}
-
function getProfileImg (store: IndexedFormula, user: NamedNode): string | HTMLElement {
+ const profileUrl = null
+ try {
const profileUrl = widgets.findImage(user)
if (!profileUrl) {
return emptyProfile
}
+ } catch {
+ return emptyProfile
+ }
+
const profileImage = document.createElement('div')
profileImage.classList.add('header-user-menu__photo')
profileImage.style.backgroundImage = `url("${profileUrl}")`

original_message: fixed error in empty profile


message: took out my comment

diff:
@@ -63,8 +63,6 @@ export async function initHeader (store: IndexedFormula, options: HeaderOptions)
function rebuildHeader (header: HTMLElement, store: IndexedFormula, pod: NamedNode, options: HeaderOptions) {
return async (session: SolidSession | null) => {
const user = session ? sym(session.webId) : null
- // SAM - don't forget to put in the line above instead of the line below :)
- // const user = sym('https://sharonstrats.inrupt.net/profile/card#me')
header.innerHTML = ''
header.appendChild(await createBanner(store, pod, user, options))
}

original_message: took out my comment


message: fix(authn): workspace message white and file id error

diff:
@@ -1311,8 +1311,8 @@ export function selectWorkspace (
const box = dom.createElement('div')
const context: AuthenticationContext = { me: me, dom: dom, div: box }
- function say (s) {
- box.appendChild(widgets.errorMessageBlock(dom, s))
+ function say (s, background) {
+ box.appendChild(widgets.errorMessageBlock(dom, s, background))
}
function figureOutBase (ws) {
@@ -1362,15 +1362,17 @@ export function selectWorkspace (
// A workspace in a storage in the public profile:
const storages = solidLogicSingleton.store.each(id, ns.space('storage')) // @@ No provenance requirement at the moment
if (w.length === 0 && storages) {
- say(`You don't seem to have any workspaces. You have ${storages.length} storage spaces.`)
+ say(`You don't seem to have any workspaces. You have ${storages.length} storage spaces.`, 'white')
storages.map(function (s: any) {
w = w.concat(solidLogicSingleton.store.each(s, ns.ldp('contains')))
return w
- }).filter(file => ['public', 'private'].includes(file.id().toLowerCase()))
+ }).filter(file => {
+ return (file.id) ? ['public', 'private'].includes(file.id().toLowerCase()) : ''
+ })
}
if (w.length === 1) {
- say(`Workspace used: ${w[0].uri}`) // @@ allow user to see URI
+ say(`Workspace used: ${w[0].uri}`, 'white') // @@ allow user to see URI
newBase = figureOutBase(w[0])
// callbackWS(w[0], newBase)
// } else if (w.length === 0) {


message: jit: Add `NULL` as terminating argv

diff:
@@ -82,8 +82,11 @@ pub(super) fn run_jit(tcx: TyCtxt<'_>) -> ! {
.chain(args.split(" "))
.map(|arg| CString::new(arg).unwrap())
.collect::<Vec<_>>();
- let argv = args.iter().map(|arg| arg.as_ptr()).collect::<Vec<_>>();
- // TODO: Rust doesn't care, but POSIX argv has a NULL sentinel at the end
+ let mut argv = args.iter().map(|arg| arg.as_ptr()).collect::<Vec<_>>();
+
+ // Push a null pointer as a terminating argument. This is required by POSIX and
+ // useful as some dynamic linkers use it as a marker to jump over.
+ argv.push(std::ptr::null());
let ret = f(args.len() as c_int, argv.as_ptr());

license: Apache License 2.0

original_message: jit: Add `NULL` as terminating argv


message: linkage: Change linkage to hidden on non-exported symbols

diff:
@@ -25,7 +25,7 @@ pub(crate) fn get_static_linkage(tcx: TyCtxt<'_>, def_id: DefId) -> Linkage {
if tcx.is_reachable_non_generic(def_id) {
Linkage::Export
} else {
- Linkage::Export // FIXME use Linkage::Hidden
+ Linkage::Hidden
}
}
}


message: FunctionCx: Store reference to CodegenCx instead

diff:
@@ -265,9 +265,7 @@ pub(crate) fn type_sign(ty: Ty<'_>) -> bool {
}
pub(crate) struct FunctionCx<'clif, 'tcx, B: Backend + 'static> {
- // FIXME use a reference to `CodegenCx` instead of `tcx`, `module` and `constants` and `caches`
- pub(crate) tcx: TyCtxt<'tcx>,
- pub(crate) module: &'clif mut Module<B>,
+ pub(crate) codegen_cx: &'clif CodegenCx<'tcx, B>,
pub(crate) global_asm: &'clif mut String,
pub(crate) pointer_type: Type, // Cached from module
@@ -285,7 +283,6 @@ pub(crate) struct FunctionCx<'clif, 'tcx, B: Backend + 'static> {
pub(crate) cold_blocks: EntitySet<Block>,
pub(crate) clif_comments: crate::pretty_clif::CommentWriter,
- pub(crate) constants_cx: &'clif mut crate::constant::ConstantCx,
pub(crate) vtables: &'clif mut FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), DataId>,
pub(crate) source_info_set: indexmap::IndexSet<SourceInfo>,


message: FunctionCx: Replace .module with .codegen_cx.module

diff:
@@ -226,9 +226,9 @@ pub(crate) fn import_function<'tcx>(
impl<'tcx, B: Backend + 'static> FunctionCx<'_, 'tcx, B> {
/// Instance must be monomorphized
pub(crate) fn get_function_ref(&mut self, inst: Instance<'tcx>) -> FuncRef {
- let func_id = import_function(selfcodegen_cx.tcx, self.module, inst);
+ let func_id = import_function(selfcodegen_cx.tcx, selfcodegen_cx.module, inst);
let func_ref = self
- .module
+ codegen_cx.module
.declare_func_in_func(func_id, &mut self.bcx.func);
#[cfg(debug_assertions)]
@@ -250,11 +250,11 @@ pub(crate) fn lib_call(
call_conv: CallConv::triple_default(self.triple()),
};
let func_id = self
- .module
+ codegen_cx.module
.declare_function(&name, Linkage::Import, &sig)
.unwrap();
let func_ref = self
- .module
+ codegen_cx.module
.declare_func_in_func(func_id, &mut self.bcx.func);
let call_inst = self.bcx.ins().call(func_ref, args);
#[cfg(debug_assertions)]

diff:
@@ -81,7 +81,7 @@ pub(crate) fn init_global_lock_constructor(
}
pub(crate) fn lock_global_lock(fx: &mut FunctionCx<'_, '_, impl Backend>) {
- let atomic_mutex = fx.module.declare_data(
+ let atomic_mutex = fxcodegen_cx.module.declare_data(
"__cg_clif_global_atomic_mutex",
Linkage::Import,
true,
@@ -89,24 +89,24 @@ pub(crate) fn lock_global_lock(fx: &mut FunctionCx<'_, '_, impl Backend>) {
None,
).unwrap();
- let pthread_mutex_lock = fx.module.declare_function("pthread_mutex_lock", Linkage::Import, &cranelift_codegen::ir::Signature {
- call_conv: fx.module.target_config().default_call_conv,
+ let pthread_mutex_lock = fxcodegen_cx.module.declare_function("pthread_mutex_lock", Linkage::Import, &cranelift_codegen::ir::Signature {
+ call_conv: fxcodegen_cx.module.target_config().default_call_conv,
params: vec![
- AbiParam::new(fx.module.target_config().pointer_type() /* *mut pthread_mutex_t */),
+ AbiParam::new(fxcodegen_cx.module.target_config().pointer_type() /* *mut pthread_mutex_t */),
],
returns: vec![AbiParam::new(types::I32 /* c_int */)],
}).unwrap();
- let pthread_mutex_lock = fx.module.declare_func_in_func(pthread_mutex_lock, fx.bcx.func);
+ let pthread_mutex_lock = fxcodegen_cx.module.declare_func_in_func(pthread_mutex_lock, fx.bcx.func);
- let atomic_mutex = fx.module.declare_data_in_func(atomic_mutex, fx.bcx.func);
- let atomic_mutex = fx.bcx.ins().global_value(fx.module.target_config().pointer_type(), atomic_mutex);
+ let atomic_mutex = fxcodegen_cx.module.declare_data_in_func(atomic_mutex, fx.bcx.func);
+ let atomic_mutex = fx.bcx.ins().global_value(fxcodegen_cx.module.target_config().pointer_type(), atomic_mutex);
fx.bcx.ins().call(pthread_mutex_lock, &[atomic_mutex]);
}
pub(crate) fn unlock_global_lock(fx: &mut FunctionCx<'_, '_, impl Backend>) {
- let atomic_mutex = fx.module.declare_data(
+ let atomic_mutex = fxcodegen_cx.module.declare_data(
"__cg_clif_global_atomic_mutex",
Linkage::Import,
true,
@@ -114,18 +114,18 @@ pub(crate) fn unlock_global_lock(fx: &mut FunctionCx<'_, '_, impl Backend>) {
None,
).unwrap();
- let pthread_mutex_unlock = fx.module.declare_function("pthread_mutex_unlock", Linkage::Import, &cranelift_codegen::ir::Signature {
- call_conv: fx.module.target_config().default_call_conv,
+ let pthread_mutex_unlock = fxcodegen_cx.module.declare_function("pthread_mutex_unlock", Linkage::Import, &cranelift_codegen::ir::Signature {
+ call_conv: fxcodegen_cx.module.target_config().default_call_conv,
params: vec![
- AbiParam::new(fx.module.target_config().pointer_type() /* *mut pthread_mutex_t */),
+ AbiParam::new(fxcodegen_cx.module.target_config().pointer_type() /* *mut pthread_mutex_t */),
],
returns: vec![AbiParam::new(types::I32 /* c_int */)],
}).unwrap();
- let pthread_mutex_unlock = fx.module.declare_func_in_func(pthread_mutex_unlock, fx.bcx.func);
+ let pthread_mutex_unlock = fxcodegen_cx.module.declare_func_in_func(pthread_mutex_unlock, fx.bcx.func);
- let atomic_mutex = fx.module.declare_data_in_func(atomic_mutex, fx.bcx.func);
- let atomic_mutex = fx.bcx.ins().global_value(fx.module.target_config().pointer_type(), atomic_mutex);
+ let atomic_mutex = fxcodegen_cx.module.declare_data_in_func(atomic_mutex, fx.bcx.func);
+ let atomic_mutex = fx.bcx.ins().global_value(fxcodegen_cx.module.target_config().pointer_type(), atomic_mutex);
fx.bcx.ins().call(pthread_mutex_unlock, &[atomic_mutex]);
}

diff:
@@ -13,8 +13,8 @@ pub(crate) fn trans_fn<'tcx, B: Backend + 'static>(
let mir = tcx.instance_mir(instance.def);
// Declare function
- let (name, sig) = get_function_name_and_sig(tcx, cx.module.isa().triple(), instance, false);
- let func_id = cx.module.declare_function(&name, linkage, &sig).unwrap();
+ let (name, sig) = get_function_name_and_sig(tcx, cxcodegen_cx.module.isa().triple(), instance, false);
+ let func_id = cxcodegen_cx.module.declare_function(&name, linkage, &sig).unwrap();
// Make FunctionBuilder
let context = &mut cx.cached_context;
@@ -30,12 +30,12 @@ pub(crate) fn trans_fn<'tcx, B: Backend + 'static>(
let block_map: IndexVec<BasicBlock, Block> = (0..mir.basic_blocks().len()).map(|_| bcx.create_block()).collect();
// Make FunctionCx
- let pointer_type = cx.module.target_config().pointer_type();
+ let pointer_type = cxcodegen_cx.module.target_config().pointer_type();
let clif_comments = crate::pretty_clif::CommentWriter::new(tcx, instance);
let mut fx = FunctionCx {
tcx,
- module: &mut cx.module,
+ module: &mut cxcodegen_cx.module,
global_asm: &mut cx.global_asm,
pointer_type,
@@ -98,10 +98,10 @@ pub(crate) fn trans_fn<'tcx, B: Backend + 'static>(
// instruction, which doesn't have an encoding.
context.compute_cfg();
context.compute_domtree();
- context.eliminate_unreachable_code(cx.module.isa()).unwrap();
+ context.eliminate_unreachable_code(cxcodegen_cx.module.isa()).unwrap();
// Define function
- let module = &mut cx.module;
+ let module = &mut cxcodegen_cx.module;
tcx.sess.time(
"define function",
|| module.define_function(
@@ -115,14 +115,14 @@ pub(crate) fn trans_fn<'tcx, B: Backend + 'static>(
crate::pretty_clif::write_clif_file(
cxcodegen_cx.tcx,
"opt",
- Some(cx.module.isa()),
+ Some(cxcodegen_cx.module.isa()),
instance,
&context,
&clif_comments,
);
// Define debuginfo for function
- let isa = cx.module.isa();
+ let isa = cxcodegen_cx.module.isa();
let debug_context = &mut cx.debug_context;
let unwind_context = &mut cx.unwind_context;
tcx.sess.time("generate debug info", || {

diff:
@@ -395,7 +395,7 @@ pub(crate) fn get_caller_location(&mut self, span: Span) -> CValue<'tcx> {
}
pub(crate) fn triple(&self) -> &target_lexicon::Triple {
- self.module.isa().triple()
+ selfcodegen_cx.module.isa().triple()
}
pub(crate) fn anonymous_str(&mut self, prefix: &str, msg: &str) -> Value {
@@ -408,7 +408,7 @@ pub(crate) fn anonymous_str(&mut self, prefix: &str, msg: &str) -> Value {
let mut data_ctx = DataContext::new();
data_ctx.define(msg.as_bytes().to_vec().into_boxed_slice());
let msg_id = self
- .module
+ codegen_cx.module
.declare_data(
&format!("__{}_{:08x}", prefix, msg_hash),
Linkage::Local,
@@ -419,9 +419,9 @@ pub(crate) fn anonymous_str(&mut self, prefix: &str, msg: &str) -> Value {
.unwrap();
// Ignore DuplicateDefinition error, as the data will be the same
- let _ = self.module.define_data(msg_id, &data_ctx);
+ let _ = selfcodegen_cx.module.define_data(msg_id, &data_ctx);
- let local_msg_id = self.module.declare_data_in_func(msg_id, self.bcx.func);
+ let local_msg_id = selfcodegen_cx.module.declare_data_in_func(msg_id, self.bcx.func);
#[cfg(debug_assertions)]
{
self.add_comment(local_msg_id, msg);

diff:
@@ -67,8 +67,8 @@ pub(crate) fn codegen_tls_ref<'tcx>(
def_id: DefId,
layout: TyAndLayout<'tcx>,
) -> CValue<'tcx> {
- let data_id = data_id_for_static(fxcodegen_cx.tcx, fx.module, def_id, false);
- let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
+ let data_id = data_id_for_static(fxcodegen_cx.tcx, fxcodegen_cx.module, def_id, false);
+ let local_data_id = fxcodegen_cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
#[cfg(debug_assertions)]
fx.add_comment(local_data_id, format!("tls {:?}", def_id));
let tls_ptr = fx.bcx.ins().tls_value(fx.pointer_type, local_data_id);
@@ -80,8 +80,8 @@ fn codegen_static_ref<'tcx>(
def_id: DefId,
layout: TyAndLayout<'tcx>,
) -> CPlace<'tcx> {
- let data_id = data_id_for_static(fxcodegen_cx.tcx, fx.module, def_id, false);
- let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
+ let data_id = data_id_for_static(fxcodegen_cx.tcx, fxcodegen_cx.module, def_id, false);
+ let local_data_id = fxcodegen_cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
#[cfg(debug_assertions)]
fx.add_comment(local_data_id, format!("{:?}", def_id));
let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
@@ -168,21 +168,21 @@ pub(crate) fn trans_const_value<'tcx>(
let base_addr = match alloc_kind {
Some(GlobalAlloc::Memory(alloc)) => {
fx.constants_cx.todo.push(TodoItem::Alloc(ptr.alloc_id));
- let data_id = data_id_for_alloc_id(fx.module, ptr.alloc_id, alloc.align, alloc.mutability);
- let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
+ let data_id = data_id_for_alloc_id(fxcodegen_cx.module, ptr.alloc_id, alloc.align, alloc.mutability);
+ let local_data_id = fxcodegen_cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
#[cfg(debug_assertions)]
fx.add_comment(local_data_id, format!("{:?}", ptr.alloc_id));
fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
}
Some(GlobalAlloc::Function(instance)) => {
- let func_id = crate::abi::import_function(fxcodegen_cx.tcx, fx.module, instance);
- let local_func_id = fx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
+ let func_id = crate::abi::import_function(fxcodegen_cx.tcx, fxcodegen_cx.module, instance);
+ let local_func_id = fxcodegen_cx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
}
Some(GlobalAlloc::Static(def_id)) => {
assert!(fxcodegen_cx.tcx.is_static(def_id));
- let data_id = data_id_for_static(fxcodegen_cx.tcx, fx.module, def_id, false);
- let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
+ let data_id = data_id_for_static(fxcodegen_cx.tcx, fxcodegen_cx.module, def_id, false);
+ let local_data_id = fxcodegen_cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
#[cfg(debug_assertions)]
fx.add_comment(local_data_id, format!("{:?}", def_id));
fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
@@ -217,9 +217,9 @@ fn pointer_for_allocation<'tcx>(
) -> crate::pointer::Pointer {
let alloc_id = fxcodegen_cx.tcx.create_memory_alloc(alloc);
fx.constants_cx.todo.push(TodoItem::Alloc(alloc_id));
- let data_id = data_id_for_alloc_id(fx.module, alloc_id, alloc.align, alloc.mutability);
+ let data_id = data_id_for_alloc_id(fxcodegen_cx.module, alloc_id, alloc.align, alloc.mutability);
- let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
+ let local_data_id = fxcodegen_cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
#[cfg(debug_assertions)]
fx.add_comment(local_data_id, format!("{:?}", alloc_id));
let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);

diff:
@@ -38,9 +38,9 @@ fn codegen_mono_items<'tcx>(
match mono_item {
MonoItem::Fn(instance) => {
let (name, sig) =
- get_function_name_and_sig(cxcodegen_cx.tcx, cx.module.isa().triple(), instance, false);
+ get_function_name_and_sig(cxcodegen_cx.tcx, cxcodegen_cx.module.isa().triple(), instance, false);
let linkage = crate::linkage::get_clif_linkage(mono_item, linkage, visibility);
- cx.module.declare_function(&name, linkage, &sig).unwrap();
+ cxcodegen_cx.module.declare_function(&name, linkage, &sig).unwrap();
}
MonoItem::Static(_) | MonoItem::GlobalAsm(_) => {}
}

diff:
@@ -169,12 +169,12 @@ fn call_inline_asm<'tcx>(
#[cfg(debug_assertions)]
fx.add_comment(stack_slot, "inline asm scratch slot");
- let inline_asm_func = fx.module.declare_function(asm_name, Linkage::Import, &Signature {
+ let inline_asm_func = fxcodegen_cx.module.declare_function(asm_name, Linkage::Import, &Signature {
call_conv: CallConv::SystemV,
params: vec![AbiParam::new(fx.pointer_type)],
returns: vec![],
}).unwrap();
- let inline_asm_func = fx.module.declare_func_in_func(inline_asm_func, &mut fx.bcx.func);
+ let inline_asm_func = fxcodegen_cx.module.declare_func_in_func(inline_asm_func, &mut fx.bcx.func);
#[cfg(debug_assertions)]
fx.add_comment(inline_asm_func, asm_name);

diff:
@@ -494,10 +494,10 @@ pub(crate) fn codegen_intrinsic_call<'tcx>(
if intrinsic.contains("nonoverlapping") {
// FIXME emit_small_memcpy
- fx.bcx.call_memcpy(fx.module.target_config(), dst, src, byte_amount);
+ fx.bcx.call_memcpy(fxcodegen_cx.module.target_config(), dst, src, byte_amount);
} else {
// FIXME emit_small_memmove
- fx.bcx.call_memmove(fx.module.target_config(), dst, src, byte_amount);
+ fx.bcx.call_memmove(fxcodegen_cx.module.target_config(), dst, src, byte_amount);
}
};
// NOTE: the volatile variants have src and dst swapped
@@ -513,10 +513,10 @@ pub(crate) fn codegen_intrinsic_call<'tcx>(
// FIXME make the copy actually volatile when using emit_small_mem{cpy,move}
if intrinsic.contains("nonoverlapping") {
// FIXME emit_small_memcpy
- fx.bcx.call_memcpy(fx.module.target_config(), dst, src, byte_amount);
+ fx.bcx.call_memcpy(fxcodegen_cx.module.target_config(), dst, src, byte_amount);
} else {
// FIXME emit_small_memmove
- fx.bcx.call_memmove(fx.module.target_config(), dst, src, byte_amount);
+ fx.bcx.call_memmove(fxcodegen_cx.module.target_config(), dst, src, byte_amount);
}
};
discriminant_value, (c ptr) {
@@ -680,7 +680,7 @@ pub(crate) fn codegen_intrinsic_call<'tcx>(
let dst_ptr = dst.load_scalar(fx);
// FIXME make the memset actually volatile when switching to emit_small_memset
// FIXME use emit_small_memset
- fx.bcx.call_memset(fx.module.target_config(), dst_ptr, val, count);
+ fx.bcx.call_memset(fxcodegen_cx.module.target_config(), dst_ptr, val, count);
};
ctlz | ctlz_nonzero, <T> (v arg) {
// FIXME trap on `ctlz_nonzero` with zero arg.

diff:
@@ -160,8 +160,8 @@ fn new(
}
fn finalize(mut self) -> (Module<B>, String, Option<DebugContext<'tcx>>, UnwindContext<'tcx>) {
- self.constants_cx.finalize(selfcodegen_cx.tcx, &mut self.module);
- (self.module, self.global_asm, self.debug_context, self.unwind_context)
+ self.constants_cx.finalize(selfcodegen_cx.tcx, &mut selfcodegen_cx.module);
+ (selfcodegen_cx.module, self.global_asm, self.debug_context, self.unwind_context)
}
}

diff:
fn codegen_print(fx: &mut FunctionCx<'_, '_, impl cranelift_module::Backend>, msg: &str) {
let puts = fx
- .module
+ codegen_cx.module
.declare_function(
"puts",
Linkage::Import,
@@ -13,7 +13,7 @@ fn codegen_print(fx: &mut FunctionCx<'_, '_, impl cranelift_module::Backend>, ms
},
)
.unwrap();
- let puts = fx.module.declare_func_in_func(puts, &mut fx.bcx.func);
+ let puts = fxcodegen_cx.module.declare_func_in_func(puts, &mut fx.bcx.func);
#[cfg(debug_assertions)]
{
fx.add_comment(puts, "puts");

diff:
@@ -595,7 +595,7 @@ fn transmute_value<'tcx>(
let src_align = src_layout.align.abi.bytes() as u8;
let dst_align = dst_layout.align.abi.bytes() as u8;
fx.bcx.emit_small_memory_copy(
- fx.module.target_config(),
+ fxcodegen_cx.module.target_config(),
to_addr,
from_addr,
size,

diff:
@@ -80,7 +80,7 @@ pub(crate) fn get_vtable<'tcx>(
data_id
};
- let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
+ let local_data_id = fxcodegen_cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
}
@@ -93,7 +93,7 @@ fn build_vtable<'tcx>(
let usize_size = fx.layout_of(fxcodegen_cx.tcx.types.usize).size.bytes() as usize;
let drop_in_place_fn =
- import_function(tcx, fx.module, Instance::resolve_drop_in_place(tcx, layout.ty).polymorphize(fxcodegen_cx.tcx));
+ import_function(tcx, fxcodegen_cx.module, Instance::resolve_drop_in_place(tcx, layout.ty).polymorphize(fxcodegen_cx.tcx));
let mut components: Vec<_> = vec![Some(drop_in_place_fn), None, None];
@@ -108,7 +108,7 @@ fn build_vtable<'tcx>(
opt_mth.map_or(None, |(def_id, substs)| {
Some(import_function(
tcx,
- fx.module,
+ fxcodegen_cx.module,
Instance::resolve_for_vtable(tcx, ParamEnv::reveal_all(), def_id, substs).unwrap().polymorphize(fxcodegen_cx.tcx),
))
})
@@ -127,13 +127,13 @@ fn build_vtable<'tcx>(
for (i, component) in components.into_iter().enumerate() {
if let Some(func_id) = component {
- let func_ref = fx.module.declare_func_in_data(func_id, &mut data_ctx);
+ let func_ref = fxcodegen_cx.module.declare_func_in_data(func_id, &mut data_ctx);
data_ctx.write_function_addr((i * usize_size) as u32, func_ref);
}
}
let data_id = fx
- .module
+ codegen_cx.module
.declare_data(
&format!(
"__vtable.{}.for.{:?}.{}",
@@ -159,7 +159,7 @@ fn build_vtable<'tcx>(
)
.unwrap();
- fx.module.define_data(data_id, &data_ctx).unwrap();
+ fxcodegen_cx.module.define_data(data_id, &data_ctx).unwrap();
data_id
}


message: FunctionCx: WIP: Replace .constants with codegen_cx.constants

diff:
@@ -49,7 +49,7 @@ pub(crate) fn trans_fn<'tcx, B: Backend + 'static>(
cold_blocks: EntitySet::new(),
clif_comments,
- constants_cx: &mut cx.constants_cx,
+ constants_cx: &mut cxcodegen_cx.constants_cx,
vtables: &mut cx.vtables,
source_info_set: indexmap::IndexSet::new(),
next_ssa_var: 0,

diff:
@@ -167,7 +167,7 @@ pub(crate) fn trans_const_value<'tcx>(
let alloc_kind = fxcodegen_cx.tcx.get_global_alloc(ptr.alloc_id);
let base_addr = match alloc_kind {
Some(GlobalAlloc::Memory(alloc)) => {
- fx.constants_cx.todo.push(TodoItem::Alloc(ptr.alloc_id));
+ fxcodegen_cx.constants_cx.todo.push(TodoItem::Alloc(ptr.alloc_id));
let data_id = data_id_for_alloc_id(fxcodegen_cx.module, ptr.alloc_id, alloc.align, alloc.mutability);
let local_data_id = fxcodegen_cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
#[cfg(debug_assertions)]
@@ -216,7 +216,7 @@ fn pointer_for_allocation<'tcx>(
alloc: &'tcx Allocation,
) -> crate::pointer::Pointer {
let alloc_id = fxcodegen_cx.tcx.create_memory_alloc(alloc);
- fx.constants_cx.todo.push(TodoItem::Alloc(alloc_id));
+ fxcodegen_cx.constants_cx.todo.push(TodoItem::Alloc(alloc_id));
let data_id = data_id_for_alloc_id(fxcodegen_cx.module, alloc_id, alloc.align, alloc.mutability);
let local_data_id = fxcodegen_cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);

diff:
@@ -88,7 +88,7 @@ fn trans_mono_item<'tcx, B: Backend + 'static>(
cxcodegen_cx.tcx.sess.time("codegen fn", || crate::base::trans_fn(cx, inst, linkage));
}
MonoItem::Static(def_id) => {
- crate::constant::codegen_static(&mut cx.constants_cx, def_id);
+ crate::constant::codegen_static(&mut cxcodegen_cx.constants_cx, def_id);
}
MonoItem::GlobalAsm(hir_id) => {
let item = tcx.hir().expect_item(hir_id);

diff:
@@ -160,7 +160,7 @@ fn new(
}
fn finalize(mut self) -> (Module<B>, String, Option<DebugContext<'tcx>>, UnwindContext<'tcx>) {
- self.constants_cx.finalize(selfcodegen_cx.tcx, &mut selfcodegen_cx.module);
+ selfcodegen_cx.constants_cx.finalize(selfcodegen_cx.tcx, &mut selfcodegen_cx.module);
(selfcodegen_cx.module, self.global_asm, self.debug_context, self.unwind_context)
}
}


message: FunctionCx: WIP: Fix overzealous sed usage

diff:
@@ -49,7 +49,7 @@ pub(crate) fn trans_fn<'tcx, B: Backend + 'static>(
cold_blocks: EntitySet::new(),
clif_comments,
- constants_cx: &mut cx.codegen_cx.constants_cx,
+ constants_cx: &mut cx.constants_cx,
vtables: &mut cx.vtables,
source_info_set: indexmap::IndexSet::new(),
next_ssa_var: 0,

diff:
@@ -265,7 +265,7 @@ pub(crate) fn type_sign(ty: Ty<'_>) -> bool {
}
pub(crate) struct FunctionCx<'clif, 'tcx, B: Backend + 'static> {
- pub(crate) .codegen_cx: &'clif CodegenCx<'tcx, B>,
+ pub(crate) codegen_cx: &'clif mut crate::CodegenCx<'tcx, B>,
pub(crate) global_asm: &'clif mut String,
pub(crate) pointer_type: Type, // Cached from module

diff:
@@ -167,7 +167,7 @@ pub(crate) fn trans_const_value<'tcx>(
let alloc_kind = fx.codegen_cx.tcx.get_global_alloc(ptr.alloc_id);
let base_addr = match alloc_kind {
Some(GlobalAlloc::Memory(alloc)) => {
- fx.codegen_cx.constants_cx.todo.push(TodoItem::Alloc(ptr.alloc_id));
+ fx.constants_cx.todo.push(TodoItem::Alloc(ptr.alloc_id));
let data_id = data_id_for_alloc_id(fx.codegen_cx.module, ptr.alloc_id, alloc.align, alloc.mutability);
let local_data_id = fx.codegen_cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
#[cfg(debug_assertions)]
@@ -216,7 +216,7 @@ fn pointer_for_allocation<'tcx>(
alloc: &'tcx Allocation,
) -> crate::pointer::Pointer {
let alloc_id = fx.codegen_cx.tcx.create_memory_alloc(alloc);
- fx.codegen_cx.constants_cx.todo.push(TodoItem::Alloc(alloc_id));
+ fx.constants_cx.todo.push(TodoItem::Alloc(alloc_id));
let data_id = data_id_for_alloc_id(fx.codegen_cx.module, alloc_id, alloc.align, alloc.mutability);
let local_data_id = fx.codegen_cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);

diff:
@@ -88,7 +88,7 @@ fn trans_mono_item<'tcx, B: Backend + 'static>(
cx.codegen_cx.tcx.sess.time("codegen fn", || crate::base::trans_fn(cx, inst, linkage));
}
MonoItem::Static(def_id) => {
- crate::constant::codegen_static(&mut cx.codegen_cx.constants_cx, def_id);
+ crate::constant::codegen_static(&mut cx.constants_cx, def_id);
}
MonoItem::GlobalAsm(hir_id) => {
let item = tcx.hir().expect_item(hir_id);

diff:
@@ -160,7 +160,7 @@ fn new(
}
fn finalize(mut self) -> (Module<B>, String, Option<DebugContext<'tcx>>, UnwindContext<'tcx>) {
- self.codegen_cx.constants_cx.finalize(self.codegen_cx.tcx, &mut self.codegen_cx.module);
+ self.constants_cx.finalize(self.codegen_cx.tcx, &mut self.codegen_cx.module);
(self.codegen_cx.module, self.global_asm, self.debug_context, self.unwind_context)
}
}